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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1490  ! raeburn     4: # $Id: lonnet.pm,v 1.1489 2022/09/08 01:41:15 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.1073    raeburn  1381: sub can_host_session {
1.1074    raeburn  1382:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1383:     my $canhost = 1;
1.1074    raeburn  1384:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1385:     if (ref($remotesessions) eq 'HASH') {
                   1386:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1387:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1388:                 $canhost = 0;
                   1389:             } else {
                   1390:                 $canhost = 1;
                   1391:             }
                   1392:         }
                   1393:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1394:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1395:                 $canhost = 1;
                   1396:             } else {
                   1397:                 $canhost = 0;
                   1398:             }
                   1399:         }
                   1400:         if ($canhost) {
                   1401:             if ($remotesessions->{'version'} ne '') {
                   1402:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1403:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1404:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1405:                         my $major = $1;
                   1406:                         my $minor = $2;
                   1407:                         if (($major < $reqmajor ) ||
                   1408:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1409:                             $canhost = 0;
                   1410:                         }
                   1411:                     } else {
                   1412:                         $canhost = 0;
                   1413:                     }
                   1414:                 }
                   1415:             }
                   1416:         }
                   1417:     }
                   1418:     if ($canhost) {
                   1419:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1420:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1421:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1422:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1423:                 if (($uint_dom ne '') && 
                   1424:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1425:                     $canhost = 0;
                   1426:                 } else {
                   1427:                     $canhost = 1;
                   1428:                 }
                   1429:             }
                   1430:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1431:                 if (($uint_dom ne '') && 
                   1432:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1433:                     $canhost = 1;
                   1434:                 } else {
                   1435:                     $canhost = 0;
                   1436:                 }
                   1437:             }
                   1438:         }
                   1439:     }
                   1440:     return $canhost;
                   1441: }
                   1442: 
1.1083    raeburn  1443: sub spare_can_host {
                   1444:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1445:     my $canhost=1;
1.1279    raeburn  1446:     my $try_server_hostname = &hostname($try_server);
                   1447:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1448:     my $serverhomedom = &host_domain($serverhomeID);
                   1449:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1450:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1451:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1452:             $canhost = 0;
                   1453:         }
                   1454:     }
1.1439    raeburn  1455:     if ($canhost) {
                   1456:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
                   1457:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
                   1458:                 unless (&shared_institution($udom,$try_server)) {
                   1459:                     $canhost = 0;
                   1460:                 }
                   1461:             }
                   1462:         }
                   1463:     }
1.1279    raeburn  1464:     if (($canhost) && ($uint_dom)) {
                   1465:         my @intdoms;
                   1466:         my $internet_names = &get_internet_names($try_server);
                   1467:         if (ref($internet_names) eq 'ARRAY') {
                   1468:             @intdoms = @{$internet_names};
                   1469:         }
                   1470:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1471:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1472:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1473:                                          $remotesessions,
                   1474:                                          $defdomdefaults{'hostedsessions'});
                   1475:         }
1.1083    raeburn  1476:     }
                   1477:     return $canhost;
                   1478: }
                   1479: 
1.1123    raeburn  1480: sub this_host_spares {
                   1481:     my ($dom) = @_;
1.1126    raeburn  1482:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1483:     my @hosts = &current_machine_ids();
                   1484:     foreach my $lonhost (@hosts) {
                   1485:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1486:             $dom_in_use = $dom;
                   1487:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1488:             last;
                   1489:         }
                   1490:     }
1.1126    raeburn  1491:     if ($dom_in_use ne '') {
                   1492:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1493:     }
                   1494:     if (ref($result) ne 'HASH') {
                   1495:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1496:         $dom_in_use = &host_domain($lonhost_in_use);
                   1497:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1498:         if (ref($result) ne 'HASH') {
                   1499:             $result = \%spareid;
                   1500:         }
                   1501:     }
                   1502:     return $result;
                   1503: }
                   1504: 
                   1505: sub spares_for_offload  {
                   1506:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1507:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1508:     if (defined($cached)) {
                   1509:         return $result;
                   1510:     } else {
1.1126    raeburn  1511:         my $cachetime = 60*60*24;
                   1512:         my %domconfig =
                   1513:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1514:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1515:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1516:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1517:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1518:                 }
                   1519:             }
                   1520:         }
                   1521:     }
1.1126    raeburn  1522:     return;
1.1123    raeburn  1523: }
                   1524: 
1.1129    raeburn  1525: sub get_lonbalancer_config {
                   1526:     my ($servers) = @_;
                   1527:     my ($currbalancer,$currtargets);
                   1528:     if (ref($servers) eq 'HASH') {
                   1529:         foreach my $server (keys(%{$servers})) {
                   1530:             my %what = (
                   1531:                          spareid => 1,
                   1532:                          perlvar => 1,
                   1533:                        );
                   1534:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1535:             if ($result eq 'ok') {
                   1536:                 if (ref($returnhash) eq 'HASH') {
                   1537:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1538:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1539:                             $currbalancer = $server;
                   1540:                             $currtargets = {};
                   1541:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1542:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1543:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1544:                                 }
                   1545:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1546:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1547:                                 }
                   1548:                             }
                   1549:                             last;
                   1550:                         }
                   1551:                     }
                   1552:                 }
                   1553:             }
                   1554:         }
                   1555:     }
                   1556:     return ($currbalancer,$currtargets);
                   1557: }
                   1558: 
                   1559: sub check_loadbalancing {
1.1331    raeburn  1560:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1561:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391    raeburn  1562:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129    raeburn  1563:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1564:     my @hosts = &current_machine_ids();
1.1129    raeburn  1565:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1566:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1567:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1568:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1569:     my $domneedscache;
1.1129    raeburn  1570:     my $cachetime = 60*60*24;
                   1571: 
                   1572:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1573:         $dom_in_use = $udom;
                   1574:         $homeintdom = 1;
                   1575:     } else {
                   1576:         $dom_in_use = $serverhomedom;
                   1577:     }
                   1578:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1579:     unless (defined($cached)) {
                   1580:         my %domconfig =
                   1581:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1582:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1583:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1584:         } else {
                   1585:             $domneedscache = $dom_in_use;
1.1129    raeburn  1586:         }
                   1587:     }
                   1588:     if (ref($result) eq 'HASH') {
1.1391    raeburn  1589:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1590:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1591:         if ($is_balancer) {
                   1592:             if (ref($currrules) eq 'HASH') {
                   1593:                 if ($homeintdom) {
                   1594:                     if ($uname ne '') {
                   1595:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1596:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1597:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1598:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1599:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1600:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1601:                             }
                   1602:                         }
                   1603:                         if ($rule_in_effect eq '') {
                   1604:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1605:                             if ($userenv{'inststatus'} ne '') {
                   1606:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1607:                                 my ($othertitle,$usertypes,$types) =
                   1608:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1609:                                 if (ref($types) eq 'ARRAY') {
                   1610:                                     foreach my $type (@{$types}) {
                   1611:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1612:                                             if (exists($currrules->{$type})) {
                   1613:                                                 $rule_in_effect = $currrules->{$type};
                   1614:                                             }
                   1615:                                         }
                   1616:                                     }
                   1617:                                 }
                   1618:                             } else {
                   1619:                                 if (exists($currrules->{'default'})) {
                   1620:                                     $rule_in_effect = $currrules->{'default'};
                   1621:                                 }
                   1622:                             }
                   1623:                         }
                   1624:                     } else {
                   1625:                         if (exists($currrules->{'default'})) {
                   1626:                             $rule_in_effect = $currrules->{'default'};
                   1627:                         }
                   1628:                     }
                   1629:                 } else {
                   1630:                     if ($currrules->{'_LC_external'} ne '') {
                   1631:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1632:                     }
                   1633:                 }
                   1634:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1635:                                                        $uname,$udom);
                   1636:             }
                   1637:         }
                   1638:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1639:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1640:         unless (defined($cached)) {
                   1641:             my %domconfig =
                   1642:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1643:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1644:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1645:             } else {
                   1646:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1647:             }
                   1648:         }
                   1649:         if (ref($result) eq 'HASH') {
1.1391    raeburn  1650:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1651:                 &check_balancer_result($result,@hosts);
                   1652:             if ($is_balancer) {
1.1129    raeburn  1653:                 if (ref($currrules) eq 'HASH') {
                   1654:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1655:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1656:                     }
                   1657:                 }
                   1658:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1659:                                                        $uname,$udom);
                   1660:             }
                   1661:         } else {
                   1662:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1663:                 $is_balancer = 1;
                   1664:                 $offloadto = &this_host_spares($dom_in_use);
                   1665:             }
1.1307    raeburn  1666:             unless (defined($cached)) {
                   1667:                 $domneedscache = $serverhomedom;
                   1668:             }
1.1129    raeburn  1669:         }
                   1670:     } else {
                   1671:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1672:             $is_balancer = 1;
                   1673:             $offloadto = &this_host_spares($dom_in_use);
                   1674:         }
1.1307    raeburn  1675:         unless (defined($cached)) {
                   1676:             $domneedscache = $serverhomedom;
                   1677:         }
                   1678:     }
                   1679:     if ($domneedscache) {
                   1680:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1681:     }
1.1430    raeburn  1682:     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1176    raeburn  1683:         my $lowest_load = 30000;
                   1684:         if (ref($offloadto) eq 'HASH') {
                   1685:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1686:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1687:                     ($otherserver,$lowest_load) =
                   1688:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1689:                 }
1.1129    raeburn  1690:             }
1.1176    raeburn  1691:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1692: 
1.1176    raeburn  1693:             if (!$found_server) {
                   1694:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1695:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1696:                         ($otherserver,$lowest_load) =
                   1697:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1698:                     }
                   1699:                 }
                   1700:             }
                   1701:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1702:             if (@{$offloadto} == 1) {
                   1703:                 $otherserver = $offloadto->[0];
                   1704:             } elsif (@{$offloadto} > 1) {
                   1705:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1706:                     ($otherserver,$lowest_load) =
                   1707:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1708:                 }
                   1709:             }
                   1710:         }
1.1331    raeburn  1711:         unless ($caller eq 'login') {
                   1712:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1713:                 $is_balancer = 0;
                   1714:                 if ($uname ne '' && $udom ne '') {
                   1715:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389    raeburn  1716:                         &appenv({'user.loadbalexempt'     => $lonhost,
1.1331    raeburn  1717:                                  'user.loadbalcheck.time' => time});
                   1718:                     }
1.1176    raeburn  1719:                 }
1.1129    raeburn  1720:             }
                   1721:         }
1.1430    raeburn  1722:     }
                   1723:     if (($is_balancer) && (!$homeintdom)) {
                   1724:         undef($setcookie);
1.1129    raeburn  1725:     }
1.1391    raeburn  1726:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129    raeburn  1727: }
                   1728: 
1.1191    raeburn  1729: sub check_balancer_result {
                   1730:     my ($result,@hosts) = @_;
1.1391    raeburn  1731:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1732:     if (ref($result) eq 'HASH') {
                   1733:         if ($result->{'lonhost'} ne '') {
                   1734:             my $currbalancer = $result->{'lonhost'};
                   1735:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1736:                 $is_balancer = 1;
                   1737:                 $currtargets = $result->{'targets'};
                   1738:                 $currrules = $result->{'rules'};
                   1739:             }
1.1391    raeburn  1740:             $dom_balancers = $currbalancer;
1.1191    raeburn  1741:         } else {
1.1391    raeburn  1742:             if (keys(%{$result})) {
                   1743:                 foreach my $key (keys(%{$result})) {
                   1744:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1745:                         (ref($result->{$key}) eq 'HASH')) {
                   1746:                         $is_balancer = 1;
                   1747:                         $currrules = $result->{$key}{'rules'};
                   1748:                         $currtargets = $result->{$key}{'targets'};
                   1749:                         $setcookie = $result->{$key}{'cookie'};
                   1750:                         last;
                   1751:                     }
1.1191    raeburn  1752:                 }
1.1391    raeburn  1753:                 $dom_balancers = join(',',sort(keys(%{$result})));
1.1191    raeburn  1754:             }
                   1755:         }
                   1756:     }
1.1391    raeburn  1757:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1758: }
                   1759: 
1.1129    raeburn  1760: sub get_loadbalancer_targets {
                   1761:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1762:     my $offloadto;
1.1175    raeburn  1763:     if ($rule_in_effect eq 'none') {
                   1764:         return [$perlvar{'lonHostID'}];
                   1765:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1766:         $offloadto = $currtargets;
                   1767:     } else {
                   1768:         if ($rule_in_effect eq 'homeserver') {
                   1769:             my $homeserver = &homeserver($uname,$udom);
                   1770:             if ($homeserver ne 'no_host') {
                   1771:                 $offloadto = [$homeserver];
                   1772:             }
                   1773:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1774:             my %domconfig =
                   1775:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1776:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1777:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1778:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1779:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1780:                     }
                   1781:                 }
                   1782:             } else {
1.1178    raeburn  1783:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1784:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1785:                 if (&hostname($remotebalancer) ne '') {
                   1786:                     $offloadto = [$remotebalancer];
                   1787:                 }
                   1788:             }
                   1789:         } elsif (&hostname($rule_in_effect) ne '') {
                   1790:             $offloadto = [$rule_in_effect];
                   1791:         }
                   1792:     }
                   1793:     return $offloadto;
                   1794: }
                   1795: 
1.1127    raeburn  1796: sub internet_dom_servers {
                   1797:     my ($dom) = @_;
                   1798:     my (%uniqservers,%servers);
                   1799:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1800:     my @machinedoms = &machine_domains($primaryserver);
                   1801:     foreach my $mdom (@machinedoms) {
                   1802:         my %currservers = %servers;
                   1803:         my %server = &get_servers($mdom);
                   1804:         %servers = (%currservers,%server);
                   1805:     }
                   1806:     my %by_hostname;
                   1807:     foreach my $id (keys(%servers)) {
                   1808:         push(@{$by_hostname{$servers{$id}}},$id);
                   1809:     }
                   1810:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1811:         if (@{$by_hostname{$hostname}} > 1) {
                   1812:             my $match = 0;
                   1813:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1814:                 if (&host_domain($id) eq $dom) {
                   1815:                     $uniqservers{$id} = $hostname;
                   1816:                     $match = 1;
                   1817:                 }
                   1818:             }
                   1819:             unless ($match) {
                   1820:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1821:             }
                   1822:         } else {
                   1823:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1824:         }
                   1825:     }
                   1826:     return %uniqservers;
                   1827: }
                   1828: 
1.1347    raeburn  1829: sub trusted_domains {
                   1830:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1831:     my ($trusted,$untrusted);
1.1347    raeburn  1832:     if (&domain($calldom) eq '') {
1.1349    raeburn  1833:         return ($trusted,$untrusted);
1.1347    raeburn  1834:     }
1.1395    raeburn  1835:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1836:         return ($trusted,$untrusted);
1.1347    raeburn  1837:     }
                   1838:     my $callprimary = &domain($calldom,'primary');
                   1839:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1840:     if ($intcalldom eq '') {
1.1349    raeburn  1841:         return ($trusted,$untrusted);
1.1347    raeburn  1842:     }
                   1843: 
                   1844:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1845:     unless (defined($cached)) {
                   1846:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1847:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1848:         $trustconfig = $domconfig{'trust'};
                   1849:     }
                   1850:     if (ref($trustconfig)) {
                   1851:         my (%possexc,%possinc,@allexc,@allinc); 
                   1852:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1853:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1854:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1855:             }
                   1856:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395    raeburn  1857:                 $possinc{$intcalldom} = 1;
1.1347    raeburn  1858:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1859:             }
                   1860:         }
                   1861:         if (keys(%possexc)) {
                   1862:             if (keys(%possinc)) {
                   1863:                 foreach my $key (sort(keys(%possexc))) {
                   1864:                     next if ($key eq $intcalldom);
                   1865:                     unless ($possinc{$key}) {
                   1866:                         push(@allexc,$key);
                   1867:                     }
                   1868:                 }
                   1869:             } else {
                   1870:                 @allexc = sort(keys(%possexc));
                   1871:             }
                   1872:         }
                   1873:         if (keys(%possinc)) {
                   1874:             $possinc{$intcalldom} = 1;
                   1875:             @allinc = sort(keys(%possinc));
                   1876:         }
                   1877:         if ((@allexc > 0) || (@allinc > 0)) {
                   1878:             my %doms_by_intdom;
                   1879:             my %allintdoms = &all_host_intdom();
                   1880:             my %alldoms = &all_host_domain();
                   1881:             foreach my $key (%allintdoms) {
                   1882:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1883:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1884:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1885:                     }
                   1886:                 } else {
                   1887:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1888:                 }
                   1889:             }
                   1890:             foreach my $exc (@allexc) {
                   1891:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395    raeburn  1892:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347    raeburn  1893:                 }
                   1894:             }
                   1895:             foreach my $inc (@allinc) {
                   1896:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395    raeburn  1897:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347    raeburn  1898:                 }
                   1899:             }
                   1900:         }
                   1901:     }
1.1349    raeburn  1902:     return ($trusted,$untrusted);
1.1347    raeburn  1903: }
                   1904: 
                   1905: sub will_trust {
                   1906:     my ($cmdtype,$domain,$possdom) = @_;
                   1907:     return 1 if ($domain eq $possdom);
                   1908:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1909:     my $willtrust; 
                   1910:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1911:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1912:             $willtrust = 1;
                   1913:         }
                   1914:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1915:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1916:             $willtrust = 1;
                   1917:         }
                   1918:     } else {
                   1919:         $willtrust = 1;
                   1920:     }
                   1921:     return $willtrust;
                   1922: }
                   1923: 
1.1       albertel 1924: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1925: 
1.599     albertel 1926: my %homecache;
1.1       albertel 1927: sub homeserver {
1.230     stredwic 1928:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1929:     my $index="$uname:$udom";
1.426     albertel 1930: 
1.599     albertel 1931:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1932: 
                   1933:     my %servers = &get_servers($udom,'library');
                   1934:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1935:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1936: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1937: 
                   1938: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1939: 	if ($answer eq 'found') {
                   1940: 	    delete($badServerCache{$tryserver}); 
                   1941: 	    return $homecache{$index}=$tryserver;
                   1942: 	} elsif ($answer eq 'no_host') {
                   1943: 	    $badServerCache{$tryserver}=1;
                   1944: 	}
1.1       albertel 1945:     }    
                   1946:     return 'no_host';
1.70      www      1947: }
                   1948: 
1.1300    raeburn  1949: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1950: 
                   1951: sub idget {
1.1300    raeburn  1952:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1953:     my %returnhash=();
1.1300    raeburn  1954:     my @ids=(); 
                   1955:     if (ref($idsref) eq 'ARRAY') {
                   1956:         @ids = @{$idsref};
                   1957:     } else {
                   1958:         return %returnhash; 
                   1959:     }
                   1960:     if ($namespace eq '') {
                   1961:         $namespace = 'ids';
                   1962:     }
1.70      www      1963:     
1.841     albertel 1964:     my %servers = &get_servers($udom,'library');
                   1965:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1966: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1967: 	if ($namespace eq 'ids') {
                   1968: 	    $idlist=~tr/A-Z/a-z/;
                   1969: 	}
                   1970: 	my $reply;
                   1971: 	if ($namespace eq 'ids') {
                   1972: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1973: 	} else {
                   1974: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1975: 	}
1.841     albertel 1976: 	my @answer=();
                   1977: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1978: 	    @answer=split(/\&/,$reply);
                   1979: 	}                    ;
                   1980: 	my $i;
                   1981: 	for ($i=0;$i<=$#ids;$i++) {
                   1982: 	    if ($answer[$i]) {
1.1299    raeburn  1983: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1984: 	    }
1.841     albertel 1985: 	}
1.1300    raeburn  1986:     }
1.70      www      1987:     return %returnhash;
                   1988: }
                   1989: 
                   1990: # ------------------------------------- Find the IDs behind a list of usernames
                   1991: 
                   1992: sub idrget {
                   1993:     my ($udom,@unames)=@_;
                   1994:     my %returnhash=();
1.800     albertel 1995:     foreach my $uname (@unames) {
                   1996:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1997:     }
1.70      www      1998:     return %returnhash;
                   1999: }
                   2000: 
1.1300    raeburn  2001: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      2002: 
                   2003: sub idput {
1.1300    raeburn  2004:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      2005:     my %servers=();
1.1300    raeburn  2006:     my %ids=();
                   2007:     my %byid = ();
                   2008:     if (ref($idsref) eq 'HASH') {
                   2009:         %ids=%{$idsref};
                   2010:     }
                   2011:     if ($namespace eq '') {
                   2012:         $namespace = 'ids'; 
                   2013:     }
1.800     albertel 2014:     foreach my $uname (keys(%ids)) {
                   2015: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  2016:         if ($uhom eq '') {
                   2017:             $uhom=&homeserver($uname,$udom);
                   2018:         }
1.70      www      2019:         if ($uhom ne 'no_host') {
1.800     albertel 2020:             my $esc_unam=&escape($uname);
1.1300    raeburn  2021:             if ($namespace eq 'ids') {
                   2022:                 my $id=&escape($ids{$uname});
                   2023:                 $id=~tr/A-Z/a-z/;
                   2024:                 my $esc_unam=&escape($uname);
                   2025:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      2026:             } else {
1.1300    raeburn  2027:                 my @currids = split(/,/,$ids{$uname});
                   2028:                 foreach my $id (@currids) {
                   2029:                     $byid{$uhom}{$id} .= $uname.',';
                   2030:                 }
                   2031:             }
                   2032:         }
                   2033:     }
                   2034:     if ($namespace eq 'clickers') {
                   2035:         foreach my $server (keys(%byid)) {
                   2036:             if (ref($byid{$server}) eq 'HASH') {
                   2037:                 foreach my $id (keys(%{$byid{$server}})) {
                   2038:                     $byid{$server} =~ s/,$//;
                   2039:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   2040:                 }
1.70      www      2041:             }
                   2042:         }
1.191     harris41 2043:     }
1.800     albertel 2044:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2045:         $servers{$server} =~ s/\&$//;
                   2046:         if ($namespace eq 'ids') {     
                   2047:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   2048:         } else {
                   2049:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   2050:         }
1.191     harris41 2051:     }
1.344     www      2052: }
                   2053: 
1.1300    raeburn  2054: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  2055: 
                   2056: sub iddel {
1.1300    raeburn  2057:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  2058:     my %result=();
1.1300    raeburn  2059:     my %ids=();
                   2060:     my %byid = ();
                   2061:     if (ref($idshashref) eq 'HASH') {
                   2062:         %ids=%{$idshashref};
                   2063:     } else {
1.1231    raeburn  2064:         return %result;
                   2065:     }
1.1300    raeburn  2066:     if ($namespace eq '') {
                   2067:         $namespace = 'ids';
                   2068:     }
1.1231    raeburn  2069:     my %servers=();
1.1300    raeburn  2070:     while (my ($id,$unamestr) = each(%ids)) {
                   2071:         if ($namespace eq 'ids') {
                   2072:             my $uhom = $uhome;
                   2073:             if ($uhom eq '') { 
                   2074:                 $uhom=&homeserver($unamestr,$udom);
                   2075:             }
                   2076:             if ($uhom ne 'no_host') {
                   2077:                 $servers{$uhom}.='&'.&escape($id);
                   2078:             }
                   2079:          } else {
                   2080:             my @curritems = split(/,/,$ids{$id});
                   2081:             foreach my $uname (@curritems) {
                   2082:                 my $uhom = $uhome;
                   2083:                 if ($uhom eq '') {
                   2084:                     $uhom=&homeserver($uname,$udom);
                   2085:                 }
                   2086:                 if ($uhom ne 'no_host') { 
                   2087:                     $byid{$uhom}{$id} .= $uname.',';
                   2088:                 }
                   2089:             }
1.1231    raeburn  2090:         }
1.1300    raeburn  2091:     }
                   2092:     if ($namespace eq 'clickers') {
                   2093:         foreach my $server (keys(%byid)) {
                   2094:             if (ref($byid{$server}) eq 'HASH') {
                   2095:                 foreach my $id (keys(%{$byid{$server}})) {
                   2096:                     $byid{$server}{$id} =~ s/,$//;
                   2097:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   2098:                 }
1.1231    raeburn  2099:             }
                   2100:         }
                   2101:     }
                   2102:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2103:         $servers{$server} =~ s/\&$//;
                   2104:         if ($namespace eq 'ids') {
                   2105:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   2106:         } elsif ($namespace eq 'clickers') {
                   2107:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   2108:         }
1.1231    raeburn  2109:     }
                   2110:     return %result;
                   2111: }
                   2112: 
1.1300    raeburn  2113: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   2114: 
                   2115: sub updateclickers {
                   2116:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   2117:     my %clickers;
                   2118:     if (ref($idshashref) eq 'HASH') {
                   2119:         %clickers=%{$idshashref};
                   2120:     } else {
                   2121:         return;
                   2122:     }
                   2123:     my $items='';
                   2124:     foreach my $item (keys(%clickers)) {
                   2125:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   2126:     }
                   2127:     $items=~s/\&$//;
                   2128:     my $request = "updateclickers:$udom:$action:$items";
                   2129:     if ($critical) {
                   2130:         return &critical($request,$uhome);
                   2131:     } else {
                   2132:         return &reply($request,$uhome);
                   2133:     }
                   2134: }
                   2135: 
1.1023    raeburn  2136: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  2137: sub dump_dom {
1.1165    droeschl 2138:     my ($namespace, $udom, $regexp) = @_;
                   2139: 
                   2140:     $udom ||= $env{'user.domain'};
                   2141: 
                   2142:     return () unless $udom;
                   2143: 
                   2144:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  2145: }
                   2146: 
1.1023    raeburn  2147: # ------------------------------------------ get items from domain db files   
1.806     raeburn  2148: 
                   2149: sub get_dom {
1.1462    raeburn  2150:     my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
1.1267    raeburn  2151:     return if ($udom eq 'public');
1.806     raeburn  2152:     my $items='';
                   2153:     foreach my $item (@$storearr) {
                   2154:         $items.=&escape($item).'&';
                   2155:     }
                   2156:     $items=~s/\&$//;
1.860     raeburn  2157:     if (!$udom) {
                   2158:         $udom=$env{'user.domain'};
1.1267    raeburn  2159:         return if ($udom eq 'public');
1.860     raeburn  2160:         if (defined(&domain($udom,'primary'))) {
                   2161:             $uhome=&domain($udom,'primary');
                   2162:         } else {
1.874     albertel 2163:             undef($uhome);
1.860     raeburn  2164:         }
                   2165:     } else {
                   2166:         if (!$uhome) {
                   2167:             if (defined(&domain($udom,'primary'))) {
                   2168:                 $uhome=&domain($udom,'primary');
                   2169:             }
                   2170:         }
                   2171:     }
                   2172:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  2173:         my $rep;
1.1442    raeburn  2174:         if (grep { $_ eq $uhome } &current_machine_ids()) {
                   2175:             # domain information is hosted on this machine
1.1462    raeburn  2176:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1.1344    raeburn  2177:         } else {
1.1462    raeburn  2178:             if ($encrypt) {
1.1442    raeburn  2179:                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2180:             } else {
                   2181:                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2182:             }
1.1344    raeburn  2183:         }
1.866     raeburn  2184:         my %returnhash;
1.875     albertel 2185:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2186:             return %returnhash;
                   2187:         }
1.806     raeburn  2188:         my @pairs=split(/\&/,$rep);
                   2189:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2190:             return @pairs;
                   2191:         }
                   2192:         my $i=0;
                   2193:         foreach my $item (@$storearr) {
                   2194:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2195:             $i++;
                   2196:         }
                   2197:         return %returnhash;
                   2198:     } else {
1.880     banghart 2199:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2200:     }
                   2201: }
                   2202: 
                   2203: # -------------------------------------------- put items in domain db files 
                   2204: 
                   2205: sub put_dom {
1.1462    raeburn  2206:     my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
1.860     raeburn  2207:     if (!$udom) {
                   2208:         $udom=$env{'user.domain'};
                   2209:         if (defined(&domain($udom,'primary'))) {
                   2210:             $uhome=&domain($udom,'primary');
                   2211:         } else {
1.874     albertel 2212:             undef($uhome);
1.860     raeburn  2213:         }
                   2214:     } else {
                   2215:         if (!$uhome) {
                   2216:             if (defined(&domain($udom,'primary'))) {
                   2217:                 $uhome=&domain($udom,'primary');
                   2218:             }
                   2219:         }
                   2220:     } 
                   2221:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2222:         my $items='';
                   2223:         foreach my $item (keys(%$storehash)) {
                   2224:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2225:         }
                   2226:         $items=~s/\&$//;
1.1462    raeburn  2227:         if ($encrypt) {
1.1344    raeburn  2228:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2229:         } else {
                   2230:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2231:         }
1.806     raeburn  2232:     } else {
1.860     raeburn  2233:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2234:     }
                   2235: }
                   2236: 
1.1023    raeburn  2237: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2238: sub newput_dom {
1.1023    raeburn  2239:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2240:     my $result;
                   2241:     if (!$udom) {
                   2242:         $udom=$env{'user.domain'};
                   2243:     }
1.1023    raeburn  2244:     if ($udom) {
                   2245:         my $uname = &get_domainconfiguser($udom);
                   2246:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2247:     }
                   2248:     return $result;
                   2249: }
                   2250: 
1.1023    raeburn  2251: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2252: sub del_dom {
1.1023    raeburn  2253:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2254:     if (ref($storearr) eq 'ARRAY') {
                   2255:         if (!$udom) {
                   2256:             $udom=$env{'user.domain'};
                   2257:         }
1.1023    raeburn  2258:         if ($udom) {
                   2259:             my $uname = &get_domainconfiguser($udom); 
                   2260:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2261:         }
                   2262:     }
                   2263: }
                   2264: 
1.1481    raeburn  2265: sub store_dom {
1.1482    raeburn  2266:     my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
1.1481    raeburn  2267:     $$storehash{'ip'}=&get_requestor_ip();
                   2268:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2269:     my $namevalue='';
                   2270:     foreach my $key (keys(%{$storehash})) {
                   2271:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   2272:     }
                   2273:     $namevalue=~s/\&$//;
                   2274:     if (grep { $_ eq $home } current_machine_ids()) {
                   2275:         return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
                   2276:     } else {
                   2277:         if ($namespace eq 'private') {
                   2278:             return 'refused';
1.1482    raeburn  2279:         } elsif ($encrypt) {
                   2280:             return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
1.1481    raeburn  2281:         } else {
1.1482    raeburn  2282:             return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
1.1481    raeburn  2283:         }
                   2284:     }
                   2285: }
                   2286: 
1.1482    raeburn  2287: sub restore_dom {
                   2288:     my ($id,$namespace,$dom,$home,$encrypt) = @_;
                   2289:     my $answer;
                   2290:     if (grep { $_ eq $home } current_machine_ids()) {
                   2291:         $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
                   2292:     } elsif ($namespace ne 'private') {
                   2293:         if ($encrypt) {
                   2294:             $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
                   2295:         } else {
                   2296:             $answer=&reply("restoredom:$dom:$namespace:$id",$home);
                   2297:         }
                   2298:     }
                   2299:     my %returnhash=();
                   2300:     unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') || 
                   2301:             ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
                   2302:         foreach my $line (split(/\&/,$answer)) {
                   2303:             my ($name,$value)=split(/\=/,$line);
                   2304:             $returnhash{&unescape($name)}=&thaw_unescape($value);
                   2305:         }
                   2306:         my $version;
                   2307:         for ($version=1;$version<=$returnhash{'version'};$version++) {
                   2308:             foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2309:                 $returnhash{$item}=$returnhash{$version.':'.$item};
                   2310:             }
                   2311:         }
                   2312:     }
                   2313:     return %returnhash;
                   2314: }
                   2315: 
1.1023    raeburn  2316: # ----------------------------------construct domainconfig user for a domain 
                   2317: sub get_domainconfiguser {
                   2318:     my ($udom) = @_;
                   2319:     return $udom.'-domainconfig';
                   2320: }
                   2321: 
1.837     raeburn  2322: sub retrieve_inst_usertypes {
                   2323:     my ($udom) = @_;
                   2324:     my (%returnhash,@order);
1.989     raeburn  2325:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2326:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2327:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2328:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2329:     } else {
                   2330:         if (defined(&domain($udom,'primary'))) {
                   2331:             my $uhome=&domain($udom,'primary');
                   2332:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2333:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2334:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2335:                 return (\%returnhash,\@order);
                   2336:             }
                   2337:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2338:             my @pairs=split(/\&/,$hashitems);
                   2339:             foreach my $item (@pairs) {
                   2340:                 my ($key,$value)=split(/=/,$item,2);
                   2341:                 $key = &unescape($key);
                   2342:                 next if ($key =~ /^error: 2 /);
                   2343:                 $returnhash{$key}=&thaw_unescape($value);
                   2344:             }
                   2345:             my @esc_order = split(/\&/,$orderitems);
                   2346:             foreach my $item (@esc_order) {
                   2347:                 push(@order,&unescape($item));
                   2348:             }
                   2349:         } else {
1.1256    raeburn  2350:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2351:         }
1.1256    raeburn  2352:         return (\%returnhash,\@order);
1.837     raeburn  2353:     }
                   2354: }
                   2355: 
1.868     raeburn  2356: sub is_domainimage {
                   2357:     my ($url) = @_;
1.1468    raeburn  2358:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868     raeburn  2359:         if (&domain($1) ne '') {
                   2360:             return '1';
                   2361:         }
                   2362:     }
                   2363:     return;
                   2364: }
                   2365: 
1.899     raeburn  2366: sub inst_directory_query {
                   2367:     my ($srch) = @_;
                   2368:     my $udom = $srch->{'srchdomain'};
                   2369:     my %results;
                   2370:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2371:     my $outcome;
1.899     raeburn  2372:     if ($homeserver ne '') {
1.1357    raeburn  2373:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2374:             if ($srch->{'srchby'} eq 'email') {
1.1417    raeburn  2375:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1357    raeburn  2376:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2377:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2378:                     (($major == 2) && ($minor < 12))) {
                   2379:                     return;
                   2380:                 }
                   2381:             }
                   2382:         }
1.904     albertel 2383: 	my $queryid=&reply("querysend:instdirsearch:".
                   2384: 			   &escape($srch->{'srchby'}).':'.
                   2385: 			   &escape($srch->{'srchterm'}).':'.
                   2386: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2387: 	my $host=&hostname($homeserver);
                   2388: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2389: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2390: 	    return;
                   2391: 	}
                   2392: 	my $response = &get_query_reply($queryid);
                   2393: 	my $maxtries = 5;
                   2394: 	my $tries = 1;
                   2395: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2396: 	    $response = &get_query_reply($queryid);
                   2397: 	    $tries ++;
                   2398: 	}
                   2399: 
                   2400:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2401:             if ($response eq 'unavailable') {
                   2402:                 $outcome = $response;
                   2403:             } else {
                   2404:                 $outcome = 'ok';
                   2405:                 my @matches = split(/\n/,$response);
                   2406:                 foreach my $match (@matches) {
                   2407:                     my ($key,$value) = split(/=/,$match);
                   2408:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2409:                 }
1.899     raeburn  2410:             }
                   2411:         }
                   2412:     }
1.909     raeburn  2413:     return ($outcome,%results);
1.899     raeburn  2414: }
                   2415: 
                   2416: sub usersearch {
                   2417:     my ($srch) = @_;
                   2418:     my $dom = $srch->{'srchdomain'};
                   2419:     my %results;
                   2420:     my %libserv = &all_library();
                   2421:     my $query = 'usersearch';
                   2422:     foreach my $tryserver (keys(%libserv)) {
                   2423:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2424:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2425:                 if ($srch->{'srchby'} eq 'email') {
1.1417    raeburn  2426:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1357    raeburn  2427:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2428:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2429:                              (($major == 2) && ($minor < 12)));
                   2430:                 }
                   2431:             }
1.899     raeburn  2432:             my $host=&hostname($tryserver);
                   2433:             my $queryid=
1.911     raeburn  2434:                 &reply("querysend:".&escape($query).':'.
                   2435:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2436:                        &escape($srch->{'srchtype'}).':'.
                   2437:                        &escape($srch->{'srchterm'}),$tryserver);
                   2438:             if ($queryid !~/^\Q$host\E\_/) {
                   2439:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2440:                 next;
1.899     raeburn  2441:             }
                   2442:             my $reply = &get_query_reply($queryid);
                   2443:             my $maxtries = 1;
                   2444:             my $tries = 1;
                   2445:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2446:                 $reply = &get_query_reply($queryid);
                   2447:                 $tries ++;
                   2448:             }
                   2449:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2450:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2451:             } else {
1.911     raeburn  2452:                 my @matches;
                   2453:                 if ($reply =~ /\n/) {
                   2454:                     @matches = split(/\n/,$reply);
                   2455:                 } else {
                   2456:                     @matches = split(/\&/,$reply);
                   2457:                 }
1.899     raeburn  2458:                 foreach my $match (@matches) {
                   2459:                     my ($uname,$udom,%userhash);
1.911     raeburn  2460:                     foreach my $entry (split(/:/,$match)) {
                   2461:                         my ($key,$value) =
                   2462:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2463:                         $userhash{$key} = $value;
                   2464:                         if ($key eq 'username') {
                   2465:                             $uname = $value;
                   2466:                         } elsif ($key eq 'domain') {
                   2467:                             $udom = $value;
1.911     raeburn  2468:                         }
1.899     raeburn  2469:                     }
                   2470:                     $results{$uname.':'.$udom} = \%userhash;
                   2471:                 }
                   2472:             }
                   2473:         }
                   2474:     }
                   2475:     return %results;
                   2476: }
                   2477: 
1.912     raeburn  2478: sub get_instuser {
                   2479:     my ($udom,$uname,$id) = @_;
                   2480:     my $homeserver = &domain($udom,'primary');
                   2481:     my ($outcome,%results);
                   2482:     if ($homeserver ne '') {
                   2483:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2484:                            &escape($id).':'.&escape($udom),$homeserver);
                   2485:         my $host=&hostname($homeserver);
                   2486:         if ($queryid !~/^\Q$host\E\_/) {
                   2487:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2488:             return;
                   2489:         }
                   2490:         my $response = &get_query_reply($queryid);
                   2491:         my $maxtries = 5;
                   2492:         my $tries = 1;
                   2493:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2494:             $response = &get_query_reply($queryid);
                   2495:             $tries ++;
                   2496:         }
                   2497:         if (!&error($response) && $response ne 'refused') {
                   2498:             if ($response eq 'unavailable') {
                   2499:                 $outcome = $response;
                   2500:             } else {
                   2501:                 $outcome = 'ok';
                   2502:                 my @matches = split(/\n/,$response);
                   2503:                 foreach my $match (@matches) {
                   2504:                     my ($key,$value) = split(/=/,$match);
                   2505:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2506:                 }
                   2507:             }
                   2508:         }
                   2509:     }
                   2510:     my %userinfo;
                   2511:     if (ref($results{$uname}) eq 'HASH') {
                   2512:         %userinfo = %{$results{$uname}};
                   2513:     } 
                   2514:     return ($outcome,%userinfo);
                   2515: }
                   2516: 
1.1290    raeburn  2517: sub get_multiple_instusers {
                   2518:     my ($udom,$users,$caller) = @_;
                   2519:     my ($outcome,$results);
                   2520:     if (ref($users) eq 'HASH') {
                   2521:         my $count = keys(%{$users}); 
                   2522:         my $requested = &freeze_escape($users);
                   2523:         my $homeserver = &domain($udom,'primary');
                   2524:         if ($homeserver ne '') {
                   2525:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2526:             my $host=&hostname($homeserver);
                   2527:             if ($queryid !~/^\Q$host\E\_/) {
                   2528:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2529:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2530:                 return ($outcome,$results);
                   2531:             }
                   2532:             my $response = &get_query_reply($queryid);
                   2533:             my $maxtries = 5;
                   2534:             if ($count > 100) {
                   2535:                 $maxtries = 1+int($count/20);
                   2536:             }
                   2537:             my $tries = 1;
                   2538:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2539:                 $response = &get_query_reply($queryid);
                   2540:                 $tries ++;
                   2541:             }
                   2542:             if ($response eq '') {
                   2543:                 $results = {};
                   2544:                 foreach my $key (keys(%{$users})) {
                   2545:                     my ($uname,$id);
                   2546:                     if ($caller eq 'id') {
                   2547:                         $id = $key;
                   2548:                     } else {
                   2549:                         $uname = $key;
                   2550:                     }
                   2551:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2552:                     $outcome = $resp;
1.1290    raeburn  2553:                     if ($resp eq 'ok') {
                   2554:                         %{$results} = (%{$results}, %info);
                   2555:                     } else {
                   2556:                         last;
                   2557:                     }
                   2558:                 }
                   2559:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2560:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2561:                     $outcome = $response;
                   2562:                 } else {
1.1291    raeburn  2563:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2564:                     if ($outcome eq 'ok') {
                   2565:                         $results = &thaw_unescape($userdata); 
                   2566:                     }
                   2567:                 }
                   2568:             }
                   2569:         }
                   2570:     }
                   2571:     return ($outcome,$results);
                   2572: }
                   2573: 
1.912     raeburn  2574: sub inst_rulecheck {
1.923     raeburn  2575:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2576:     my %returnhash;
                   2577:     if ($udom ne '') {
                   2578:         if (ref($rules) eq 'ARRAY') {
                   2579:             @{$rules} = map {&escape($_);} (@{$rules});
                   2580:             my $rulestr = join(':',@{$rules});
                   2581:             my $homeserver=&domain($udom,'primary');
                   2582:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2583:                 my $response;
                   2584:                 if ($item eq 'username') {                
                   2585:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2586:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2587:                                               $homeserver));
1.923     raeburn  2588:                 } elsif ($item eq 'id') {
                   2589:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2590:                                               ':'.&escape($id).':'.$rulestr,
                   2591:                                               $homeserver));
1.945     raeburn  2592:                 } elsif ($item eq 'selfcreate') {
                   2593:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2594:                                                &escape($udom).':'.&escape($uname).
                   2595:                                               ':'.$rulestr,$homeserver));
1.1484    raeburn  2596:                 } elsif ($item eq 'unamemap') {
                   2597:                     $response=&unescape(&reply('instunamemapcheck:'.
                   2598:                                                &escape($udom).':'.&escape($uname).
                   2599:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2600:                 }
1.912     raeburn  2601:                 if ($response ne 'refused') {
                   2602:                     my @pairs=split(/\&/,$response);
                   2603:                     foreach my $item (@pairs) {
                   2604:                         my ($key,$value)=split(/=/,$item,2);
                   2605:                         $key = &unescape($key);
                   2606:                         next if ($key =~ /^error: 2 /);
                   2607:                         $returnhash{$key}=&thaw_unescape($value);
                   2608:                     }
                   2609:                 }
                   2610:             }
                   2611:         }
                   2612:     }
                   2613:     return %returnhash;
                   2614: }
                   2615: 
                   2616: sub inst_userrules {
1.923     raeburn  2617:     my ($udom,$check) = @_;
1.912     raeburn  2618:     my (%ruleshash,@ruleorder);
                   2619:     if ($udom ne '') {
                   2620:         my $homeserver=&domain($udom,'primary');
                   2621:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2622:             my $response;
                   2623:             if ($check eq 'id') {
                   2624:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2625:                                  $homeserver);
1.943     raeburn  2626:             } elsif ($check eq 'email') {
                   2627:                 $response=&reply('instemailrules:'.&escape($udom),
                   2628:                                  $homeserver);
1.1484    raeburn  2629:             } elsif ($check eq 'unamemap') {
                   2630:                 $response=&reply('unamemaprules:'.&escape($udom),
                   2631:                                  $homeserver); 
1.923     raeburn  2632:             } else {
                   2633:                 $response=&reply('instuserrules:'.&escape($udom),
                   2634:                                  $homeserver);
                   2635:             }
1.912     raeburn  2636:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2637:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2638:                 ($response ne 'no_such_host')) {
                   2639:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2640:                 my @pairs=split(/\&/,$hashitems);
                   2641:                 foreach my $item (@pairs) {
                   2642:                     my ($key,$value)=split(/=/,$item,2);
                   2643:                     $key = &unescape($key);
                   2644:                     next if ($key =~ /^error: 2 /);
                   2645:                     $ruleshash{$key}=&thaw_unescape($value);
                   2646:                 }
                   2647:                 my @esc_order = split(/\&/,$orderitems);
                   2648:                 foreach my $item (@esc_order) {
                   2649:                     push(@ruleorder,&unescape($item));
                   2650:                 }
                   2651:             }
                   2652:         }
                   2653:     }
                   2654:     return (\%ruleshash,\@ruleorder);
                   2655: }
                   2656: 
1.976     raeburn  2657: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2658: 
                   2659: sub get_domain_defaults {
1.1240    raeburn  2660:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2661:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2662:     my $cachetime = 60*60*24;
1.1240    raeburn  2663:     unless ($ignore_cache) {
                   2664:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2665:         if (defined($cached)) {
                   2666:             if (ref($result) eq 'HASH') {
                   2667:                 return %{$result};
                   2668:             }
1.943     raeburn  2669:         }
                   2670:     }
                   2671:     my %domdefaults;
                   2672:     my %domconfig =
1.989     raeburn  2673:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2674:                                   'requestcourses','inststatus',
1.1183    raeburn  2675:                                   'coursedefaults','usersessions',
1.1258    raeburn  2676:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2677:                                   'coursecategories','ssl','autoenroll',
1.1482    raeburn  2678:                                   'trust','helpsettings','wafproxy','ltisec'],$domain);
1.1305    raeburn  2679:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2680:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2681:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2682:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2683:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2684:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2685:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2686:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2687:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2688:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2689:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.1484    raeburn  2690:         $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
1.943     raeburn  2691:     } else {
                   2692:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2693:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2694:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2695:     }
1.976     raeburn  2696:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2697:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2698:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2699:         } else {
                   2700:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2701:         }
1.1177    raeburn  2702:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2703:         foreach my $item (@usertools) {
                   2704:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2705:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2706:             }
                   2707:         }
1.1229    raeburn  2708:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2709:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2710:         }
1.976     raeburn  2711:     }
1.985     raeburn  2712:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2713:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2714:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2715:         }
                   2716:     }
1.1183    raeburn  2717:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2718:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2719:     }
1.989     raeburn  2720:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2721:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2722:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2723:         }
                   2724:     }
1.1047    raeburn  2725:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2726:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2727:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1476    raeburn  2728:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1277    raeburn  2729:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2730:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2731:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2732:         }
1.1254    raeburn  2733:         foreach my $type (@coursetypes) {
                   2734:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2735:                 unless ($type eq 'community') {
                   2736:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2737:                 }
                   2738:             }
                   2739:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2740:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2741:             }
1.1277    raeburn  2742:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2743:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2744:                     $domdefaults{$type.'postsubtimeout'} = 
                   2745:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2746:                 }
                   2747:             }
1.1230    raeburn  2748:         }
1.1286    raeburn  2749:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2750:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2751:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2752:                 if (@clonecodes) {
                   2753:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2754:                 }
                   2755:             }
                   2756:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2757:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2758:         }
1.1356    raeburn  2759:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2760:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
1.1480    raeburn  2761:         }
                   2762:         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
                   2763:             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
                   2764:         }
1.1047    raeburn  2765:     }
1.1073    raeburn  2766:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2767:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2768:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2769:         }
                   2770:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2771:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2772:         }
1.1279    raeburn  2773:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2774:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2775:         }
1.1440    raeburn  2776:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1439    raeburn  2777:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2778:         }
1.1073    raeburn  2779:     }
1.1254    raeburn  2780:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2781:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2782:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2783:                             'approval','limit');
                   2784:             foreach my $type (@coursetypes) {
                   2785:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2786:                     my @mgrdc = ();
                   2787:                     foreach my $item (@settings) {
                   2788:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2789:                             push(@mgrdc,$item);
                   2790:                         }
                   2791:                     }
                   2792:                     if (@mgrdc) {
                   2793:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2794:                     }
                   2795:                 }
                   2796:             }
                   2797:         }
                   2798:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2799:             foreach my $type (@coursetypes) {
                   2800:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2801:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2802:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2803:                     }
                   2804:                 }
                   2805:             }
                   2806:         }
                   2807:     }
1.1258    raeburn  2808:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2809:         $domdefaults{'catauth'} = 'std';
                   2810:         $domdefaults{'catunauth'} = 'std';
1.1413    raeburn  2811:         if ($domconfig{'coursecategories'}{'auth'}) {
1.1258    raeburn  2812:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2813:         }
                   2814:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2815:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2816:         }
                   2817:     }
1.1315    raeburn  2818:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2819:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2820:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2821:         }
1.1338    raeburn  2822:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2823:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2824:         }
                   2825:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2826:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2827:         }
                   2828:     }
1.1320    raeburn  2829:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2830:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2831:         foreach my $prefix (@prefixes) {
                   2832:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2833:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2834:             }
                   2835:         }
                   2836:     }
1.1314    raeburn  2837:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2838:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1477    raeburn  2839:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1314    raeburn  2840:     }
1.1332    raeburn  2841:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2842:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2843:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2844:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2845:         }
                   2846:     }
1.1434    raeburn  2847:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
1.1449    raeburn  2848:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
1.1434    raeburn  2849:             if ($domconfig{'wafproxy'}{$item}) {
                   2850:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
                   2851:             }
                   2852:         }
1.1482    raeburn  2853:     }
                   2854:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   2855:         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
                   2856:             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
                   2857:             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
                   2858:             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
                   2859:         }
                   2860:         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
                   2861:             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
                   2862:                 $domdefaults{'privhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
                   2863:             }
                   2864:         }
                   2865:     }
1.1219    raeburn  2866:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2867:     return %domdefaults;
                   2868: }
                   2869: 
1.1412    raeburn  2870: sub get_dom_cats {
                   2871:     my ($dom) = @_;
                   2872:     return unless (&domain($dom));
                   2873:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2874:     unless (defined($cached)) {
                   2875:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2876:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2877:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2878:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2879:             } else {
                   2880:                 $cats = {};
                   2881:             }
                   2882:         } else {
                   2883:             $cats = {};
                   2884:         }
                   2885:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2886:     }
1.1413    raeburn  2887:     return $cats;
                   2888: }
                   2889: 
                   2890: sub get_dom_instcats {
                   2891:     my ($dom) = @_;
                   2892:     return unless (&domain($dom));
                   2893:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2894:     unless (defined($cached)) {
                   2895:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2896:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2897:         if ($totcodes > 0) {
                   2898:             my $caller = 'global';
                   2899:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2900:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2901:                 $instcats = {
                   2902:                                 codes => \%codes,
                   2903:                                 codetitles => \@codetitles,
                   2904:                                 cat_titles => \%cat_titles,
                   2905:                                 cat_order => \%cat_order,
                   2906:                             };
                   2907:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2908:             }
                   2909:         }
                   2910:     }
                   2911:     return $instcats;
                   2912: }
                   2913: 
                   2914: sub retrieve_instcodes {
                   2915:     my ($coursecodes,$dom) = @_;
                   2916:     my $totcodes;
                   2917:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2918:     foreach my $course (keys(%courses)) {
                   2919:         if (ref($courses{$course}) eq 'HASH') {
                   2920:             if ($courses{$course}{'inst_code'} ne '') {
                   2921:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2922:                 $totcodes ++;
                   2923:             }
                   2924:         }
                   2925:     }
                   2926:     return $totcodes;
1.1412    raeburn  2927: }
                   2928: 
1.1311    raeburn  2929: sub course_portal_url {
1.1451    raeburn  2930:     my ($cnum,$cdom,$r) = @_;
1.1311    raeburn  2931:     my $chome = &homeserver($cnum,$cdom);
                   2932:     my $hostname = &hostname($chome);
                   2933:     my $protocol = $protocol{$chome};
                   2934:     $protocol = 'http' if ($protocol ne 'https');
                   2935:     my %domdefaults = &get_domain_defaults($cdom);
                   2936:     my $firsturl;
                   2937:     if ($domdefaults{'portal_def'}) {
                   2938:         $firsturl = $domdefaults{'portal_def'};
                   2939:     } else {
1.1451    raeburn  2940:         my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
                   2941:         $hostname = $alias if ($alias ne '');
1.1311    raeburn  2942:         $firsturl = $protocol.'://'.$hostname;
                   2943:     }
                   2944:     return $firsturl;
                   2945: }
                   2946: 
1.1407    raeburn  2947: # --------------------------------------------- Get domain config for passwords
                   2948: 
                   2949: sub get_passwdconf {
                   2950:     my ($dom) = @_;
                   2951:     my (%passwdconf,$gotconf,$lookup);
                   2952:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2953:     if (defined($cached)) {
                   2954:         if (ref($result) eq 'HASH') {
                   2955:             %passwdconf = %{$result};
                   2956:             $gotconf = 1;
                   2957:         }
                   2958:     }
                   2959:     unless ($gotconf) {
                   2960:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2961:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2962:             %passwdconf = %{$domconfig{'passwords'}};
                   2963:         }
                   2964:         my $cachetime = 24*60*60;
                   2965:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2966:     }
                   2967:     return %passwdconf;
                   2968: }
                   2969: 
1.344     www      2970: # --------------------------------------------------- Assign a key to a student
                   2971: 
                   2972: sub assign_access_key {
1.364     www      2973: #
                   2974: # a valid key looks like uname:udom#comments
                   2975: # comments are being appended
                   2976: #
1.498     www      2977:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2978:     $kdom=
1.620     albertel 2979:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2980:     $knum=
1.620     albertel 2981:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2982:     $cdom=
1.620     albertel 2983:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2984:     $cnum=
1.620     albertel 2985:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2986:     $udom=$env{'user.name'} unless (defined($udom));
                   2987:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2988:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2989:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2990:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2991:                                                   # assigned to this person
                   2992:                                                   # - this should not happen,
1.345     www      2993:                                                   # unless something went wrong
                   2994:                                                   # the first time around
                   2995: # ready to assign
1.364     www      2996:         $logentry=$1.'; '.$logentry;
1.496     www      2997:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2998:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2999: # key now belongs to user
1.346     www      3000: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      3001:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  3002:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      3003:                 return 'ok';
                   3004:             } else {
                   3005:                 return 
                   3006:   'error: Count not permanently assign key, will need to be re-entered later.';
                   3007: 	    }
                   3008:         } else {
                   3009:             return 'error: Could not assign key, try again later.';
                   3010:         }
1.364     www      3011:     } elsif (!$existing{$ckey}) {
1.345     www      3012: # the key does not exist
                   3013: 	return 'error: The key does not exist';
                   3014:     } else {
                   3015: # the key is somebody else's
                   3016: 	return 'error: The key is already in use';
                   3017:     }
1.344     www      3018: }
                   3019: 
1.364     www      3020: # ------------------------------------------ put an additional comment on a key
                   3021: 
                   3022: sub comment_access_key {
                   3023: #
                   3024: # a valid key looks like uname:udom#comments
                   3025: # comments are being appended
                   3026: #
                   3027:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   3028:     $cdom=
1.620     albertel 3029:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      3030:     $cnum=
1.620     albertel 3031:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      3032:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   3033:     if ($existing{$ckey}) {
                   3034:         $existing{$ckey}.='; '.$logentry;
                   3035: # ready to assign
1.367     www      3036:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      3037:                                                  $cdom,$cnum) eq 'ok') {
                   3038: 	    return 'ok';
                   3039:         } else {
                   3040: 	    return 'error: Count not store comment.';
                   3041:         }
                   3042:     } else {
                   3043: # the key does not exist
                   3044: 	return 'error: The key does not exist';
                   3045:     }
                   3046: }
                   3047: 
1.344     www      3048: # ------------------------------------------------------ Generate a set of keys
                   3049: 
                   3050: sub generate_access_keys {
1.364     www      3051:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      3052:     $cdom=
1.620     albertel 3053:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      3054:     $cnum=
1.620     albertel 3055:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      3056:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      3057:     unless (($cdom) && ($cnum)) { return 0; }
                   3058:     if ($number>10000) { return 0; }
                   3059:     sleep(2); # make sure don't get same seed twice
                   3060:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   3061:     my $total=0;
                   3062:     for (my $i=1;$i<=$number;$i++) {
                   3063:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   3064:                   sprintf("%lx",int(100000*rand)).'-'.
                   3065:                   sprintf("%lx",int(100000*rand));
                   3066:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   3067:        $newkey=~s/0/h/g; # and also 0 and O
                   3068:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   3069:        if ($existing{$newkey}) {
                   3070:            $i--;
                   3071:        } else {
1.364     www      3072: 	  if (&put('accesskeys',
                   3073:               { $newkey => '# generated '.localtime().
1.620     albertel 3074:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      3075:                            '; '.$logentry },
                   3076: 		   $cdom,$cnum) eq 'ok') {
1.344     www      3077:               $total++;
                   3078: 	  }
                   3079:        }
                   3080:     }
1.620     albertel 3081:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      3082:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   3083:     return $total;
                   3084: }
                   3085: 
                   3086: # ------------------------------------------------------- Validate an accesskey
                   3087: 
                   3088: sub validate_access_key {
                   3089:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   3090:     $cdom=
1.620     albertel 3091:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      3092:     $cnum=
1.620     albertel 3093:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   3094:     $udom=$env{'user.domain'} unless (defined($udom));
                   3095:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      3096:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 3097:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      3098: }
                   3099: 
                   3100: # ------------------------------------- Find the section of student in a course
1.652     albertel 3101: sub devalidate_getsection_cache {
                   3102:     my ($udom,$unam,$courseid)=@_;
                   3103:     my $hashid="$udom:$unam:$courseid";
                   3104:     &devalidate_cache_new('getsection',$hashid);
                   3105: }
1.298     matthew  3106: 
1.815     albertel 3107: sub courseid_to_courseurl {
                   3108:     my ($courseid) = @_;
                   3109:     #already url style courseid
                   3110:     return $courseid if ($courseid =~ m{^/});
                   3111: 
                   3112:     if (exists($env{'course.'.$courseid.'.num'})) {
                   3113: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   3114: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   3115: 	return "/$cdom/$cnum";
                   3116:     }
                   3117: 
                   3118:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   3119:     if (exists($courseinfo{'num'})) {
                   3120: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   3121:     }
                   3122: 
                   3123:     return undef;
                   3124: }
                   3125: 
1.298     matthew  3126: sub getsection {
                   3127:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 3128:     my $cachetime=1800;
1.551     albertel 3129: 
                   3130:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 3131:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 3132:     if (defined($cached)) { return $result; }
                   3133: 
1.298     matthew  3134:     my %Pending; 
                   3135:     my %Expired;
                   3136:     #
                   3137:     # Each role can either have not started yet (pending), be active, 
                   3138:     #    or have expired.
                   3139:     #
                   3140:     # If there is an active role, we are done.
                   3141:     #
                   3142:     # If there is more than one role which has not started yet, 
                   3143:     #     choose the one which will start sooner
                   3144:     # If there is one role which has not started yet, return it.
                   3145:     #
                   3146:     # If there is more than one expired role, choose the one which ended last.
                   3147:     # If there is a role which has expired, return it.
                   3148:     #
1.815     albertel 3149:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  3150:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  3151:     foreach my $key (keys(%roleshash)) {
1.479     albertel 3152:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  3153:         my $section=$1;
                   3154:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  3155:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  3156:         my $now=time;
1.548     albertel 3157:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  3158:             $Expired{$end}=$section;
                   3159:             next;
                   3160:         }
1.548     albertel 3161:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  3162:             $Pending{$start}=$section;
                   3163:             next;
                   3164:         }
1.599     albertel 3165:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  3166:     }
                   3167:     #
                   3168:     # Presumedly there will be few matching roles from the above
                   3169:     # loop and the sorting time will be negligible.
                   3170:     if (scalar(keys(%Pending))) {
                   3171:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 3172:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  3173:     } 
                   3174:     if (scalar(keys(%Expired))) {
                   3175:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   3176:         my $time = pop(@sorted);
1.599     albertel 3177:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  3178:     }
1.599     albertel 3179:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  3180: }
1.70      www      3181: 
1.599     albertel 3182: sub save_cache {
                   3183:     &purge_remembered();
1.722     albertel 3184:     #&Apache::loncommon::validate_page();
1.620     albertel 3185:     undef(%env);
1.780     albertel 3186:     undef($env_loaded);
1.599     albertel 3187: }
1.452     albertel 3188: 
1.599     albertel 3189: my $to_remember=-1;
                   3190: my %remembered;
                   3191: my %accessed;
                   3192: my $kicks=0;
                   3193: my $hits=0;
1.849     albertel 3194: sub make_key {
                   3195:     my ($name,$id) = @_;
1.872     albertel 3196:     if (length($id) > 65 
                   3197: 	&& length(&escape($id)) > 200) {
                   3198: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   3199:     }
1.849     albertel 3200:     return &escape($name.':'.$id);
                   3201: }
                   3202: 
1.599     albertel 3203: sub devalidate_cache_new {
                   3204:     my ($name,$id,$debug) = @_;
                   3205:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  3206:     my $remembered_id=$name.':'.$id;
1.849     albertel 3207:     $id=&make_key($name,$id);
1.599     albertel 3208:     $memcache->delete($id);
1.1319    damieng  3209:     delete($remembered{$remembered_id});
                   3210:     delete($accessed{$remembered_id});
1.599     albertel 3211: }
                   3212: 
                   3213: sub is_cached_new {
                   3214:     my ($name,$id,$debug) = @_;
1.1319    damieng  3215:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   3216:     if (exists($remembered{$remembered_id})) {
                   3217: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   3218: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3219: 	$hits++;
1.1319    damieng  3220: 	return ($remembered{$remembered_id},1);
1.599     albertel 3221:     }
1.1319    damieng  3222:     $id=&make_key($name,$id);
1.599     albertel 3223:     my $value = $memcache->get($id);
                   3224:     if (!(defined($value))) {
                   3225: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 3226: 	return (undef,undef);
1.416     albertel 3227:     }
1.599     albertel 3228:     if ($value eq '__undef__') {
                   3229: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   3230: 	$value=undef;
                   3231:     }
1.1319    damieng  3232:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3233:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   3234:     return ($value,1);
                   3235: }
                   3236: 
                   3237: sub do_cache_new {
                   3238:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  3239:     my $remembered_id=$name.':'.$id;
1.849     albertel 3240:     $id=&make_key($name,$id);
1.599     albertel 3241:     my $setvalue=$value;
                   3242:     if (!defined($setvalue)) {
                   3243: 	$setvalue='__undef__';
                   3244:     }
1.623     albertel 3245:     if (!defined($time) ) {
                   3246: 	$time=600;
                   3247:     }
1.599     albertel 3248:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 3249:     my $result = $memcache->set($id,$setvalue,$time);
                   3250:     if (! $result) {
1.872     albertel 3251: 	&logthis("caching of id -> $id  failed");
1.910     albertel 3252: 	$memcache->disconnect_all();
1.872     albertel 3253:     }
1.600     albertel 3254:     # need to make a copy of $value
1.1319    damieng  3255:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3256:     return $value;
                   3257: }
                   3258: 
                   3259: sub make_room {
1.1319    damieng  3260:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3261: 
1.1319    damieng  3262:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3263:                                     : $value;
1.599     albertel 3264:     if ($to_remember<0) { return; }
1.1319    damieng  3265:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3266:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3267:     my $to_kick;
                   3268:     my $max_time=0;
                   3269:     foreach my $other (keys(%accessed)) {
                   3270: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3271: 	    $to_kick=$other;
                   3272: 	    $max_time=&tv_interval($accessed{$other});
                   3273: 	}
                   3274:     }
                   3275:     delete($remembered{$to_kick});
                   3276:     delete($accessed{$to_kick});
                   3277:     $kicks++;
                   3278:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3279:     return;
                   3280: }
                   3281: 
1.599     albertel 3282: sub purge_remembered {
1.604     albertel 3283:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3284:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3285:     undef(%remembered);
                   3286:     undef(%accessed);
1.428     albertel 3287: }
1.70      www      3288: # ------------------------------------- Read an entry from a user's environment
                   3289: 
                   3290: sub userenvironment {
                   3291:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3292:     my $items;
                   3293:     foreach my $item (@what) {
                   3294:         $items.=&escape($item).'&';
                   3295:     }
                   3296:     $items=~s/\&$//;
1.70      www      3297:     my %returnhash=();
1.1009    raeburn  3298:     my $uhome = &homeserver($unam,$udom);
                   3299:     unless ($uhome eq 'no_host') {
                   3300:         my @answer=split(/\&/, 
                   3301:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3302:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3303:             return %returnhash;
                   3304:         }
1.1009    raeburn  3305:         my $i;
                   3306:         for ($i=0;$i<=$#what;$i++) {
                   3307: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3308:         }
1.70      www      3309:     }
                   3310:     return %returnhash;
1.1       albertel 3311: }
                   3312: 
1.617     albertel 3313: # ---------------------------------------------------------- Get a studentphoto
                   3314: sub studentphoto {
                   3315:     my ($udom,$unam,$ext) = @_;
                   3316:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3317:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3318:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3319:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3320:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3321:             } else {
                   3322:                 my ($result,$perm_reqd)=
1.707     albertel 3323: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3324:                 if ($result eq 'ok') {
                   3325:                     if (!($perm_reqd eq 'yes')) {
                   3326:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3327:                     }
                   3328:                 }
                   3329:             }
                   3330:         }
                   3331:     } else {
                   3332:         my ($result,$perm_reqd) = 
1.707     albertel 3333: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3334:         if ($result eq 'ok') {
                   3335:             if (!($perm_reqd eq 'yes')) {
                   3336:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3337:             }
                   3338:         }
                   3339:     }
                   3340:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3341: }
                   3342: 
                   3343: sub retrievestudentphoto {
                   3344:     my ($udom,$unam,$ext,$type) = @_;
                   3345:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3346:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3347:     if ($ret eq 'ok') {
                   3348:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3349:         if ($type eq 'thumbnail') {
                   3350:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3351:         }
                   3352:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3353:         return $tokenurl;
                   3354:     } else {
                   3355:         if ($type eq 'thumbnail') {
                   3356:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3357:         } else { 
                   3358:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3359:         }
1.617     albertel 3360:     }
                   3361: }
                   3362: 
1.263     www      3363: # -------------------------------------------------------------------- New chat
                   3364: 
                   3365: sub chatsend {
1.724     raeburn  3366:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3367:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3368:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3369:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3370:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3371: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3372: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3373: }
                   3374: 
                   3375: # ------------------------------------------ Find current version of a resource
                   3376: 
                   3377: sub getversion {
                   3378:     my $fname=&clutter(shift);
1.1189    raeburn  3379:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3380:     return &currentversion(&filelocation('',$fname));
                   3381: }
                   3382: 
                   3383: sub currentversion {
                   3384:     my $fname=shift;
                   3385:     my $author=$fname;
                   3386:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3387:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3388:     my $home=&homeserver($uname,$udom);
1.292     www      3389:     if ($home eq 'no_host') { 
                   3390:         return -1; 
                   3391:     }
1.1112    www      3392:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3393:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3394: 	return -1;
                   3395:     }
1.1112    www      3396:     return $answer;
1.263     www      3397: }
                   3398: 
1.1111    www      3399: #
                   3400: # Return special version number of resource if set by override, empty otherwise
                   3401: #
                   3402: sub usedversion {
                   3403:     my $fname=shift;
                   3404:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3405:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3406:     if ($urlversion) { return $urlversion; }
                   3407:     return '';
                   3408: }
                   3409: 
1.1       albertel 3410: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3411: 
1.1       albertel 3412: sub subscribe {
                   3413:     my $fname=shift;
1.761     raeburn  3414:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3415:     $fname=~s/[\n\r]//g;
1.1       albertel 3416:     my $author=$fname;
                   3417:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3418:     my ($udom,$uname)=split(/\//,$author);
                   3419:     my $home=homeserver($uname,$udom);
1.335     albertel 3420:     if ($home eq 'no_host') {
                   3421:         return 'not_found';
1.1       albertel 3422:     }
                   3423:     my $answer=reply("sub:$fname",$home);
1.64      www      3424:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3425: 	$answer.=' by '.$home;
                   3426:     }
1.1       albertel 3427:     return $answer;
                   3428: }
                   3429:     
1.8       www      3430: # -------------------------------------------------------------- Replicate file
                   3431: 
                   3432: sub repcopy {
                   3433:     my $filename=shift;
1.23      www      3434:     $filename=~s/\/+/\//g;
1.1142    raeburn  3435:     my $londocroot = $perlvar{'lonDocRoot'};
                   3436:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3437:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3438:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3439: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3440: 	return &repcopy_userfile($filename);
                   3441:     }
1.532     albertel 3442:     $filename=~s/[\n\r]//g;
1.8       www      3443:     my $transname="$filename.in.transfer";
1.828     www      3444: # FIXME: this should flock
1.607     raeburn  3445:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3446:     my $remoteurl=subscribe($filename);
1.64      www      3447:     if ($remoteurl =~ /^con_lost by/) {
                   3448: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3449:            return 'unavailable';
1.8       www      3450:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3451: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3452: 	   return 'not_found';
1.64      www      3453:     } elsif ($remoteurl =~ /^rejected by/) {
                   3454: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3455:            return 'forbidden';
1.20      www      3456:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3457:            return 'ok';
1.8       www      3458:     } else {
1.290     www      3459:         my $author=$filename;
                   3460:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3461:         my ($udom,$uname)=split(/\//,$author);
                   3462:         my $home=homeserver($uname,$udom);
                   3463:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3464:            my @parts=split(/\//,$filename);
                   3465:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3466:            if ($path ne "$londocroot/res") {
1.8       www      3467:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3468: 	       return 'bad_request';
1.8       www      3469:            }
                   3470:            my $count;
                   3471:            for ($count=5;$count<$#parts;$count++) {
                   3472:                $path.="/$parts[$count]";
                   3473:                if ((-e $path)!=1) {
                   3474: 		   mkdir($path,0777);
                   3475:                }
                   3476:            }
                   3477:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3478:            my $response;
                   3479:            if ($remoteurl =~ m{/raw/}) {
                   3480:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3481:            } else {
                   3482:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3483:            }
1.8       www      3484:            if ($response->is_error()) {
                   3485: 	       unlink($transname);
                   3486:                my $message=$response->status_line;
1.672     albertel 3487:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3488:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3489:                return 'unavailable';
1.8       www      3490:            } else {
1.16      www      3491: 	       if ($remoteurl!~/\.meta$/) {
                   3492:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3493:                   my $mresponse;
                   3494:                   if ($remoteurl =~ m{/raw/}) {
                   3495:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3496:                   } else {
                   3497:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3498:                   }
1.16      www      3499:                   if ($mresponse->is_error()) {
                   3500: 		      unlink($filename.'.meta');
                   3501:                       &logthis(
1.672     albertel 3502:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3503:                   }
                   3504: 	       }
1.8       www      3505:                rename($transname,$filename);
1.607     raeburn  3506:                return 'ok';
1.8       www      3507:            }
1.290     www      3508:        }
1.8       www      3509:     }
1.330     www      3510: }
                   3511: 
1.1422    raeburn  3512: # ------------------------------------------------- Unsubscribe from a resource
                   3513: 
                   3514: sub unsubscribe {
                   3515:     my ($fname) = @_;
                   3516:     my $answer;
                   3517:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3518:     $fname=~s/[\n\r]//g;
                   3519:     my $author=$fname;
                   3520:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3521:     my ($udom,$uname)=split(/\//,$author);
                   3522:     my $home=homeserver($uname,$udom);
                   3523:     if ($home eq 'no_host') {
                   3524:         $answer = 'no_host';
                   3525:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3526:         $answer = 'home';
                   3527:     } else {
                   3528:         my $defdom = $perlvar{'lonDefDomain'};
                   3529:         if (&will_trust('content',$defdom,$udom)) {
                   3530:             $answer = reply("unsub:$fname",$home);
                   3531:         } else {
                   3532:             $answer = 'untrusted';
                   3533:         }
                   3534:     }
                   3535:     return $answer;
                   3536: }
                   3537: 
1.330     www      3538: # ------------------------------------------------ Get server side include body
                   3539: sub ssi_body {
1.381     albertel 3540:     my ($filelink,%form)=@_;
1.606     matthew  3541:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3542:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3543:     }
1.953     www      3544:     my $output='';
                   3545:     my $response;
1.980     raeburn  3546:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3547:        ($output,$response)=&externalssi($filelink);
1.953     www      3548:     } else {
1.1004    droeschl 3549:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3550:        $filelink .= 'inhibitmenu=yes';
1.953     www      3551:        ($output,$response)=&ssi($filelink,%form);
                   3552:     }
1.778     albertel 3553:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3554:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3555:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3556:     if (wantarray) {
                   3557:         return ($output, $response);
                   3558:     } else {
                   3559:         return $output;
                   3560:     }
1.8       www      3561: }
                   3562: 
1.15      www      3563: # --------------------------------------------------------- Server Side Include
                   3564: 
1.782     albertel 3565: sub absolute_url {
1.1447    raeburn  3566:     my ($host_name,$unalias,$keep_proto) = @_;
1.782     albertel 3567:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3568:     if ($host_name eq '') {
                   3569: 	$host_name = $ENV{'SERVER_NAME'};
                   3570:     }
1.1447    raeburn  3571:     if ($unalias) {
                   3572:         my $alias = &get_proxy_alias();
                   3573:         if ($alias eq $host_name) {
                   3574:             my $lonhost = $perlvar{'lonHostID'};
                   3575:             my $hostname = &hostname($lonhost);
                   3576:             my $lcproto; 
                   3577:             if (($keep_proto) || ($hostname eq '')) {
                   3578:                 $lcproto = $protocol;
                   3579:             } else {
                   3580:                 $lcproto = $protocol{$lonhost};
                   3581:                 $lcproto = 'http' if ($lcproto ne 'https');
                   3582:                 $lcproto .= '://';
                   3583:             }
                   3584:             unless ($hostname eq '') {
                   3585:                 return $lcproto.$hostname;
                   3586:             }
                   3587:         }
                   3588:     }
1.782     albertel 3589:     return $protocol.$host_name;
                   3590: }
                   3591: 
1.942     foxr     3592: #
                   3593: #   Server side include.
                   3594: # Parameters:
                   3595: #  fn     Possibly encrypted resource name/id.
                   3596: #  form   Hash that describes how the rendering should be done
                   3597: #         and other things.
1.944     foxr     3598: # Returns:
1.950     raeburn  3599: #   Scalar context: The content of the response.
                   3600: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3601: #     
1.15      www      3602: sub ssi {
                   3603: 
1.944     foxr     3604:     my ($fn,%form)=@_;
1.1447    raeburn  3605:     my ($host,$request,$response);
                   3606:     $host = &absolute_url('',1);
1.711     albertel 3607: 
                   3608:     $form{'no_update_last_known'}=1;
1.895     albertel 3609:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3610:     if (%form) {
1.1447    raeburn  3611:       $request=new HTTP::Request('POST',$host.$fn);
1.1272    droeschl 3612:       $request->content(join('&',map { 
                   3613:             my $name = escape($_);
                   3614:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3615:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3616:             : &escape($form{$_}) );    
                   3617:         } keys(%form)));
1.23      www      3618:     } else {
1.1447    raeburn  3619:       $request=new HTTP::Request('GET',$host.$fn);
1.23      www      3620:     }
                   3621: 
1.15      www      3622:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3623:     my $lonhost = $perlvar{'lonHostID'};
1.1385    raeburn  3624:     my $islocal;
                   3625:     if (($env{'request.course.id'}) &&
                   3626:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3627:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3628:         ($form{'grade_symb'} ne '') &&
                   3629:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3630:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
                   3631:         $islocal = 1;
                   3632:     }
1.1447    raeburn  3633:     $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
                   3634:                                              '','','',$islocal);
1.1182    foxr     3635: 
1.944     foxr     3636:     if (wantarray) {
1.1345    raeburn  3637: 	return ($response->content, $response);
1.944     foxr     3638:     } else {
1.1345    raeburn  3639: 	return $response->content;
1.942     foxr     3640:     }
1.324     www      3641: }
                   3642: 
                   3643: sub externalssi {
                   3644:     my ($url)=@_;
                   3645:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3646:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3647:     if (wantarray) {
                   3648:         return ($response->content, $response);
                   3649:     } else {
                   3650:         return $response->content;
                   3651:     }
1.15      www      3652: }
1.254     www      3653: 
1.1354    raeburn  3654: 
                   3655: # If the local copy of a replicated resource is outdated, trigger a  
                   3656: # connection from the homeserver to flush the delayed queue. If no update 
                   3657: # happens, remove local copies of outdated resource (and corresponding
                   3658: # metadata file).
                   3659: 
1.1352    raeburn  3660: sub remove_stale_resfile {
                   3661:     my ($url) = @_;
1.1354    raeburn  3662:     my $removed;
1.1352    raeburn  3663:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3664:         my $audom = $1;
                   3665:         my $auname = $2;
1.1353    raeburn  3666:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3667:             my $homeserver = &homeserver($auname,$audom);
                   3668:             unless (($homeserver eq 'no_host') ||
                   3669:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3670:                 my $fname = &filelocation('',$url);
                   3671:                 if (-e $fname) {
                   3672:                     my $hostname = &hostname($homeserver);
                   3673:                     if ($hostname) {
1.1397    raeburn  3674:                         my $protocol = $protocol{$homeserver};
                   3675:                         $protocol = 'http' if ($protocol ne 'https');
1.1352    raeburn  3676:                         my $uri = &declutter($url);
                   3677:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3678:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3679:                         if ($response->is_success()) {
                   3680:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3681:                             my $locmodtime = (stat($fname))[9];
                   3682:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3683:                                 my $stale;
                   3684:                                 my $answer = &reply('pong',$homeserver);
                   3685:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3686:                                     sleep(0.2);
                   3687:                                     $locmodtime = (stat($fname))[9];
                   3688:                                     if ($locmodtime < $remmodtime) {
                   3689:                                         my $posstransfer = $fname.'.in.transfer';
                   3690:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3691:                                             $removed = 1;
                   3692:                                         } else {
                   3693:                                             $stale = 1;
                   3694:                                         }
                   3695:                                     } else {
                   3696:                                         $removed = 1;
                   3697:                                     }
                   3698:                                 } else {
                   3699:                                     $stale = 1;
                   3700:                                 }
                   3701:                                 if ($stale) {
1.1421    raeburn  3702:                                     if (unlink($fname)) {
                   3703:                                         if ($uri!~/\.meta$/) {
                   3704:                                             if (-e $fname.'.meta') {
                   3705:                                                 unlink($fname.'.meta');
                   3706:                                             }
                   3707:                                         }
1.1422    raeburn  3708:                                         my $unsubresult = &unsubscribe($fname);
                   3709:                                         unless ($unsubresult eq 'ok') {
                   3710:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3711:                                         }
1.1421    raeburn  3712:                                         $removed = 1;
1.1354    raeburn  3713:                                     }
1.1352    raeburn  3714:                                 }
                   3715:                             }
                   3716:                         }
                   3717:                     }
                   3718:                 }
                   3719:             }
                   3720:         }
                   3721:     }
1.1354    raeburn  3722:     return $removed;
1.1352    raeburn  3723: }
                   3724: 
1.492     albertel 3725: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3726: 
                   3727: sub allowuploaded {
                   3728:     my ($srcurl,$url)=@_;
                   3729:     $url=&clutter(&declutter($url));
                   3730:     my $dir=$url;
                   3731:     $dir=~s/\/[^\/]+$//;
                   3732:     my %httpref=();
                   3733:     my $httpurl=&hreflocation('',$url);
                   3734:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3735:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3736: }
1.477     raeburn  3737: 
1.1193    raeburn  3738: #
                   3739: # Determine if the current user should be able to edit a particular resource,
                   3740: # when viewing in course context.
                   3741: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3742: #     Functions.
                   3743: # (b) When displaying folder contents in course editor, used to determine if
                   3744: #     "Edit" link will be displayed alongside resource.
                   3745: #
1.1196    raeburn  3746: #  input: six args -- filename (decluttered), course number, course domain,
                   3747: #                   url, symb (if registered) and group (if this is a group
                   3748: #                   item -- e.g., bulletin board, group page etc.).
                   3749: #  output: array of five scalars -- 
1.1193    raeburn  3750: #          $cfile -- url for file editing if editable on current server
                   3751: #          $home -- homeserver of resource (i.e., for author if published,
                   3752: #                                           or course if uploaded.).
                   3753: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3754: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3755: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3756: #
                   3757: 
                   3758: sub can_edit_resource {
1.1194    raeburn  3759:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3760:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3761: #
                   3762: # For aboutme pages user can only edit his/her own.
                   3763: #
1.1199    raeburn  3764:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3765:         my ($sdom,$sname) = ($1,$2);
                   3766:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3767:             $home = $env{'user.home'};
                   3768:             $cfile = $resurl;
                   3769:             if ($env{'form.forceedit'}) {
                   3770:                 $forceview = 1;
                   3771:             } else {
                   3772:                 $forceedit = 1;
                   3773:             }
                   3774:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3775:         } else {
                   3776:             return;
                   3777:         }
                   3778:     }
                   3779: 
                   3780:     if ($env{'request.course.id'}) {
                   3781:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3782:         if ($group ne '') {
                   3783: # if this is a group homepage or group bulletin board, check group privs
                   3784:             my $allowed = 0;
1.1197    raeburn  3785:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3786:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3787:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3788:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3789:                     $allowed = 1;
                   3790:                 }
1.1197    raeburn  3791:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3792:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3793:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3794:                     $allowed = 1;
                   3795:                 }
                   3796:             }
                   3797:             if ($allowed) {
                   3798:                 $home=&homeserver($cnum,$cdom);
                   3799:                 if ($env{'form.forceedit'}) {
                   3800:                     $forceview = 1;
                   3801:                 } else {
                   3802:                     $forceedit = 1;
                   3803:                 }
                   3804:                 $cfile = $resurl;
                   3805:             } else {
                   3806:                 return;
                   3807:             }
                   3808:         } else {
1.1208    raeburn  3809:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3810:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3811:                     return;
                   3812:                 }
                   3813:             } elsif (!$crsedit) {
1.1194    raeburn  3814: #
                   3815: # No edit allowed where CC has switched to student role.
                   3816: #
                   3817:                 return;
                   3818:             }
                   3819:         }
                   3820:     }
                   3821: 
1.1193    raeburn  3822:     if ($file ne '') {
                   3823:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3824:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3825:                 $uploaded = 1;
                   3826:                 $incourse = 1;
1.1193    raeburn  3827:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3828:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3829:                     if ($env{'form.forceedit'}) {
                   3830:                         $forceview = 1;
                   3831:                     } else {
                   3832:                         $forceedit = 1;
                   3833:                     }
1.1194    raeburn  3834:                 }
                   3835:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3836:                 $incourse = 1;
                   3837:                 if ($env{'form.forceedit'}) {
                   3838:                     $forceview = 1;
                   3839:                 } else {
                   3840:                     $forceedit = 1;
                   3841:                 }
                   3842:                 $cfile = $resurl;
                   3843:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3844:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3845:                     $incourse = 1;
                   3846:                     if ($env{'form.forceedit'}) {
                   3847:                         $forceview = 1;
                   3848:                     } else {
                   3849:                         $forceedit = 1;
                   3850:                     }
                   3851:                     $cfile = $resurl;
1.1199    raeburn  3852:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3853:                     $incourse = 1;
                   3854:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3855:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3856:                     $incourse = 1;
1.1199    raeburn  3857:                     if ($env{'form.forceedit'}) {
                   3858:                         $forceview = 1;
                   3859:                     } else {
                   3860:                         $forceedit = 1;
                   3861:                     }
                   3862:                     $cfile = $resurl;
1.1419    raeburn  3863:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3864:                     my ($map,$id,$res) = &decode_symb($symb);
                   3865:                     if ($map =~ /\.page$/) {
                   3866:                         $incourse = 1;
                   3867:                         if ($env{'form.forceedit'}) {
                   3868:                             $forceview = 1;
                   3869:                             $cfile = $map;
                   3870:                         } else {
                   3871:                             $forceedit = 1;
                   3872:                             $cfile =  '/adm/wrapper'.$resurl;
                   3873:                         }
                   3874:                     }
1.1343    raeburn  3875:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3876:                     $incourse = 1;
                   3877:                     if ($env{'form.forceedit'}) {
                   3878:                         $forceview = 1;
                   3879:                     } else {
                   3880:                         $forceedit = 1;
                   3881:                     }
                   3882:                     $cfile = $resurl;
1.1208    raeburn  3883:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3884:                     $incourse = 1;
                   3885:                     if ($env{'form.forceedit'}) {
                   3886:                         $forceview = 1;
                   3887:                     } else {
                   3888:                         $forceedit = 1;
                   3889:                     }
                   3890:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3891:                 }
                   3892:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3893:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3894:                 if (&is_on_map($template)) { 
                   3895:                     $incourse = 1;
                   3896:                     $forceview = 1;
                   3897:                     $cfile = $template;
1.1193    raeburn  3898:                 }
1.1199    raeburn  3899:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1418    raeburn  3900:                 $incourse = 1;
                   3901:                 if ($env{'form.forceedit'}) {
                   3902:                     $forceview = 1;
                   3903:                 } else {
                   3904:                     $forceedit = 1;
                   3905:                 }
                   3906:                 $cfile = $resurl;
1.1343    raeburn  3907:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3908:                 $incourse = 1;
                   3909:                 if ($env{'form.forceedit'}) {
                   3910:                     $forceview = 1;
                   3911:                 } else {
                   3912:                     $forceedit = 1;
                   3913:                 }
                   3914:                 $cfile = $resurl;
1.1199    raeburn  3915:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3916:                 $incourse = 1;
                   3917:                 $forceview = 1;
                   3918:                 if ($symb) {
                   3919:                     my ($map,$id,$res)=&decode_symb($symb);
                   3920:                     $env{'request.symb'} = $symb;
                   3921:                     $cfile = &clutter($res);
                   3922:                 } else {
                   3923:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3924:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3925:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3926:                         $cfile = '/adm/wrapper'.$escfile;
                   3927:                     } else {
                   3928:                         $escfile =~ s{^http://}{};
                   3929:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3930:                     }
1.1199    raeburn  3931:                 }
1.1234    raeburn  3932:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3933:                 if ($env{'form.forceedit'}) {
                   3934:                     $forceview = 1;
                   3935:                 } else {
                   3936:                     $forceedit = 1;
                   3937:                 }
                   3938:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3939:             }
                   3940:         }
1.1194    raeburn  3941:         if ($uploaded || $incourse) {
                   3942:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3943:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3944:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3945:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3946:             # Check that the user has permission to edit this resource
                   3947:             my $setpriv = 1;
                   3948:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3949:             if (defined($cfudom)) {
                   3950:                 $home=&homeserver($cfuname,$cfudom);
                   3951:                 $cfile=$file;
                   3952:             }
                   3953:         }
1.1194    raeburn  3954:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3955:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3956:             my @ids=&current_machine_ids();
                   3957:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3958:                 $switchserver=1;
                   3959:             }
                   3960:         }
                   3961:     }
1.1194    raeburn  3962:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3963: }
                   3964: 
                   3965: sub is_course_upload {
                   3966:     my ($file,$cnum,$cdom) = @_;
                   3967:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3968:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3969:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3970:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3971:         return 1;
                   3972:     }
                   3973:     return;
                   3974: }
                   3975: 
1.1194    raeburn  3976: sub in_course {
1.1195    raeburn  3977:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3978:     if ($hideprivileged) {
                   3979:         my $skipuser;
1.1219    raeburn  3980:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3981:         my @possdoms = ($cdom);  
                   3982:         if ($coursehash{'checkforpriv'}) { 
                   3983:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3984:         }
                   3985:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3986:             $skipuser = 1;
                   3987:             if ($coursehash{'nothideprivileged'}) {
                   3988:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3989:                     my $user;
                   3990:                     if ($item =~ /:/) {
                   3991:                         $user = $item;
                   3992:                     } else {
                   3993:                         $user = join(':',split(/[\@]/,$item));
                   3994:                     }
                   3995:                     if ($user eq $uname.':'.$udom) {
                   3996:                         undef($skipuser);
                   3997:                         last;
                   3998:                     }
                   3999:                 }
                   4000:             }
                   4001:             if ($skipuser) {
                   4002:                 return 0;
                   4003:             }
                   4004:         }
                   4005:     }
1.1194    raeburn  4006:     $type ||= 'any';
                   4007:     if (!defined($cdom) || !defined($cnum)) {
                   4008:         my $cid  = $env{'request.course.id'};
                   4009:         $cdom = $env{'course.'.$cid.'.domain'};
                   4010:         $cnum = $env{'course.'.$cid.'.num'};
                   4011:     }
                   4012:     my $typesref;
1.1195    raeburn  4013:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  4014:         $typesref = ['active','previous','future'];
                   4015:     } elsif ($type eq 'previous' || $type eq 'future') {
                   4016:         $typesref = [$type];
                   4017:     }
                   4018:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   4019:                               $typesref,undef,[$cdom]);
                   4020:     my ($tmp) = keys(%roles);
                   4021:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   4022:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   4023:     if (@course_roles > 0) {
                   4024:         return 1;
                   4025:     }
                   4026:     return 0;
                   4027: }
                   4028: 
1.478     albertel 4029: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 4030: # input: action, courseID, current domain, intended
1.637     raeburn  4031: #        path to file, source of file, instruction to parse file for objects,
                   4032: #        ref to hash for embedded objects,
                   4033: #        ref to hash for codebase of java objects.
1.1095    raeburn  4034: #        reference to scalar to accommodate mime type determined
                   4035: #          from File::MMagic if $parser = parse.
1.637     raeburn  4036: #
1.485     raeburn  4037: # output: url to file (if action was uploaddoc), 
                   4038: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  4039: #
1.478     albertel 4040: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   4041: # course.
1.477     raeburn  4042: #
1.478     albertel 4043: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   4044: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   4045: #          course's home server.
1.477     raeburn  4046: #
1.478     albertel 4047: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   4048: #          be copied from $source (current location) to 
                   4049: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   4050: #         and will then be copied to
                   4051: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   4052: #         course's home server.
1.485     raeburn  4053: #
1.481     raeburn  4054: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 4055: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  4056: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   4057: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   4058: #         in course's home server.
1.637     raeburn  4059: #
1.477     raeburn  4060: 
                   4061: sub process_coursefile {
1.1095    raeburn  4062:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   4063:         $mimetype)=@_;
1.477     raeburn  4064:     my $fetchresult;
1.638     albertel 4065:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  4066:     if ($action eq 'propagate') {
1.638     albertel 4067:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   4068: 			     $home);
1.481     raeburn  4069:     } else {
1.477     raeburn  4070:         my $fpath = '';
                   4071:         my $fname = $file;
1.478     albertel 4072:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  4073:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  4074:         my $filepath = &build_filepath($fpath);
1.481     raeburn  4075:         if ($action eq 'copy') {
                   4076:             if ($source eq '') {
                   4077:                 $fetchresult = 'no source file';
                   4078:                 return $fetchresult;
                   4079:             } else {
                   4080:                 my $destination = $filepath.'/'.$fname;
                   4081:                 rename($source,$destination);
                   4082:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4083:                                  $home);
1.481     raeburn  4084:             }
                   4085:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  4086:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 4087:             print $fh $env{'form.'.$source};
1.481     raeburn  4088:             close($fh);
1.637     raeburn  4089:             if ($parser eq 'parse') {
1.1024    raeburn  4090:                 my $mm = new File::MMagic;
1.1095    raeburn  4091:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   4092:                 if ($type eq 'text/html') {
1.1024    raeburn  4093:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   4094:                     unless ($parse_result eq 'ok') {
                   4095:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   4096:                     }
1.637     raeburn  4097:                 }
1.1095    raeburn  4098:                 if (ref($mimetype)) {
                   4099:                     $$mimetype = $type;
                   4100:                 } 
1.637     raeburn  4101:             }
1.477     raeburn  4102:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4103:                                  $home);
1.481     raeburn  4104:             if ($fetchresult eq 'ok') {
                   4105:                 return '/uploaded/'.$fpath.'/'.$fname;
                   4106:             } else {
                   4107:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 4108:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  4109:                 return '/adm/notfound.html';
                   4110:             }
1.477     raeburn  4111:         }
                   4112:     }
1.485     raeburn  4113:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  4114:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 4115:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  4116:     }
                   4117:     return $fetchresult;
                   4118: }
                   4119: 
1.637     raeburn  4120: sub build_filepath {
                   4121:     my ($fpath) = @_;
                   4122:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   4123:     unless ($fpath eq '') {
                   4124:         my @parts=split('/',$fpath);
                   4125:         foreach my $part (@parts) {
                   4126:             $filepath.= '/'.$part;
                   4127:             if ((-e $filepath)!=1) {
                   4128:                 mkdir($filepath,0777);
                   4129:             }
                   4130:         }
                   4131:     }
                   4132:     return $filepath;
                   4133: }
                   4134: 
                   4135: sub store_edited_file {
1.638     albertel 4136:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  4137:     my $file = $primary_url;
                   4138:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   4139:     my $fpath = '';
                   4140:     my $fname = $file;
                   4141:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   4142:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   4143:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  4144:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  4145:     print $fh $content;
                   4146:     close($fh);
1.638     albertel 4147:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  4148:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4149: 			  $home);
1.637     raeburn  4150:     if ($$fetchresult eq 'ok') {
                   4151:         return '/uploaded/'.$fpath.'/'.$fname;
                   4152:     } else {
1.638     albertel 4153:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   4154: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  4155:         return '/adm/notfound.html';
                   4156:     }
                   4157: }
                   4158: 
1.531     albertel 4159: sub clean_filename {
1.831     albertel 4160:     my ($fname,$args)=@_;
1.315     www      4161: # Replace Windows backslashes by forward slashes
1.257     www      4162:     $fname=~s/\\/\//g;
1.831     albertel 4163:     if (!$args->{'keep_path'}) {
                   4164:         # Get rid of everything but the actual filename
                   4165: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   4166:     }
1.315     www      4167: # Replace spaces by underscores
                   4168:     $fname=~s/\s+/\_/g;
1.1406    raeburn  4169: # Transliterate non-ascii text to ascii
                   4170:     my $lang = &Apache::lonlocal::current_language();
                   4171:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      4172: # Replace all other weird characters by nothing
1.831     albertel 4173:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 4174: # Replace all .\d. sequences with _\d. so they no longer look like version
                   4175: # numbers
                   4176:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1443    raeburn  4177: # Replace three or more adjacent underscores with one for consistency 
                   4178: # with loncfile::filename_check() so complete url can be extracted by
                   4179: # lonnet::decode_symb()
                   4180:     $fname=~s/_{3,}/_/g;
1.531     albertel 4181:     return $fname;
                   4182: }
1.1406    raeburn  4183: 
1.1051    raeburn  4184: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   4185: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   4186: # image with the same aspect ratio as the original, but with dimensions which do 
                   4187: # not exceed $resizewidth and $resizeheight.
                   4188:  
1.984     neumanie 4189: sub resizeImage {
1.1051    raeburn  4190:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   4191:     my $ima = Image::Magick->new;
                   4192:     my $resized;
                   4193:     if (-e $img_path) {
                   4194:         $ima->Read($img_path);
                   4195:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   4196:             my $width = $ima->Get('width');
                   4197:             my $height = $ima->Get('height');
                   4198:             if ($width > $resizewidth) {
                   4199: 	        my $factor = $width/$resizewidth;
                   4200:                 my $newheight = $height/$factor;
                   4201:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   4202:                 $resized = 1;
                   4203:             }
                   4204:         }
                   4205:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   4206:             my $width = $ima->Get('width');
                   4207:             my $height = $ima->Get('height');
                   4208:             if ($height > $resizeheight) {
                   4209:                 my $factor = $height/$resizeheight;
                   4210:                 my $newwidth = $width/$factor;
                   4211:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   4212:                 $resized = 1;
                   4213:             }
                   4214:         }
                   4215:         if ($resized) {
                   4216:             $ima->Write($img_path);
                   4217:         }
                   4218:     }
                   4219:     return;
1.977     amueller 4220: }
                   4221: 
1.608     albertel 4222: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 4223: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  4224: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  4225: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1401    raeburn  4226: #                                    canceloverwrite, scantron or ''.
1.1090    raeburn  4227: #                   if 'coursedoc': upload to the current course
                   4228: #                   if 'existingfile': write file to tmp/overwrites directory 
                   4229: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   4230: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 4231: #        $subdir - directory in userfile to store the file into
1.1401    raeburn  4232: #        $parser - instruction to parse file for objects ($parser = parse) or
                   4233: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   4234: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
                   4235: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  4236: #        $allfiles - reference to hash for embedded objects
                   4237: #        $codebase - reference to hash for codebase of java objects
                   4238: #        $desuname - username for permanent storage of uploaded file
                   4239: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  4240: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   4241: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  4242: #        $resizewidth - width (pixels) to which to resize uploaded image
                   4243: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  4244: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  4245: #                    from File::MMagic.
1.858     raeburn  4246: # 
1.686     albertel 4247: # output: url of file in userspace, or error: <message> 
                   4248: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 4249: 
1.531     albertel 4250: sub userfileupload {
1.1090    raeburn  4251:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  4252:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 4253:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 4254:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 4255:     $fname=&clean_filename($fname);
1.1090    raeburn  4256:     # See if there is anything left
1.257     www      4257:     unless ($fname) { return 'error: no uploaded file'; }
1.1406    raeburn  4258:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   4259:     if ($fname =~ /^\./) {
                   4260:         my ($s,$usec) = &gettimeofday();
                   4261:         while (length($usec) < 6) {
                   4262:             $usec = '0'.$usec;
                   4263:         }
                   4264:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   4265:     }
1.1090    raeburn  4266:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   4267:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   4268:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   4269:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  4270:         my $now = time;
1.1090    raeburn  4271:         my $filepath;
1.1095    raeburn  4272:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  4273:              $filepath = 'tmp/helprequests/'.$now;
                   4274:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   4275:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   4276:                          '_'.$env{'user.domain'}.'/pending';
                   4277:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   4278:             my ($docuname,$docudom);
1.1350    raeburn  4279:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  4280:                 $docudom = $destudom;
                   4281:             } else {
                   4282:                 $docudom = $env{'user.domain'};
                   4283:             }
1.1350    raeburn  4284:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  4285:                 $docuname = $destuname;
                   4286:             } else {
                   4287:                 $docuname = $env{'user.name'};
                   4288:             }
                   4289:             if (exists($env{'form.group'})) {
                   4290:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4291:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4292:             }
                   4293:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   4294:             if ($context eq 'canceloverwrite') {
                   4295:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   4296:                 if (-e  $tempfile) {
                   4297:                     my @info = stat($tempfile);
                   4298:                     if ($info[9] eq $env{'form.timestamp'}) {
                   4299:                         unlink($tempfile);
                   4300:                     }
                   4301:                 }
                   4302:                 return;
1.523     raeburn  4303:             }
                   4304:         }
1.1090    raeburn  4305:         # Create the directory if not present
1.741     raeburn  4306:         my @parts=split(/\//,$filepath);
                   4307:         my $fullpath = $perlvar{'lonDaemons'};
                   4308:         for (my $i=0;$i<@parts;$i++) {
                   4309:             $fullpath .= '/'.$parts[$i];
                   4310:             if ((-e $fullpath)!=1) {
                   4311:                 mkdir($fullpath,0777);
                   4312:             }
                   4313:         }
1.1359    raeburn  4314:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  4315:         print $fh $env{'form.'.$formname};
                   4316:         close($fh);
1.1090    raeburn  4317:         if ($context eq 'existingfile') {
                   4318:             my @info = stat($fullpath.'/'.$fname);
                   4319:             return ($fullpath.'/'.$fname,$info[9]);
                   4320:         } else {
                   4321:             return $fullpath.'/'.$fname;
                   4322:         }
1.523     raeburn  4323:     }
1.995     raeburn  4324:     if ($subdir eq 'scantron') {
                   4325:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4326:     } else {
1.995     raeburn  4327:         $fname="$subdir/$fname";
                   4328:     }
1.1090    raeburn  4329:     if ($context eq 'coursedoc') {
1.638     albertel 4330: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4331: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4332:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4333:             return &finishuserfileupload($docuname,$docudom,
                   4334: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4335: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4336:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4337:         } else {
1.1218    raeburn  4338:             if ($env{'form.folder'}) {
                   4339:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4340:             }
1.638     albertel 4341:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4342: 				       $fname,$formname,$parser,
1.1095    raeburn  4343: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4344:         }
1.719     banghart 4345:     } elsif (defined($destuname)) {
                   4346:         my $docuname=$destuname;
                   4347:         my $docudom=$destudom;
1.860     raeburn  4348: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4349: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4350:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4351:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4352:     } else {
1.638     albertel 4353:         my $docuname=$env{'user.name'};
                   4354:         my $docudom=$env{'user.domain'};
1.1220    raeburn  4355:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4356:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4357:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4358:         }
1.860     raeburn  4359: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4360: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4361:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4362:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4363:     }
1.271     www      4364: }
                   4365: 
                   4366: sub finishuserfileupload {
1.860     raeburn  4367:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4368:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4369:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4370:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4371:   
1.860     raeburn  4372:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4373:     $file=$fname;
                   4374:     if ($fname=~m|/|) {
                   4375:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4376: 	$path.=$fnamepath.'/';
                   4377:     }
1.259     www      4378:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4379:     my $count;
                   4380:     for ($count=4;$count<=$#parts;$count++) {
                   4381:         $filepath.="/$parts[$count]";
                   4382:         if ((-e $filepath)!=1) {
                   4383: 	    mkdir($filepath,0777);
                   4384:         }
                   4385:     }
1.984     neumanie 4386: 
1.258     www      4387: # Save the file
                   4388:     {
1.1359    raeburn  4389: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4390: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4391: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4392: 	    return '/adm/notfound.html';
                   4393: 	}
1.1090    raeburn  4394:         if ($context eq 'overwrite') {
1.1117    foxr     4395:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4396:             my $target = $filepath.'/'.$file;
                   4397:             if (-e $source) {
                   4398:                 my @info = stat($source);
                   4399:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4400:                     unless (&File::Copy::move($source,$target)) {
                   4401:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4402:                         return "Moving from $source failed";
                   4403:                     }
                   4404:                 } else {
                   4405:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4406:                 }
                   4407:             } else {
                   4408:                 return "Temporary file: $source missing";
                   4409:             }
                   4410:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4411: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4412: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4413: 	    return '/adm/notfound.html';
                   4414: 	}
1.570     albertel 4415: 	close(FH);
1.1051    raeburn  4416:         if ($resizewidth && $resizeheight) {
                   4417:             my $mm = new File::MMagic;
                   4418:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4419:             if ($mime_type =~ m{^image/}) {
                   4420: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4421:             }  
1.977     amueller 4422: 	}
1.258     www      4423:     }
1.1152    raeburn  4424:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4425:         if (ref($mimetype)) {
                   4426:             if ($$mimetype eq '') {
                   4427:                 my $mm = new File::MMagic;
                   4428:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4429:                 $$mimetype = $type;
                   4430:             }
                   4431:         }
                   4432:     }
1.1401    raeburn  4433:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4434:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4435:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4436:                                                        $allfiles,$codebase);
                   4437:             unless ($parse_result eq 'ok') {
                   4438:                 &logthis('Failed to parse '.$filepath.$file.
                   4439: 	   	         ' for embedded media: '.$parse_result); 
                   4440:             }
1.637     raeburn  4441:         }
1.1401    raeburn  4442:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4443:         my $format = $env{'form.scantron_format'};
                   4444:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4445:     }
1.860     raeburn  4446:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4447:         my $input = $filepath.'/'.$file;
                   4448:         my $output = $filepath.'/'.'tn-'.$file;
                   4449:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  4450:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4451:         system({$args[0]} @args);
1.860     raeburn  4452:         if (-e $filepath.'/'.'tn-'.$file) {
                   4453:             $fetchthumb  = 1; 
                   4454:         }
                   4455:     }
1.858     raeburn  4456:  
1.259     www      4457: # Notify homeserver to grep it
                   4458: #
1.984     neumanie 4459:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4460:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4461:     if ($fetchresult eq 'ok') {
1.860     raeburn  4462:         if ($fetchthumb) {
                   4463:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4464:             if ($thumbresult ne 'ok') {
                   4465:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4466:                          $docuhome.': '.$thumbresult);
                   4467:             }
                   4468:         }
1.259     www      4469: #
1.258     www      4470: # Return the URL to it
1.494     albertel 4471:         return '/uploaded/'.$path.$file;
1.263     www      4472:     } else {
1.494     albertel 4473:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4474: 		 ': '.$fetchresult);
1.263     www      4475:         return '/adm/notfound.html';
1.858     raeburn  4476:     }
1.493     albertel 4477: }
                   4478: 
1.637     raeburn  4479: sub extract_embedded_items {
1.961     raeburn  4480:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4481:     my @state = ();
1.1164    raeburn  4482:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4483:     my %javafiles = (
                   4484:                       codebase => '',
                   4485:                       code => '',
                   4486:                       archive => ''
                   4487:                     );
                   4488:     my %mediafiles = (
                   4489:                       src => '',
                   4490:                       movie => '',
                   4491:                      );
1.648     raeburn  4492:     my $p;
                   4493:     if ($content) {
                   4494:         $p = HTML::LCParser->new($content);
                   4495:     } else {
1.961     raeburn  4496:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4497:     }
1.641     albertel 4498:     while (my $t=$p->get_token()) {
1.640     albertel 4499: 	if ($t->[0] eq 'S') {
                   4500: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4501: 	    push(@state, $tagname);
1.648     raeburn  4502:             if (lc($tagname) eq 'allow') {
                   4503:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4504:             }
1.640     albertel 4505: 	    if (lc($tagname) eq 'img') {
                   4506: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4507: 	    }
1.886     albertel 4508: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4509:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4510:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4511:                 }
1.886     albertel 4512: 	    }
1.645     raeburn  4513:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4514:                 my $src;
1.645     raeburn  4515:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4516:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4517:                 } else {
1.1164    raeburn  4518:                     if ($attr->{'src'} ne '') {
                   4519:                         $src = $attr->{'src'};
                   4520:                         &add_filetype($allfiles,$src,'src');
                   4521:                     }
                   4522:                 }
                   4523:                 my $text = $p->get_trimmed_text();
                   4524:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4525:                     my @swfargs = split(/,/,$1);
                   4526:                     foreach my $item (@swfargs) {
                   4527:                         $item =~ s/["']//g;
                   4528:                         $item =~ s/^\s+//;
                   4529:                         $item =~ s/\s+$//;
                   4530:                     }
                   4531:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4532:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4533:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4534:                         } else {
                   4535:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4536:                         }
                   4537:                     }
1.645     raeburn  4538:                 }
                   4539:             }
                   4540:             if (lc($tagname) eq 'link') {
                   4541:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4542:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4543:                 }
                   4544:             }
1.640     albertel 4545: 	    if (lc($tagname) eq 'object' ||
                   4546: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4547: 		foreach my $item (keys(%javafiles)) {
                   4548: 		    $javafiles{$item} = '';
                   4549: 		}
1.1164    raeburn  4550:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4551:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4552:                 }
1.640     albertel 4553: 	    }
                   4554: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4555: 		my $name = lc($attr->{'name'});
                   4556: 		foreach my $item (keys(%javafiles)) {
                   4557: 		    if ($name eq $item) {
                   4558: 			$javafiles{$item} = $attr->{'value'};
                   4559: 			last;
                   4560: 		    }
                   4561: 		}
1.1164    raeburn  4562:                 my $pathfrom;
1.640     albertel 4563: 		foreach my $item (keys(%mediafiles)) {
                   4564: 		    if ($name eq $item) {
1.1164    raeburn  4565:                         $pathfrom = $attr->{'value'};
                   4566:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4567: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4568: 			last;
                   4569: 		    }
                   4570: 		}
1.1164    raeburn  4571:                 if ($name eq 'flashvars') {
                   4572:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4573:                 }
                   4574:                 if ($pathfrom ne '') {
                   4575:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4576:                                          $pathfrom);
                   4577:                 }
1.640     albertel 4578: 	    }
                   4579: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4580: 		foreach my $item (keys(%javafiles)) {
                   4581: 		    if ($attr->{$item}) {
                   4582: 			$javafiles{$item} = $attr->{$item};
                   4583: 			last;
                   4584: 		    }
                   4585: 		}
                   4586: 		foreach my $item (keys(%mediafiles)) {
                   4587: 		    if ($attr->{$item}) {
                   4588: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4589: 			last;
                   4590: 		    }
                   4591: 		}
1.1164    raeburn  4592:                 if (lc($tagname) eq 'embed') {
                   4593:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4594:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4595:                                              $attr->{'src'});
                   4596:                     }
                   4597:                 }
1.640     albertel 4598: 	    }
1.1243    raeburn  4599:             if (lc($tagname) eq 'iframe') {
                   4600:                 my $src = $attr->{'src'} ;
                   4601:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4602:                     &add_filetype($allfiles,$src,'src');
                   4603:                 } elsif ($src =~ m{^/}) {
                   4604:                     if ($env{'request.course.id'}) {
                   4605:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4606:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4607:                         my $url = &hreflocation('',$fullpath);
                   4608:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4609:                             my $relpath = $1;
                   4610:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4611:                                 &add_filetype($allfiles,$1,'src');
                   4612:                             }
                   4613:                         }
                   4614:                     }
                   4615:                 }
                   4616:             }
1.1164    raeburn  4617:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4618:                 pop(@state);
1.1164    raeburn  4619:             }
1.640     albertel 4620: 	} elsif ($t->[0] eq 'E') {
                   4621: 	    my ($tagname) = ($t->[1]);
                   4622: 	    if ($javafiles{'codebase'} ne '') {
                   4623: 		$javafiles{'codebase'} .= '/';
                   4624: 	    }  
                   4625: 	    if (lc($tagname) eq 'applet' ||
                   4626: 		lc($tagname) eq 'object' ||
                   4627: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4628: 		) {
                   4629: 		foreach my $item (keys(%javafiles)) {
                   4630: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4631: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4632: 			&add_filetype($allfiles,$file,$item);
                   4633: 		    }
                   4634: 		}
                   4635: 	    } 
                   4636: 	    pop @state;
                   4637: 	}
                   4638:     }
1.1164    raeburn  4639:     foreach my $id (sort(keys(%flashvars))) {
                   4640:         if ($shockwave{$id} ne '') {
                   4641:             my @pairs = split(/\&/,$flashvars{$id});
                   4642:             foreach my $pair (@pairs) {
                   4643:                 my ($key,$value) = split(/\=/,$pair);
                   4644:                 if ($key eq 'thumb') {
                   4645:                     &add_filetype($allfiles,$value,$key);
                   4646:                 } elsif ($key eq 'content') {
                   4647:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4648:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4649:                     if ($ext ne '') {
                   4650:                         &add_filetype($allfiles,$path.$value,$ext);
                   4651:                     }
                   4652:                 }
                   4653:             }
                   4654:         }
                   4655:     }
1.637     raeburn  4656:     return 'ok';
                   4657: }
                   4658: 
1.639     albertel 4659: sub add_filetype {
                   4660:     my ($allfiles,$file,$type)=@_;
                   4661:     if (exists($allfiles->{$file})) {
                   4662: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4663: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4664: 	}
                   4665:     } else {
                   4666: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4667:     }
                   4668: }
                   4669: 
1.1164    raeburn  4670: sub embedded_dependency {
                   4671:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4672:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4673:         if (($identifier ne '') &&
                   4674:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4675:             ($pathfrom ne '')) {
                   4676:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4677:             foreach my $dep (@{$related->{$identifier}}) {
                   4678:                 &add_filetype($allfiles,$path.$dep,'object');
                   4679:             }
                   4680:         }
                   4681:     }
                   4682:     return;
                   4683: }
                   4684: 
1.1401    raeburn  4685: sub bubblesheet_converter {
                   4686:     my ($cdom,$fullpath,$config,$format) = @_;
                   4687:     if ((&domain($cdom) ne '') &&
1.1403    raeburn  4688:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401    raeburn  4689:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404    raeburn  4690:         my (%csvcols,%csvoptions);
                   4691:         if (ref($config->{'fields'}) eq 'HASH') {  
                   4692:             %csvcols = %{$config->{'fields'}};
                   4693:         }
                   4694:         if (ref($config->{'options'}) eq 'HASH') {
                   4695:             %csvoptions = %{$config->{'options'}};
                   4696:         }
1.1401    raeburn  4697:         my %csvbynum = reverse(%csvcols);
                   4698:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4699:         if (keys(%scantronconf)) {
                   4700:             my %bynum = (
                   4701:                           $scantronconf{CODEstart} => 'CODEstart',
                   4702:                           $scantronconf{IDstart}   => 'IDstart',
                   4703:                           $scantronconf{PaperID}   => 'PaperID',
                   4704:                           $scantronconf{FirstName} => 'FirstName',
                   4705:                           $scantronconf{LastName}  => 'LastName',
                   4706:                           $scantronconf{Qstart}    => 'Qstart',
                   4707:                         );
                   4708:             my @ordered;
                   4709:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403    raeburn  4710:                 push(@ordered,$bynum{$item});
1.1401    raeburn  4711:             }
                   4712:             my %mapstart = (
                   4713:                               CODEstart => 'CODE',
                   4714:                               IDstart   => 'ID',
                   4715:                               PaperID   => 'PaperID',
                   4716:                               FirstName => 'FirstName',
                   4717:                               LastName  => 'LastName',
                   4718:                               Qstart    => 'FirstQuestion',
                   4719:                            );
                   4720:             my %maplength = (
                   4721:                               CODEstart => 'CODElength',
                   4722:                               IDstart   => 'IDlength',
                   4723:                               PaperID   => 'PaperIDlength',
                   4724:                               FirstName => 'FirstNamelength',
                   4725:                               LastName  => 'LastNamelength',
                   4726:             );
                   4727:             if (open(my $fh,'<',$fullpath)) {
                   4728:                 my $output;
1.1403    raeburn  4729:                 my %lettdig = &letter_to_digits();
                   4730:                 my %diglett = reverse(%lettdig);
                   4731:                 my $numletts = scalar(keys(%lettdig));
1.1404    raeburn  4732:                 my $num = 0;
1.1401    raeburn  4733:                 while (my $line=<$fh>) {
1.1404    raeburn  4734:                     $num ++;
                   4735:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401    raeburn  4736:                     $line =~ s{[\r\n]+$}{};
                   4737:                     my %found;
1.1475    raeburn  4738:                     my @values = split(/,/,$line,-1);
1.1401    raeburn  4739:                     my ($qstart,$record);
                   4740:                     for (my $i=0; $i<@values; $i++) {
1.1403    raeburn  4741:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4742:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4743:                             if ($values[$i] eq '') {
                   4744:                                 $values[$i] = $scantronconf{'Qoff'};
                   4745:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4746:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4747:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4748:                                 }
                   4749:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4750:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4751:                                     $values[$i] = $diglett{$values[$i]};
                   4752:                                 }
                   4753:                             } else {
                   4754:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4755:                                     my $digit;
                   4756:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4757:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4758:                                         if ($values[$i] eq 'J') {
                   4759:                                             $digit += $numletts;
                   4760:                                         }
                   4761:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4762:                                         $digit = $values[$i]-1;
                   4763:                                         if ($values[$i] eq '0') {
                   4764:                                             $digit += $numletts;
                   4765:                                         }
                   4766:                                     }
                   4767:                                     my $qval='';
                   4768:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4769:                                         if ($j == $digit) {
                   4770:                                             $qval .= $scantronconf{'Qon'};
                   4771:                                         } else {
                   4772:                                             $qval .= $scantronconf{'Qoff'};
                   4773:                                         }
                   4774:                                     }
                   4775:                                     $values[$i] = $qval;
                   4776:                                 }
                   4777:                             }
                   4778:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4779:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4780:                             }
                   4781:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4782:                             if ($numblank > 0) {
                   4783:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4784:                             }
1.1401    raeburn  4785:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4786:                                 $qstart = $i;
1.1403    raeburn  4787:                                 $found{$csvbynum{$i}} = $values[$i];
1.1401    raeburn  4788:                             } else {
1.1403    raeburn  4789:                                 $found{'FirstQuestion'} .= $values[$i];
                   4790:                             }
                   4791:                         } elsif (exists($csvbynum{$i})) {
1.1404    raeburn  4792:                             if ($csvoptions{'rem'}) {
                   4793:                                 $values[$i] =~ s/^\s+//;
                   4794:                             }
                   4795:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403    raeburn  4796:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4797:                                     $values[$i] = '0'.$values[$i];
1.1401    raeburn  4798:                                 }
                   4799:                             }
                   4800:                             $found{$csvbynum{$i}} = $values[$i];
                   4801:                         }
                   4802:                     }
                   4803:                     foreach my $item (@ordered) {
                   4804:                         my $currlength = 1+length($record);
                   4805:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4806:                         if ($numspaces > 0) {
                   4807:                             $record .= (' ' x $numspaces);
                   4808:                         }
                   4809:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4810:                             unless ($item eq 'Qstart') {
                   4811:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4812:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4813:                                 }
                   4814:                             }
                   4815:                             $record .= $found{$mapstart{$item}};
                   4816:                         }
                   4817:                     }
                   4818:                     $output .= "$record\n";
                   4819:                 }
                   4820:                 close($fh);
                   4821:                 if ($output) {
                   4822:                     if (open(my $fh,'>',$fullpath)) {
                   4823:                         print $fh $output;
                   4824:                         close($fh);
                   4825:                     }
                   4826:                 }
                   4827:             }
                   4828:         }
                   4829:         return;
                   4830:     }
                   4831: }
                   4832: 
1.1403    raeburn  4833: sub letter_to_digits {
                   4834:     my %lettdig = (
                   4835:                     A => 1,
                   4836:                     B => 2,
                   4837:                     C => 3,
                   4838:                     D => 4,
                   4839:                     E => 5,
                   4840:                     F => 6,
                   4841:                     G => 7,
                   4842:                     H => 8,
                   4843:                     I => 9,
                   4844:                     J => 0,
                   4845:                   );
                   4846:     return %lettdig;
                   4847: }
                   4848: 
1.1401    raeburn  4849: sub get_scantron_config {
                   4850:     my ($which,$cdom) = @_;
                   4851:     my @lines = &get_scantronformat_file($cdom);
                   4852:     my %config;
                   4853:     #FIXME probably should move to XML it has already gotten a bit much now
                   4854:     foreach my $line (@lines) {
                   4855:         my ($name,$descrip)=split(/:/,$line);
                   4856:         if ($name ne $which ) { next; }
                   4857:         chomp($line);
                   4858:         my @config=split(/:/,$line);
                   4859:         $config{'name'}=$config[0];
                   4860:         $config{'description'}=$config[1];
                   4861:         $config{'CODElocation'}=$config[2];
                   4862:         $config{'CODEstart'}=$config[3];
                   4863:         $config{'CODElength'}=$config[4];
                   4864:         $config{'IDstart'}=$config[5];
                   4865:         $config{'IDlength'}=$config[6];
                   4866:         $config{'Qstart'}=$config[7];
                   4867:         $config{'Qlength'}=$config[8];
                   4868:         $config{'Qoff'}=$config[9];
                   4869:         $config{'Qon'}=$config[10];
                   4870:         $config{'PaperID'}=$config[11];
                   4871:         $config{'PaperIDlength'}=$config[12];
                   4872:         $config{'FirstName'}=$config[13];
                   4873:         $config{'FirstNamelength'}=$config[14];
                   4874:         $config{'LastName'}=$config[15];
                   4875:         $config{'LastNamelength'}=$config[16];
                   4876:         $config{'BubblesPerRow'}=$config[17];
                   4877:         last;
                   4878:     }
                   4879:     return %config;
                   4880: }
                   4881: 
                   4882: sub get_scantronformat_file {
                   4883:     my ($cdom) = @_;
                   4884:     if ($cdom eq '') {
                   4885:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4886:     }
                   4887:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4888:     my $gottab = 0;
                   4889:     my @lines;
                   4890:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4891:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4892:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4893:             if ($formatfile ne '-1') {
                   4894:                 @lines = split("\n",$formatfile,-1);
                   4895:                 $gottab = 1;
                   4896:             }
                   4897:         }
                   4898:     }
                   4899:     if (!$gottab) {
                   4900:         my $confname = $cdom.'-domainconfig';
                   4901:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4902:         my $formatfile = &getfile($default);
                   4903:         if ($formatfile ne '-1') {
                   4904:             @lines = split("\n",$formatfile,-1);
                   4905:             $gottab = 1;
                   4906:         }
                   4907:     }
                   4908:     if (!$gottab) {
                   4909:         my @domains = &current_machine_domains();
                   4910:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4911:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4912:                 @lines = <$fh>;
                   4913:                 close($fh);
1.1403    raeburn  4914:             }
1.1401    raeburn  4915:         } else {
                   4916:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4917:                 @lines = <$fh>;
                   4918:                 close($fh);
                   4919:             }
                   4920:         }
1.1488    raeburn  4921:         chomp(@lines);
1.1401    raeburn  4922:     }
                   4923:     return @lines;
                   4924: }
                   4925: 
1.493     albertel 4926: sub removeuploadedurl {
1.984     neumanie 4927:     my ($url)=@_;	
                   4928:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4929:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4930: }
                   4931: 
                   4932: sub removeuserfile {
                   4933:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4934:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4935:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4936:     if ($result eq 'ok') {	
1.798     raeburn  4937:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4938:             my $metafile = $fname.'.meta';
                   4939:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4940: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4941:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4942:             my $sqlresult = 
1.823     albertel 4943:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4944:                                         'portfolio_metadata',$group,
                   4945:                                         'delete');
1.798     raeburn  4946:         }
                   4947:     }
                   4948:     return $result;
1.257     www      4949: }
1.15      www      4950: 
1.530     albertel 4951: sub mkdiruserfile {
                   4952:     my ($docuname,$docudom,$dir)=@_;
                   4953:     my $home=&homeserver($docuname,$docudom);
                   4954:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4955: }
                   4956: 
1.531     albertel 4957: sub renameuserfile {
                   4958:     my ($docuname,$docudom,$old,$new)=@_;
                   4959:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4960:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4961:                         &escape("$old").':'.&escape("$new"),$home);
                   4962:     if ($result eq 'ok') {
                   4963:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4964:             my $oldmeta = $old.'.meta';
                   4965:             my $newmeta = $new.'.meta';
                   4966:             my $metaresult = 
                   4967:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4968: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4969:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4970:             my $sqlresult = 
1.823     albertel 4971:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4972:                                         'portfolio_metadata',$group,
                   4973:                                         'delete');
1.798     raeburn  4974:         }
                   4975:     }
                   4976:     return $result;
1.531     albertel 4977: }
                   4978: 
1.14      www      4979: # ------------------------------------------------------------------------- Log
                   4980: 
                   4981: sub log {
                   4982:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4983:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4984: }
                   4985: 
                   4986: # ------------------------------------------------------------------ Course Log
1.352     www      4987: #
                   4988: # This routine flushes several buffers of non-mission-critical nature
                   4989: #
1.157     www      4990: 
                   4991: sub flushcourselogs {
1.352     www      4992:     &logthis('Flushing log buffers');
                   4993: #
                   4994: # course logs
                   4995: # This is a log of all transactions in a course, which can be used
                   4996: # for data mining purposes
                   4997: #
                   4998: # It also collects the courseid database, which lists last transaction
                   4999: # times and course titles for all courseids
                   5000: #
                   5001:     my %courseidbuffer=();
1.921     raeburn  5002:     foreach my $crsid (keys(%courselogs)) {
1.352     www      5003:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      5004: 		          &escape($courselogs{$crsid}),
                   5005: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      5006: 	    delete $courselogs{$crsid};
                   5007:         } else {
                   5008:             &logthis('Failed to flush log buffer for '.$crsid);
                   5009:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 5010:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      5011:                         " exceeded maximum size, deleting.</font>");
                   5012:                delete $courselogs{$crsid};
                   5013:             }
1.352     www      5014:         }
1.920     raeburn  5015:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  5016:             'description' => $coursedescrbuf{$crsid},
                   5017:             'inst_code'    => $courseinstcodebuf{$crsid},
                   5018:             'type'        => $coursetypebuf{$crsid},
                   5019:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  5020:         };
1.191     harris41 5021:     }
1.352     www      5022: #
                   5023: # Write course id database (reverse lookup) to homeserver of courses 
                   5024: # Is used in pickcourse
                   5025: #
1.840     albertel 5026:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  5027:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  5028:                                     $courseidbuffer{$crs_home},
                   5029:                                     $crs_home,'timeonly');
1.352     www      5030:     }
                   5031: #
                   5032: # File accesses
                   5033: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   5034: #
1.449     matthew  5035:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  5036:         if ($entry =~ /___count$/) {
                   5037:             my ($dom,$name);
1.807     albertel 5038:             ($dom,$name,undef)=
1.811     albertel 5039: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  5040:             if (! defined($dom) || $dom eq '' || 
                   5041:                 ! defined($name) || $name eq '') {
1.620     albertel 5042:                 my $cid = $env{'request.course.id'};
1.1472    raeburn  5043: #
                   5044: # FIXME 11/29/2021
                   5045: # Typo in rev. 1.458 (2003/12/09)??
                   5046: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
                   5047: #
                   5048: # While these ramain as  $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
                   5049: # $dom and $name will always be null, so the &inc() call will default to storing this data
                   5050: # in a nohist_accesscount.db file for the user rather than the course.
                   5051: #
                   5052: # That said there is a lot of noise in the data being stored.
                   5053: # So counts for prtspool/  and adm/ etc. are recorded.
                   5054: #
                   5055: # A review of which items ending '___count' are written to %accesshash should likely be 
                   5056: # made before deciding whether to set these to 'course.' instead of 'request.'
                   5057: #
                   5058: # Under the current scheme each user receives a nohist_accesscount.db file listing 
                   5059: # accesses for things which are not published resources, regardless of course, and
                   5060: # there is not a nohist_accesscount.db file in a course, which might log accesses from
                   5061: # anyone in the course for things which are not published resources.
                   5062: #
                   5063: # For an author, nohist_accesscount.db ends up having records for other items
                   5064: # mixed up with the legitimate access counts for the author's published resources.
                   5065: #
1.620     albertel 5066:                 $dom  = $env{'request.'.$cid.'.domain'};
                   5067:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  5068:             }
1.450     matthew  5069:             my $value = $accesshash{$entry};
                   5070:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   5071:             my %temphash=($url => $value);
1.449     matthew  5072:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   5073:             if ($result eq 'ok') {
                   5074:                 delete $accesshash{$entry};
                   5075:             }
                   5076:         } else {
1.811     albertel 5077:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      5078:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  5079:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  5080:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   5081:                 delete $accesshash{$entry};
                   5082:             }
1.185     www      5083:         }
1.191     harris41 5084:     }
1.352     www      5085: #
                   5086: # Roles
                   5087: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   5088: #
1.800     albertel 5089:     foreach my $entry (keys(%userrolehash)) {
1.351     www      5090:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      5091: 	    split(/\:/,$entry);
                   5092:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      5093:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      5094:                 $rudom,$runame) eq 'ok') {
                   5095: 	    delete $userrolehash{$entry};
                   5096:         }
                   5097:     }
1.662     raeburn  5098: #
1.1334    raeburn  5099: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  5100: #
                   5101:     my %domrolebuffer = ();
1.1000    raeburn  5102:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 5103:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  5104:         if ($domrolebuffer{$rudom}) {
                   5105:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   5106:                       '='.&escape($domainrolehash{$entry});
                   5107:         } else {
                   5108:             $domrolebuffer{$rudom}.=&escape($entry).
                   5109:                       '='.&escape($domainrolehash{$entry});
                   5110:         }
                   5111:         delete $domainrolehash{$entry};
                   5112:     }
                   5113:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  5114: 	my %servers;
                   5115: 	if (defined(&domain($dom,'primary'))) {
                   5116: 	    my $primary=&domain($dom,'primary');
                   5117: 	    my $hostname=&hostname($primary);
                   5118: 	    $servers{$primary} = $hostname;
                   5119: 	} else { 
                   5120: 	    %servers = &get_servers($dom,'library');
                   5121: 	}
1.841     albertel 5122: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  5123: 	    if (&reply('domroleput:'.$dom.':'.
                   5124: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   5125: 		last;
                   5126: 	    } else {  
1.841     albertel 5127: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   5128: 	    }
1.662     raeburn  5129:         }
                   5130:     }
1.186     www      5131:     $dumpcount++;
1.157     www      5132: }
                   5133: 
                   5134: sub courselog {
                   5135:     my $what=shift;
1.158     www      5136:     $what=time.':'.$what;
1.620     albertel 5137:     unless ($env{'request.course.id'}) { return ''; }
                   5138:     $coursedombuf{$env{'request.course.id'}}=
                   5139:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5140:     $coursenumbuf{$env{'request.course.id'}}=
                   5141:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   5142:     $coursehombuf{$env{'request.course.id'}}=
                   5143:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   5144:     $coursedescrbuf{$env{'request.course.id'}}=
                   5145:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   5146:     $courseinstcodebuf{$env{'request.course.id'}}=
                   5147:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   5148:     $courseownerbuf{$env{'request.course.id'}}=
                   5149:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  5150:     $coursetypebuf{$env{'request.course.id'}}=
                   5151:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 5152:     if (defined $courselogs{$env{'request.course.id'}}) {
                   5153: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      5154:     } else {
1.620     albertel 5155: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      5156:     }
1.620     albertel 5157:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      5158: 	&flushcourselogs();
                   5159:     }
1.158     www      5160: }
                   5161: 
                   5162: sub courseacclog {
                   5163:     my $fnsymb=shift;
1.620     albertel 5164:     unless ($env{'request.course.id'}) { return ''; }
                   5165:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      5166:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      5167:         $what.=':POST';
1.583     matthew  5168:         # FIXME: Probably ought to escape things....
1.800     albertel 5169: 	foreach my $key (keys(%env)) {
                   5170:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  5171:                 my $formitem = $1;
                   5172:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   5173:                     $what.=':'.$formitem.'='.$env{$key};
                   5174:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1432    raeburn  5175:                     if ($formitem eq 'proctorpassword') {
1.1433    raeburn  5176:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1432    raeburn  5177:                     } else {
                   5178:                         $what.=':'.$formitem.'='.$env{$key};
                   5179:                     }
1.975     raeburn  5180:                 }
1.158     www      5181:             }
1.191     harris41 5182:         }
1.583     matthew  5183:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   5184:         # FIXME: We should not be depending on a form parameter that someone
                   5185:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 5186:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  5187:             $what.= ':POST';
                   5188:             # FIXME: Probably ought to escape things....
                   5189:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   5190:                                  'crsdiscuss') {
1.620     albertel 5191:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  5192:             }
                   5193:         }
1.158     www      5194:     }
                   5195:     &courselog($what);
1.149     www      5196: }
                   5197: 
1.185     www      5198: sub countacc {
                   5199:     my $url=&declutter(shift);
1.458     matthew  5200:     return if (! defined($url) || $url eq '');
1.620     albertel 5201:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      5202: #
                   5203: # Mark that this url was used in this course
                   5204: #
1.620     albertel 5205:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      5206: #
                   5207: # Increase the access count for this resource in this child process
                   5208: #
1.281     www      5209:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  5210:     $accesshash{$key}++;
1.185     www      5211: }
1.349     www      5212: 
1.361     www      5213: sub linklog {
                   5214:     my ($from,$to)=@_;
                   5215:     $from=&declutter($from);
                   5216:     $to=&declutter($to);
                   5217:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   5218:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   5219: }
1.1160    www      5220: 
                   5221: sub statslog {
                   5222:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   5223:     if ($users<2) { return; }
                   5224:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   5225:             'course'       => $env{'request.course.id'},
                   5226:             'sections'     => '"all"',
                   5227:             'num_students' => $users,
                   5228:             'part'         => $part,
                   5229:             'symb'         => $symb,
                   5230:             'mean_tries'   => $av_attempts,
                   5231:             'deg_of_diff'  => $degdiff});
                   5232:     foreach my $key (keys(%dynstore)) {
                   5233:         $accesshash{$key}=$dynstore{$key};
                   5234:     }
                   5235: }
1.361     www      5236:   
1.349     www      5237: sub userrolelog {
                   5238:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 5239:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      5240:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5241:        $userrolehash
                   5242:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      5243:                     =$tend.':'.$tstart;
1.662     raeburn  5244:     }
1.1169    droeschl 5245:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 5246:        $userrolehash
                   5247:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   5248:                     =$tend.':'.$tstart;
                   5249:     }
1.1334    raeburn  5250:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  5251:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5252:        $domainrolehash
                   5253:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   5254:                     = $tend.':'.$tstart;
                   5255:     }
1.351     www      5256: }
                   5257: 
1.957     raeburn  5258: sub courserolelog {
                   5259:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  5260:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   5261:         my $cdom = $1;
                   5262:         my $cnum = $2;
                   5263:         my $sec = $3;
                   5264:         my $namespace = 'rolelog';
                   5265:         my %storehash = (
                   5266:                            role    => $trole,
                   5267:                            start   => $tstart,
                   5268:                            end     => $tend,
                   5269:                            selfenroll => $selfenroll,
                   5270:                            context    => $context,
                   5271:                         );
                   5272:         if ($trole eq 'gr') {
                   5273:             $namespace = 'groupslog';
                   5274:             $storehash{'group'} = $sec;
                   5275:         } else {
                   5276:             $storehash{'section'} = $sec;
                   5277:         }
1.1188    raeburn  5278:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   5279:                    $domain,$cnum,$cdom);
1.1184    raeburn  5280:         if (($trole ne 'st') || ($sec ne '')) {
                   5281:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  5282:         }
                   5283:     }
                   5284:     return;
                   5285: }
                   5286: 
1.1184    raeburn  5287: sub domainrolelog {
                   5288:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5289:     if ($area =~ m{^/($match_domain)/$}) {
                   5290:         my $cdom = $1;
                   5291:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   5292:         my $namespace = 'rolelog';
                   5293:         my %storehash = (
                   5294:                            role    => $trole,
                   5295:                            start   => $tstart,
                   5296:                            end     => $tend,
                   5297:                            context => $context,
                   5298:                         );
1.1188    raeburn  5299:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5300:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  5301:     }
                   5302:     return;
                   5303: 
                   5304: }
                   5305: 
                   5306: sub coauthorrolelog {
                   5307:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5308:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5309:         my $audom = $1;
                   5310:         my $auname = $2;
                   5311:         my $namespace = 'rolelog';
                   5312:         my %storehash = (
                   5313:                            role    => $trole,
                   5314:                            start   => $tstart,
                   5315:                            end     => $tend,
                   5316:                            context => $context,
                   5317:                         );
1.1188    raeburn  5318:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5319:                    $domain,$auname,$audom);
1.1184    raeburn  5320:     }
                   5321:     return;
                   5322: }
                   5323: 
1.351     www      5324: sub get_course_adv_roles {
1.948     raeburn  5325:     my ($cid,$codes) = @_;
1.620     albertel 5326:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5327:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5328:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5329:     my %nothide=();
1.800     albertel 5330:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5331:         if ($user !~ /:/) {
                   5332: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5333:         } else {
                   5334:             $nothide{$user}=1;
                   5335:         }
1.470     www      5336:     }
1.1219    raeburn  5337:     my @possdoms = ($coursehash{'domain'});
                   5338:     if ($coursehash{'checkforpriv'}) {
                   5339:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5340:     }
1.351     www      5341:     my %returnhash=();
                   5342:     my %dumphash=
                   5343:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5344:     my $now=time;
1.997     raeburn  5345:     my %privileged;
1.1000    raeburn  5346:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5347: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5348:         if (($tstart) && ($tstart<0)) { next; }
                   5349:         if (($tend) && ($tend<$now)) { next; }
                   5350:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5351:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5352: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  5353:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5354:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5355: 	if ($role eq 'cr') { next; }
1.948     raeburn  5356:         if ($codes) {
                   5357:             if ($section) { $role .= ':'.$section; }
                   5358:             if ($returnhash{$role}) {
                   5359:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5360:             } else {
                   5361:                 $returnhash{$role}=$username.':'.$domain;
                   5362:             }
1.351     www      5363:         } else {
1.988     raeburn  5364:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5365:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5366:             if ($returnhash{$key}) {
                   5367: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5368:             } else {
                   5369:                 $returnhash{$key}=$username.':'.$domain;
                   5370:             }
1.351     www      5371:         }
1.948     raeburn  5372:     }
1.400     www      5373:     return %returnhash;
                   5374: }
                   5375: 
                   5376: sub get_my_roles {
1.937     raeburn  5377:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5378:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5379:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5380:     my (%dumphash,%nothide);
1.1086    raeburn  5381:     if ($context eq 'userroles') {
1.1166    raeburn  5382:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5383:     } else {
1.1219    raeburn  5384:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5385:         if ($hidepriv) {
                   5386:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5387:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5388:                 if ($user !~ /:/) {
                   5389:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5390:                 } else {
                   5391:                     $nothide{$user} = 1;
                   5392:                 }
                   5393:             }
                   5394:         }
1.858     raeburn  5395:     }
1.400     www      5396:     my %returnhash=();
                   5397:     my $now=time;
1.999     raeburn  5398:     my %privileged;
1.800     albertel 5399:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5400:         my ($role,$tend,$tstart);
                   5401:         if ($context eq 'userroles') {
1.1149    raeburn  5402:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5403: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5404:         } else {
                   5405:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5406:         }
1.400     www      5407:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5408:         my $status = 'active';
1.939     raeburn  5409:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5410:             $status = 'previous';
                   5411:         } 
                   5412:         if (($tstart) && ($now<$tstart)) {
                   5413:             $status = 'future';
                   5414:         }
                   5415:         if (ref($types) eq 'ARRAY') {
                   5416:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5417:                 next;
                   5418:             } 
                   5419:         } else {
                   5420:             if ($status ne 'active') {
                   5421:                 next;
                   5422:             }
                   5423:         }
1.867     raeburn  5424:         my ($rolecode,$username,$domain,$section,$area);
                   5425:         if ($context eq 'userroles') {
1.1186    raeburn  5426:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5427:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5428:         } else {
                   5429:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5430:         }
1.832     raeburn  5431:         if (ref($roledoms) eq 'ARRAY') {
                   5432:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5433:                 next;
                   5434:             }
                   5435:         }
                   5436:         if (ref($roles) eq 'ARRAY') {
                   5437:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5438:                 if ($role =~ /^cr\//) {
                   5439:                     if (!grep(/^cr$/,@{$roles})) {
                   5440:                         next;
                   5441:                     }
1.1104    raeburn  5442:                 } elsif ($role =~ /^gr\//) {
                   5443:                     if (!grep(/^gr$/,@{$roles})) {
                   5444:                         next;
                   5445:                     }
1.922     raeburn  5446:                 } else {
                   5447:                     next;
                   5448:                 }
1.832     raeburn  5449:             }
1.867     raeburn  5450:         }
1.937     raeburn  5451:         if ($hidepriv) {
1.1219    raeburn  5452:             my @privroles = ('dc','su');
1.999     raeburn  5453:             if ($context eq 'userroles') {
1.1219    raeburn  5454:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5455:             } else {
1.1219    raeburn  5456:                 my $possdoms = [$domain];
                   5457:                 if (ref($roledoms) eq 'ARRAY') {
                   5458:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  5459:                 }
1.1219    raeburn  5460:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5461:                     if (!$nothide{$username.':'.$domain}) {
                   5462:                         next;
                   5463:                     }
                   5464:                 }
1.937     raeburn  5465:             }
                   5466:         }
1.933     raeburn  5467:         if ($withsec) {
                   5468:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5469:                 $tstart.':'.$tend;
                   5470:         } else {
                   5471:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5472:         }
1.832     raeburn  5473:     }
1.373     www      5474:     return %returnhash;
1.399     www      5475: }
                   5476: 
1.1333    raeburn  5477: sub get_all_adhocroles {
                   5478:     my ($dom) = @_;
                   5479:     my @roles_by_num = ();
                   5480:     my %domdefaults = &get_domain_defaults($dom);
                   5481:     my (%description,%access_in_dom,%access_info);
                   5482:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5483:         my $count = 0;
                   5484:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5485:         my %ordered;
                   5486:         foreach my $role (sort(keys(%domcurrent))) {
                   5487:             my ($order,$desc,$access_in_dom);
                   5488:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5489:                 $order = $domcurrent{$role}{'order'};
                   5490:                 $desc = $domcurrent{$role}{'desc'};
                   5491:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5492:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5493:             }
                   5494:             if ($order eq '') {
                   5495:                 $order = $count;
                   5496:             }
                   5497:             $ordered{$order} = $role;
                   5498:             if ($desc ne '') {
                   5499:                 $description{$role} = $desc;
                   5500:             } else {
                   5501:                 $description{$role}= $role;
                   5502:             }
                   5503:             $count++;
                   5504:         }
                   5505:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5506:             push(@roles_by_num,$ordered{$item});
                   5507:         }
                   5508:     }
                   5509:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5510: }
                   5511: 
1.1332    raeburn  5512: sub get_my_adhocroles {
1.1333    raeburn  5513:     my ($cid,$checkreg) = @_;
                   5514:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5515:     if ($env{'request.course.id'} eq $cid) {
                   5516:         $cdom = $env{'course.'.$cid.'.domain'};
                   5517:         $cnum = $env{'course.'.$cid.'.num'};
                   5518:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5519:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5520:         $cdom = $1;
                   5521:         $cnum = $2;
                   5522:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5523:                                      $cdom,$cnum);
                   5524:     }
                   5525:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5526:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5527:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5528:         if ($rosterhash{$user} ne '') {
                   5529:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5530:             return ([],{}) if ($type eq 'auto');
                   5531:         }
                   5532:     }
                   5533:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  5534:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  5535:             my $then=$env{'user.login.time'};
                   5536:             my $update=$env{'user.update.time'};
1.1335    raeburn  5537:             if (!$update) {
                   5538:                 $update = $then;
                   5539:             }
                   5540:             my @liveroles;
1.1334    raeburn  5541:             foreach my $role ('dh','da') {
                   5542:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  5543:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  5544:                     my $limit = $update;
                   5545:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5546:                         $limit = $then;
                   5547:                     }
1.1335    raeburn  5548:                     my $activerole = 1;
                   5549:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5550:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5551:                     if ($activerole) {
                   5552:                         push(@liveroles,$role);
                   5553:                     }
1.1334    raeburn  5554:                 }
1.1332    raeburn  5555:             }
1.1335    raeburn  5556:             if (@liveroles) {
1.1332    raeburn  5557:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  5558:                     my ($accessref,$accessinfo,%access_in_dom);
                   5559:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5560:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5561:                         if (@{$roles_by_num}) {
1.1332    raeburn  5562:                             my %settings;
                   5563:                             if ($env{'request.course.id'} eq $cid) {
                   5564:                                 foreach my $envkey (keys(%env)) {
                   5565:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5566:                                         $settings{$1} = $env{$envkey};
                   5567:                                     }
                   5568:                                 }
                   5569:                             } else {
                   5570:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5571:                             }
                   5572:                             my %setincrs;
                   5573:                             if ($settings{'internal.adhocaccess'}) {
                   5574:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5575:                             }
                   5576:                             my @statuses;
                   5577:                             if ($env{'environment.inststatus'}) {
                   5578:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5579:                             }
                   5580:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  5581:                             if (ref($accessref) eq 'HASH') {
                   5582:                                 %access_in_dom = %{$accessref};
                   5583:                             }
                   5584:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  5585:                                 my ($curraccess,@okstatus,@personnel);
                   5586:                                 if ($setincrs{$role}) {
                   5587:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5588:                                     if ($curraccess eq 'status') {
                   5589:                                         @okstatus = split(/\&/,$rest);
                   5590:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5591:                                         @personnel = split(/\&/,$rest);
                   5592:                                     }
                   5593:                                 } else {
                   5594:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  5595:                                     if (ref($accessinfo) eq 'HASH') {
                   5596:                                         if ($curraccess eq 'status') {
                   5597:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5598:                                                 @okstatus = @{$accessinfo->{$role}};
                   5599:                                             }
                   5600:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5601:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5602:                                                 @personnel = @{$accessinfo->{$role}};
                   5603:                                             }
1.1332    raeburn  5604:                                         }
                   5605:                                     }
                   5606:                                 }
                   5607:                                 if ($curraccess eq 'none') {
                   5608:                                     next;
                   5609:                                 } elsif ($curraccess eq 'all') {
                   5610:                                     push(@possroles,$role);
1.1336    raeburn  5611:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  5612:                                     if (grep(/^dh$/,@liveroles)) {
                   5613:                                         push(@possroles,$role);
                   5614:                                     } else {
                   5615:                                         next;
                   5616:                                     }
1.1336    raeburn  5617:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  5618:                                     if (grep(/^da$/,@liveroles)) {
                   5619:                                         push(@possroles,$role);
                   5620:                                     } else {
                   5621:                                         next;
                   5622:                                     }
1.1332    raeburn  5623:                                 } elsif ($curraccess eq 'status') {
                   5624:                                     if (@okstatus) {
                   5625:                                         if (!@statuses) {
                   5626:                                             if (grep(/^default$/,@okstatus)) {
                   5627:                                                 push(@possroles,$role);
                   5628:                                             }
                   5629:                                         } else {
                   5630:                                             foreach my $status (@okstatus) {
                   5631:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5632:                                                     push(@possroles,$role);
                   5633:                                                     last;
                   5634:                                                 }
                   5635:                                             }
                   5636:                                         }
                   5637:                                     }
                   5638:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5639:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5640:                                         if ($curraccess eq 'exc') {
                   5641:                                             push(@possroles,$role);
                   5642:                                         }
                   5643:                                     } elsif ($curraccess eq 'inc') {
                   5644:                                         push(@possroles,$role);
                   5645:                                     }
                   5646:                                 }
                   5647:                             }
                   5648:                         }
                   5649:                     }
                   5650:                 }
                   5651:             }
                   5652:         }
                   5653:     }
1.1333    raeburn  5654:     unless (ref($description) eq 'HASH') {
                   5655:         if (ref($roles_by_num) eq 'ARRAY') {
                   5656:             my %desc;
                   5657:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5658:             $description = \%desc;
                   5659:         } else {
                   5660:             $description = {};
                   5661:         }
                   5662:     }
                   5663:     return (\@possroles,$description);
1.1332    raeburn  5664: }
                   5665: 
1.399     www      5666: # ----------------------------------------------------- Frontpage Announcements
                   5667: #
                   5668: #
                   5669: 
                   5670: sub postannounce {
                   5671:     my ($server,$text)=@_;
1.844     albertel 5672:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5673:     unless ($text=~/\w/) { $text=''; }
                   5674:     return &reply('setannounce:'.&escape($text),$server);
                   5675: }
                   5676: 
                   5677: sub getannounce {
1.448     albertel 5678: 
1.1359    raeburn  5679:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5680: 	my $announcement='';
1.800     albertel 5681: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5682: 	close($fh);
1.399     www      5683: 	if ($announcement=~/\w/) { 
                   5684: 	    return 
                   5685:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5686:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5687: 	} else {
                   5688: 	    return '';
                   5689: 	}
                   5690:     } else {
                   5691: 	return '';
                   5692:     }
1.351     www      5693: }
1.353     www      5694: 
                   5695: # ---------------------------------------------------------- Course ID routines
                   5696: # Deal with domain's nohist_courseid.db files
                   5697: #
                   5698: 
                   5699: sub courseidput {
1.921     raeburn  5700:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5701:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5702:     my $outcome;
                   5703:     if ($caller eq 'timeonly') {
                   5704:         my $cids = '';
                   5705:         foreach my $item (keys(%$storehash)) {
                   5706:             $cids.=&escape($item).'&';
                   5707:         }
                   5708:         $cids=~s/\&$//;
                   5709:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5710:                           $coursehome);       
                   5711:     } else {
                   5712:         my $items = '';
                   5713:         foreach my $item (keys(%$storehash)) {
                   5714:             $items.= &escape($item).'='.
                   5715:                      &freeze_escape($$storehash{$item}).'&';
                   5716:         }
                   5717:         $items=~s/\&$//;
                   5718:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5719:                           $coursehome);
1.918     raeburn  5720:     }
                   5721:     if ($outcome eq 'unknown_cmd') {
                   5722:         my $what;
                   5723:         foreach my $cid (keys(%$storehash)) {
                   5724:             $what .= &escape($cid).'=';
1.921     raeburn  5725:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5726:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5727:             }
                   5728:             $what =~ s/\:$/&/;
                   5729:         }
                   5730:         $what =~ s/\&$//;  
                   5731:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5732:     } else {
                   5733:         return $outcome;
                   5734:     }
1.353     www      5735: }
                   5736: 
                   5737: sub courseiddump {
1.921     raeburn  5738:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5739:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5740:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  5741:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  5742:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5743:     my $as_hash = 1;
                   5744:     my %returnhash;
                   5745:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5746:     my %libserv = &all_library();
                   5747:     foreach my $tryserver (keys(%libserv)) {
                   5748:         if ( (  $hostidflag == 1 
                   5749: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5750: 	     || (!defined($hostidflag)) ) {
                   5751: 
1.918     raeburn  5752: 	    if (($domfilter eq '') ||
                   5753: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5754:                 my $rep;
                   5755:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5756:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5757:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5758:                                 &escape($descfilter), &escape($instcodefilter), 
                   5759:                                 &escape($ownerfilter), &escape($coursefilter),
                   5760:                                 &escape($typefilter), &escape($regexp_ok), 
                   5761:                                 $as_hash, &escape($selfenrollonly), 
                   5762:                                 &escape($catfilter), $showhidden, $caller, 
                   5763:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5764:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5765:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5766:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5767:                 } else {
                   5768:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5769:                              $sincefilter.':'.&escape($descfilter).':'.
                   5770:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5771:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5772:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5773:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5774:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5775:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5776:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5777:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5778:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5779:                 }
                   5780:                      
1.918     raeburn  5781:                 my @pairs=split(/\&/,$rep);
                   5782:                 foreach my $item (@pairs) {
                   5783:                     my ($key,$value)=split(/\=/,$item,2);
                   5784:                     $key = &unescape($key);
                   5785:                     next if ($key =~ /^error: 2 /);
                   5786:                     my $result = &thaw_unescape($value);
                   5787:                     if (ref($result) eq 'HASH') {
                   5788:                         $returnhash{$key}=$result;
                   5789:                     } else {
1.921     raeburn  5790:                         my @responses = split(/:/,$value);
                   5791:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5792:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5793:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5794:                         }
1.1008    raeburn  5795:                     }
1.353     www      5796:                 }
                   5797:             }
                   5798:         }
                   5799:     }
                   5800:     return %returnhash;
                   5801: }
                   5802: 
1.1055    raeburn  5803: sub courselastaccess {
                   5804:     my ($cdom,$cnum,$hostidref) = @_;
                   5805:     my %returnhash;
                   5806:     if ($cdom && $cnum) {
                   5807:         my $chome = &homeserver($cnum,$cdom);
                   5808:         if ($chome ne 'no_host') {
                   5809:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5810:             &extract_lastaccess(\%returnhash,$rep);
                   5811:         }
                   5812:     } else {
                   5813:         if (!$cdom) { $cdom=''; }
                   5814:         my %libserv = &all_library();
                   5815:         foreach my $tryserver (keys(%libserv)) {
                   5816:             if (ref($hostidref) eq 'ARRAY') {
                   5817:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5818:             } 
                   5819:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5820:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5821:                 &extract_lastaccess(\%returnhash,$rep);
                   5822:             }
                   5823:         }
                   5824:     }
                   5825:     return %returnhash;
                   5826: }
                   5827: 
                   5828: sub extract_lastaccess {
                   5829:     my ($returnhash,$rep) = @_;
                   5830:     if (ref($returnhash) eq 'HASH') {
                   5831:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5832:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5833:                  $rep eq '') {
                   5834:             my @pairs=split(/\&/,$rep);
                   5835:             foreach my $item (@pairs) {
                   5836:                 my ($key,$value)=split(/\=/,$item,2);
                   5837:                 $key = &unescape($key);
                   5838:                 next if ($key =~ /^error: 2 /);
                   5839:                 $returnhash->{$key} = &thaw_unescape($value);
                   5840:             }
                   5841:         }
                   5842:     }
                   5843:     return;
                   5844: }
                   5845: 
1.658     raeburn  5846: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5847: 
                   5848: sub dcmailput {
1.685     raeburn  5849:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5850:     my $status = &Apache::lonnet::critical(
1.740     www      5851:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5852:        &escape($message),$server);
1.662     raeburn  5853:     return $status;
                   5854: }
                   5855: 
1.658     raeburn  5856: sub dcmaildump {
                   5857:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5858:     my %returnhash=();
1.846     albertel 5859: 
                   5860:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5861:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5862:                                                          &escape($enddate).':';
                   5863: 	my @esc_senders=map { &escape($_)} @$senders;
                   5864: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5865: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5866:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5867:             if (($key) && ($value)) {
                   5868:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5869:             }
                   5870:         }
                   5871:     }
                   5872:     return %returnhash;
                   5873: }
1.662     raeburn  5874: # ---------------------------------------------------------- Domain roles
                   5875: 
                   5876: sub get_domain_roles {
                   5877:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5878:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5879:         $startdate = '.';
                   5880:     }
1.1018    raeburn  5881:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5882:         $enddate = '.';
                   5883:     }
1.922     raeburn  5884:     my $rolelist;
                   5885:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5886:         $rolelist = join('&',@{$roles});
1.922     raeburn  5887:     }
1.662     raeburn  5888:     my %personnel = ();
1.841     albertel 5889: 
                   5890:     my %servers = &get_servers($dom,'library');
                   5891:     foreach my $tryserver (keys(%servers)) {
                   5892: 	%{$personnel{$tryserver}}=();
                   5893: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5894: 					    &escape($startdate).':'.
                   5895: 					    &escape($enddate).':'.
                   5896: 					    &escape($rolelist), $tryserver))) {
                   5897: 	    my ($key,$value) = split(/\=/,$line,2);
                   5898: 	    if (($key) && ($value)) {
                   5899: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5900: 	    }
                   5901: 	}
1.662     raeburn  5902:     }
                   5903:     return %personnel;
                   5904: }
1.658     raeburn  5905: 
1.1332    raeburn  5906: sub get_active_domroles {
                   5907:     my ($dom,$roles) = @_;
                   5908:     return () unless (ref($roles) eq 'ARRAY');
                   5909:     my $now = time;
                   5910:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5911:     my %domroles;
                   5912:     foreach my $server (keys(%dompersonnel)) {
                   5913:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5914:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5915:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5916:         }
                   5917:     }
                   5918:     return %domroles;
                   5919: }
                   5920: 
1.1057    www      5921: # ----------------------------------------------------------- Interval timing 
1.149     www      5922: 
1.1153    www      5923: {
                   5924: # Caches needed for speedup of navmaps
                   5925: # We don't want to cache this for very long at all (5 seconds at most)
                   5926: # 
                   5927: # The user for whom we cache
                   5928: my $cachedkey='';
                   5929: # The cached times for this user
                   5930: my %cachedtimes=();
                   5931: # When this was last done
1.1282    raeburn  5932: my $cachedtime='';
1.1153    www      5933: 
                   5934: sub load_all_first_access {
1.1308    raeburn  5935:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5936:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5937:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5938:         (!$ignorecache)) {
1.1154    raeburn  5939:         return;
                   5940:     }
                   5941:     $cachedtime=time;
                   5942:     $cachedkey=$uname.':'.$udom;
                   5943:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5944: }
                   5945: 
1.504     albertel 5946: sub get_first_access {
1.1308    raeburn  5947:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5948:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5949:     if ($argsymb) { $symb=$argsymb; }
                   5950:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5951:     if ($argmap) { $map = $argmap; }
1.926     albertel 5952:     if ($type eq 'course') {
                   5953: 	$res='course';
                   5954:     } elsif ($type eq 'map') {
1.588     albertel 5955: 	$res=&symbread($map);
                   5956:     } else {
                   5957: 	$res=$symb;
                   5958:     }
1.1308    raeburn  5959:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5960:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5961: }
                   5962: 
                   5963: sub set_first_access {
1.1162    raeburn  5964:     my ($type,$interval)=@_;
1.790     albertel 5965:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5966:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5967:     if ($type eq 'course') {
                   5968: 	$res='course';
                   5969:     } elsif ($type eq 'map') {
1.588     albertel 5970: 	$res=&symbread($map);
                   5971:     } else {
                   5972: 	$res=$symb;
                   5973:     }
1.1153    www      5974:     $cachedkey='';
1.1162    raeburn  5975:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  5976:     if ($firstaccess) {
                   5977:         &logthis("First access time already set ($firstaccess) when attempting ".
1.1393    raeburn  5978:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5979:                  "in $courseid");
1.1386    raeburn  5980:         return 'already_set';
                   5981:     } else {
1.1162    raeburn  5982:         my $start = time;
                   5983: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5984:                           $udom,$uname);
                   5985:         if ($putres eq 'ok') {
                   5986:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5987:                  $udom,$uname); 
                   5988:             &appenv(
                   5989:                      {
                   5990:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5991:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5992:                      }
                   5993:                   );
1.1365    raeburn  5994:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5995:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5996:             }
1.1386    raeburn  5997:         } elsif ($putres ne 'refused') {
                   5998:             &logthis("Result: $putres when attempting to set first access time ".
                   5999:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  6000:         }
                   6001:         return $putres;
1.505     albertel 6002:     }
                   6003:     return 'already_set';
1.504     albertel 6004: }
1.1153    www      6005: }
1.1282    raeburn  6006: 
1.110     www      6007: # --------------------------------------------- Set Expire Date for Spreadsheet
                   6008: 
                   6009: sub expirespread {
                   6010:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 6011:     my $cid=$env{'request.course.id'}; 
1.110     www      6012:     if ($cid) {
                   6013:        my $now=time;
                   6014:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 6015:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   6016:                             $env{'course.'.$cid.'.num'}.
1.110     www      6017: 	        	    ':nohist_expirationdates:'.
                   6018:                             &escape($key).'='.$now,
1.620     albertel 6019:                             $env{'course.'.$cid.'.home'})
1.110     www      6020:     }
                   6021:     return 'ok';
1.14      www      6022: }
                   6023: 
1.109     www      6024: # ----------------------------------------------------- Devalidate Spreadsheets
                   6025: 
                   6026: sub devalidate {
1.325     www      6027:     my ($symb,$uname,$udom)=@_;
1.620     albertel 6028:     my $cid=$env{'request.course.id'}; 
1.109     www      6029:     if ($cid) {
1.391     matthew  6030:         # delete the stored spreadsheets for
                   6031:         # - the student level sheet of this user in course's homespace
                   6032:         # - the assessment level sheet for this resource 
                   6033:         #   for this user in user's homespace
1.553     albertel 6034: 	# - current conditional state info
1.325     www      6035: 	my $key=$uname.':'.$udom.':';
1.109     www      6036:         my $status=
1.299     matthew  6037: 	    &del('nohist_calculatedsheets',
1.391     matthew  6038: 		 [$key.'studentcalc:'],
1.620     albertel 6039: 		 $env{'course.'.$cid.'.domain'},
                   6040: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 6041: 		.' '.
                   6042: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  6043: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      6044:         unless ($status eq 'ok ok') {
                   6045:            &logthis('Could not devalidate spreadsheet '.
1.325     www      6046:                     $uname.' at '.$udom.' for '.
1.109     www      6047: 		    $symb.': '.$status);
1.133     albertel 6048:         }
1.553     albertel 6049: 	&delenv('user.state.'.$cid);
1.109     www      6050:     }
                   6051: }
                   6052: 
1.265     albertel 6053: sub get_scalar {
                   6054:     my ($string,$end) = @_;
                   6055:     my $value;
                   6056:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   6057: 	$value = $1;
                   6058:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   6059: 	$value = $1;
                   6060:     }
                   6061:     return &unescape($value);
                   6062: }
                   6063: 
                   6064: sub array2str {
                   6065:   my (@array) = @_;
                   6066:   my $result=&arrayref2str(\@array);
                   6067:   $result=~s/^__ARRAY_REF__//;
                   6068:   $result=~s/__END_ARRAY_REF__$//;
                   6069:   return $result;
                   6070: }
                   6071: 
1.204     albertel 6072: sub arrayref2str {
                   6073:   my ($arrayref) = @_;
1.265     albertel 6074:   my $result='__ARRAY_REF__';
1.204     albertel 6075:   foreach my $elem (@$arrayref) {
1.265     albertel 6076:     if(ref($elem) eq 'ARRAY') {
                   6077:       $result.=&arrayref2str($elem).'&';
                   6078:     } elsif(ref($elem) eq 'HASH') {
                   6079:       $result.=&hashref2str($elem).'&';
                   6080:     } elsif(ref($elem)) {
                   6081:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 6082:     } else {
                   6083:       $result.=&escape($elem).'&';
                   6084:     }
                   6085:   }
                   6086:   $result=~s/\&$//;
1.265     albertel 6087:   $result .= '__END_ARRAY_REF__';
1.204     albertel 6088:   return $result;
                   6089: }
                   6090: 
1.168     albertel 6091: sub hash2str {
1.204     albertel 6092:   my (%hash) = @_;
                   6093:   my $result=&hashref2str(\%hash);
1.265     albertel 6094:   $result=~s/^__HASH_REF__//;
                   6095:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 6096:   return $result;
                   6097: }
                   6098: 
                   6099: sub hashref2str {
                   6100:   my ($hashref)=@_;
1.265     albertel 6101:   my $result='__HASH_REF__';
1.800     albertel 6102:   foreach my $key (sort(keys(%$hashref))) {
                   6103:     if (ref($key) eq 'ARRAY') {
                   6104:       $result.=&arrayref2str($key).'=';
                   6105:     } elsif (ref($key) eq 'HASH') {
                   6106:       $result.=&hashref2str($key).'=';
                   6107:     } elsif (ref($key)) {
1.265     albertel 6108:       $result.='=';
1.800     albertel 6109:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 6110:     } else {
1.1132    raeburn  6111: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 6112:     }
                   6113: 
1.800     albertel 6114:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   6115:       $result.=&arrayref2str($hashref->{$key}).'&';
                   6116:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   6117:       $result.=&hashref2str($hashref->{$key}).'&';
                   6118:     } elsif(ref($hashref->{$key})) {
1.265     albertel 6119:        $result.='&';
1.800     albertel 6120:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 6121:     } else {
1.800     albertel 6122:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 6123:     }
                   6124:   }
1.168     albertel 6125:   $result=~s/\&$//;
1.265     albertel 6126:   $result .= '__END_HASH_REF__';
1.168     albertel 6127:   return $result;
                   6128: }
                   6129: 
                   6130: sub str2hash {
1.265     albertel 6131:     my ($string)=@_;
                   6132:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   6133:     return %$hash;
                   6134: }
                   6135: 
                   6136: sub str2hashref {
1.168     albertel 6137:   my ($string) = @_;
1.265     albertel 6138: 
                   6139:   my %hash;
                   6140: 
                   6141:   if($string !~ /^__HASH_REF__/) {
                   6142:       if (! ($string eq '' || !defined($string))) {
                   6143: 	  $hash{'error'}='Not hash reference';
                   6144:       }
                   6145:       return (\%hash, $string);
                   6146:   }
                   6147: 
                   6148:   $string =~ s/^__HASH_REF__//;
                   6149: 
                   6150:   while($string !~ /^__END_HASH_REF__/) {
                   6151:       #key
                   6152:       my $key='';
                   6153:       if($string =~ /^__HASH_REF__/) {
                   6154:           ($key, $string)=&str2hashref($string);
                   6155:           if(defined($key->{'error'})) {
                   6156:               $hash{'error'}='Bad data';
                   6157:               return (\%hash, $string);
                   6158:           }
                   6159:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6160:           ($key, $string)=&str2arrayref($string);
                   6161:           if($key->[0] eq 'Array reference error') {
                   6162:               $hash{'error'}='Bad data';
                   6163:               return (\%hash, $string);
                   6164:           }
                   6165:       } else {
                   6166:           $string =~ s/^(.*?)=//;
1.267     albertel 6167: 	  $key=&unescape($1);
1.265     albertel 6168:       }
                   6169:       $string =~ s/^=//;
                   6170: 
                   6171:       #value
                   6172:       my $value='';
                   6173:       if($string =~ /^__HASH_REF__/) {
                   6174:           ($value, $string)=&str2hashref($string);
                   6175:           if(defined($value->{'error'})) {
                   6176:               $hash{'error'}='Bad data';
                   6177:               return (\%hash, $string);
                   6178:           }
                   6179:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6180:           ($value, $string)=&str2arrayref($string);
                   6181:           if($value->[0] eq 'Array reference error') {
                   6182:               $hash{'error'}='Bad data';
                   6183:               return (\%hash, $string);
                   6184:           }
                   6185:       } else {
                   6186: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   6187:       }
                   6188:       $string =~ s/^&//;
                   6189: 
                   6190:       $hash{$key}=$value;
1.204     albertel 6191:   }
1.265     albertel 6192: 
                   6193:   $string =~ s/^__END_HASH_REF__//;
                   6194: 
                   6195:   return (\%hash, $string);
1.204     albertel 6196: }
                   6197: 
                   6198: sub str2array {
1.265     albertel 6199:     my ($string)=@_;
                   6200:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   6201:     return @$array;
                   6202: }
                   6203: 
                   6204: sub str2arrayref {
1.204     albertel 6205:   my ($string) = @_;
1.265     albertel 6206:   my @array;
                   6207: 
                   6208:   if($string !~ /^__ARRAY_REF__/) {
                   6209:       if (! ($string eq '' || !defined($string))) {
                   6210: 	  $array[0]='Array reference error';
                   6211:       }
                   6212:       return (\@array, $string);
                   6213:   }
                   6214: 
                   6215:   $string =~ s/^__ARRAY_REF__//;
                   6216: 
                   6217:   while($string !~ /^__END_ARRAY_REF__/) {
                   6218:       my $value='';
                   6219:       if($string =~ /^__HASH_REF__/) {
                   6220:           ($value, $string)=&str2hashref($string);
                   6221:           if(defined($value->{'error'})) {
                   6222:               $array[0] ='Array reference error';
                   6223:               return (\@array, $string);
                   6224:           }
                   6225:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6226:           ($value, $string)=&str2arrayref($string);
                   6227:           if($value->[0] eq 'Array reference error') {
                   6228:               $array[0] ='Array reference error';
                   6229:               return (\@array, $string);
                   6230:           }
                   6231:       } else {
                   6232: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   6233:       }
                   6234:       $string =~ s/^&//;
                   6235: 
                   6236:       push(@array, $value);
1.191     harris41 6237:   }
1.265     albertel 6238: 
                   6239:   $string =~ s/^__END_ARRAY_REF__//;
                   6240: 
                   6241:   return (\@array, $string);
1.168     albertel 6242: }
                   6243: 
1.167     albertel 6244: # -------------------------------------------------------------------Temp Store
                   6245: 
1.168     albertel 6246: sub tmpreset {
                   6247:   my ($symb,$namespace,$domain,$stuname) = @_;
                   6248:   if (!$symb) {
                   6249:     $symb=&symbread();
1.620     albertel 6250:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6251:   }
                   6252:   $symb=escape($symb);
                   6253: 
1.620     albertel 6254:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 6255:   $namespace=~s/\//\_/g;
                   6256:   $namespace=~s/\W//g;
                   6257: 
1.620     albertel 6258:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6259:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6260:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6261:       $stuname=&get_requestor_ip();
1.591     albertel 6262:   }
1.1117    foxr     6263:   my $path=LONCAPA::tempdir();
1.168     albertel 6264:   my %hash;
                   6265:   if (tie(%hash,'GDBM_File',
                   6266: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6267: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6268:     foreach my $key (keys(%hash)) {
1.180     albertel 6269:       if ($key=~ /:$symb/) {
1.168     albertel 6270: 	delete($hash{$key});
                   6271:       }
                   6272:     }
                   6273:   }
                   6274: }
                   6275: 
1.167     albertel 6276: sub tmpstore {
1.168     albertel 6277:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6278: 
                   6279:   if (!$symb) {
                   6280:     $symb=&symbread();
1.620     albertel 6281:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6282:   }
                   6283:   $symb=escape($symb);
                   6284: 
                   6285:   if (!$namespace) {
                   6286:     # I don't think we would ever want to store this for a course.
                   6287:     # it seems this will only be used if we don't have a course.
1.620     albertel 6288:     #$namespace=$env{'request.course.id'};
1.168     albertel 6289:     #if (!$namespace) {
1.620     albertel 6290:       $namespace=$env{'request.state'};
1.168     albertel 6291:     #}
                   6292:   }
                   6293:   $namespace=~s/\//\_/g;
                   6294:   $namespace=~s/\W//g;
1.620     albertel 6295:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6296:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6297:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6298:       $stuname=&get_requestor_ip();
1.591     albertel 6299:   }
1.168     albertel 6300:   my $now=time;
                   6301:   my %hash;
1.1117    foxr     6302:   my $path=LONCAPA::tempdir();
1.168     albertel 6303:   if (tie(%hash,'GDBM_File',
                   6304: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6305: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6306:     $hash{"version:$symb"}++;
                   6307:     my $version=$hash{"version:$symb"};
                   6308:     my $allkeys=''; 
                   6309:     foreach my $key (keys(%$storehash)) {
                   6310:       $allkeys.=$key.':';
1.591     albertel 6311:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6312:     }
                   6313:     $hash{"$version:$symb:timestamp"}=$now;
                   6314:     $allkeys.='timestamp';
                   6315:     $hash{"$version:keys:$symb"}=$allkeys;
                   6316:     if (untie(%hash)) {
                   6317:       return 'ok';
                   6318:     } else {
                   6319:       return "error:$!";
                   6320:     }
                   6321:   } else {
                   6322:     return "error:$!";
                   6323:   }
                   6324: }
1.167     albertel 6325: 
1.168     albertel 6326: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6327: 
1.168     albertel 6328: sub tmprestore {
                   6329:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6330: 
1.168     albertel 6331:   if (!$symb) {
                   6332:     $symb=&symbread();
1.620     albertel 6333:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6334:   }
                   6335:   $symb=escape($symb);
                   6336: 
1.620     albertel 6337:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6338: 
1.620     albertel 6339:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6340:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6341:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6342:       $stuname=&get_requestor_ip();
1.591     albertel 6343:   }
1.168     albertel 6344:   my %returnhash;
                   6345:   $namespace=~s/\//\_/g;
                   6346:   $namespace=~s/\W//g;
                   6347:   my %hash;
1.1117    foxr     6348:   my $path=LONCAPA::tempdir();
1.168     albertel 6349:   if (tie(%hash,'GDBM_File',
                   6350: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6351: 	  &GDBM_READER(),0640)) {
1.168     albertel 6352:     my $version=$hash{"version:$symb"};
                   6353:     $returnhash{'version'}=$version;
                   6354:     my $scope;
                   6355:     for ($scope=1;$scope<=$version;$scope++) {
                   6356:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6357:       my @keys=split(/:/,$vkeys);
                   6358:       my $key;
                   6359:       $returnhash{"$scope:keys"}=$vkeys;
                   6360:       foreach $key (@keys) {
1.591     albertel 6361: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6362: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6363:       }
                   6364:     }
1.168     albertel 6365:     if (!(untie(%hash))) {
                   6366:       return "error:$!";
                   6367:     }
                   6368:   } else {
                   6369:     return "error:$!";
                   6370:   }
                   6371:   return %returnhash;
1.167     albertel 6372: }
                   6373: 
1.9       www      6374: # ----------------------------------------------------------------------- Store
                   6375: 
                   6376: sub store {
1.1269    raeburn  6377:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6378:     my $home='';
                   6379: 
1.168     albertel 6380:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6381: 
1.213     www      6382:     $symb=&symbclean($symb);
1.122     albertel 6383:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6384: 
1.620     albertel 6385:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6386:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6387: 
                   6388:     &devalidate($symb,$stuname,$domain);
1.109     www      6389: 
                   6390:     $symb=escape($symb);
1.187     www      6391:     if (!$namespace) { 
1.620     albertel 6392:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6393:           return ''; 
                   6394:        } 
                   6395:     }
1.620     albertel 6396:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6397: 
1.1434    raeburn  6398:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6399:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6400: 
1.12      www      6401:     my $namevalue='';
1.800     albertel 6402:     foreach my $key (keys(%$storehash)) {
                   6403:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6404:     }
1.12      www      6405:     $namevalue=~s/\&$//;
1.187     www      6406:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  6407:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6408: }
                   6409: 
1.47      www      6410: # -------------------------------------------------------------- Critical Store
                   6411: 
                   6412: sub cstore {
1.1269    raeburn  6413:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6414:     my $home='';
                   6415: 
1.168     albertel 6416:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6417: 
1.213     www      6418:     $symb=&symbclean($symb);
1.122     albertel 6419:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6420: 
1.620     albertel 6421:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6422:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6423: 
                   6424:     &devalidate($symb,$stuname,$domain);
1.109     www      6425: 
                   6426:     $symb=escape($symb);
1.187     www      6427:     if (!$namespace) { 
1.620     albertel 6428:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6429:           return ''; 
                   6430:        } 
                   6431:     }
1.620     albertel 6432:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6433: 
1.1434    raeburn  6434:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6435:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6436: 
1.47      www      6437:     my $namevalue='';
1.800     albertel 6438:     foreach my $key (keys(%$storehash)) {
                   6439:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6440:     }
1.47      www      6441:     $namevalue=~s/\&$//;
1.187     www      6442:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6443:     return critical
1.1269    raeburn  6444:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6445: }
                   6446: 
1.9       www      6447: # --------------------------------------------------------------------- Restore
                   6448: 
                   6449: sub restore {
1.124     www      6450:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6451:     my $home='';
                   6452: 
1.168     albertel 6453:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6454: 
1.122     albertel 6455:     if (!$symb) {
1.1224    raeburn  6456:         return if ($namespace eq 'courserequests');
                   6457:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6458:     } else {
1.1224    raeburn  6459:         unless ($namespace eq 'courserequests') {
                   6460:             $symb=&escape(&symbclean($symb));
                   6461:         }
1.122     albertel 6462:     }
1.188     www      6463:     if (!$namespace) { 
1.620     albertel 6464:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6465:           return ''; 
                   6466:        } 
                   6467:     }
1.620     albertel 6468:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6469:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6470:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6471:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6472: 
1.12      www      6473:     my %returnhash=();
1.800     albertel 6474:     foreach my $line (split(/\&/,$answer)) {
                   6475: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6476:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6477:     }
1.75      www      6478:     my $version;
                   6479:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6480:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6481:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6482:        }
1.75      www      6483:     }
1.13      www      6484:     return %returnhash;
1.34      www      6485: }
                   6486: 
                   6487: # ---------------------------------------------------------- Course Description
1.1118    foxr     6488: #
                   6489: #  
1.34      www      6490: 
                   6491: sub coursedescription {
1.731     albertel 6492:     my ($courseid,$args)=@_;
1.34      www      6493:     $courseid=~s/^\///;
1.49      www      6494:     $courseid=~s/\_/\//g;
1.34      www      6495:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6496:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6497:     my $normalid=$cdomain.'_'.$cnum;
                   6498:     # need to always cache even if we get errors otherwise we keep 
                   6499:     # trying and trying and trying to get the course description.
                   6500:     my %envhash=();
                   6501:     my %returnhash=();
1.731     albertel 6502:     
                   6503:     my $expiretime=600;
                   6504:     if ($env{'request.course.id'} eq $normalid) {
                   6505: 	$expiretime=120;
                   6506:     }
                   6507: 
                   6508:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6509:     if (!$args->{'freshen_cache'}
                   6510: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6511: 	foreach my $key (keys(%env)) {
                   6512: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6513: 	    my ($setting) = $1;
                   6514: 	    $returnhash{$setting} = $env{$key};
                   6515: 	}
                   6516: 	return %returnhash;
                   6517:     }
                   6518: 
1.1118    foxr     6519:     # get the data again
                   6520: 
1.731     albertel 6521:     if (!$args->{'one_time'}) {
                   6522: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6523:     }
1.811     albertel 6524: 
1.34      www      6525:     if ($chome ne 'no_host') {
1.302     albertel 6526:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6527:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6528: 	   my $username = $env{'user.name'}; # Defult username
                   6529: 	   if(defined $args->{'user'}) {
                   6530: 	       $username = $args->{'user'};
                   6531: 	   }
1.129     albertel 6532:            $returnhash{'home'}= $chome;
                   6533: 	   $returnhash{'domain'} = $cdomain;
                   6534: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6535:            if (!defined($returnhash{'type'})) {
                   6536:                $returnhash{'type'} = 'Course';
                   6537:            }
1.130     albertel 6538:            while (my ($name,$value) = each %returnhash) {
1.53      www      6539:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6540:            }
1.270     www      6541:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6542:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6543: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6544:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6545:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6546:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6547:        }
                   6548:     }
1.731     albertel 6549:     if (!$args->{'one_time'}) {
1.949     raeburn  6550: 	&appenv(\%envhash);
1.731     albertel 6551:     }
1.302     albertel 6552:     return %returnhash;
1.461     www      6553: }
                   6554: 
1.1080    raeburn  6555: sub update_released_required {
                   6556:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6557:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6558:         $cid = $env{'request.course.id'};
                   6559:         $cdom = $env{'course.'.$cid.'.domain'};
                   6560:         $cnum = $env{'course.'.$cid.'.num'};
                   6561:         $chome = $env{'course.'.$cid.'.home'};
                   6562:     }
                   6563:     if ($needsrelease) {
                   6564:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6565:         my $needsupdate;
                   6566:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6567:             $needsupdate = 1;
                   6568:         } else {
                   6569:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6570:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6571:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6572:                 $needsupdate = 1;
                   6573:             }
                   6574:         }
                   6575:         if ($needsupdate) {
                   6576:             my %needshash = (
                   6577:                              'internal.releaserequired' => $needsrelease,
                   6578:                             );
                   6579:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6580:             if ($putresult eq 'ok') {
                   6581:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6582:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6583:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6584:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6585:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6586:                 }
                   6587:             }
                   6588:         }
                   6589:     }
                   6590:     return;
                   6591: }
                   6592: 
1.461     www      6593: # -------------------------------------------------See if a user is privileged
                   6594: 
                   6595: sub privileged {
1.1219    raeburn  6596:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6597:     my $now = time;
1.1219    raeburn  6598:     my $roles;
                   6599:     if (ref($possroles) eq 'ARRAY') {
                   6600:         $roles = $possroles; 
                   6601:     } else {
                   6602:         $roles = ['dc','su'];
                   6603:     }
                   6604:     if (ref($possdomains) eq 'ARRAY') {
                   6605:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6606:         foreach my $dom (@{$possdomains}) {
                   6607:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6608:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6609:                 foreach my $role (@{$roles}) {
                   6610:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6611:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6612:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6613:                             return 1 unless (($end && $end < $now) ||
                   6614:                                              ($start && $start > $now));
                   6615:                         }
                   6616:                     }
                   6617:                 }
                   6618:             }
                   6619:         }
                   6620:     } else {
                   6621:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6622:         my $now = time;
1.1170    droeschl 6623: 
1.1275    musolffc 6624:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6625:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  6626:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 6627:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  6628:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6629:             }
1.1219    raeburn  6630:         }
                   6631:     }
                   6632:     return 0;
                   6633: }
1.1170    droeschl 6634: 
1.1219    raeburn  6635: sub privileged_by_domain {
                   6636:     my ($domains,$roles) = @_;
                   6637:     my %privileged = ();
                   6638:     my $cachetime = 60*60*24;
                   6639:     my $now = time;
                   6640:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6641:         return %privileged;
                   6642:     }
                   6643:     foreach my $dom (@{$domains}) {
                   6644:         next if (ref($privileged{$dom}) eq 'HASH');
                   6645:         my $needroles;
                   6646:         foreach my $role (@{$roles}) {
                   6647:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6648:             if (defined($cached)) {
                   6649:                 if (ref($result) eq 'HASH') {
                   6650:                     $privileged{$dom}{$role} = $result;
                   6651:                 }
                   6652:             } else {
                   6653:                 $needroles = 1;
                   6654:             }
                   6655:         }
                   6656:         if ($needroles) {
                   6657:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6658:             $privileged{$dom} = {};
                   6659:             foreach my $server (keys(%dompersonnel)) {
                   6660:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6661:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6662:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6663:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6664:                         next if ($end && $end < $now);
                   6665:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   6666:                             $dompersonnel{$server}{$item};
                   6667:                     }
                   6668:                 }
                   6669:             }
                   6670:             if (ref($privileged{$dom}) eq 'HASH') {
                   6671:                 foreach my $role (@{$roles}) {
                   6672:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6673:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6674:                     } else {
                   6675:                         my %hash = ();
                   6676:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6677:                     }
                   6678:                 }
                   6679:             }
                   6680:         }
                   6681:     }
                   6682:     return %privileged;
1.9       www      6683: }
1.1       albertel 6684: 
1.103     harris41 6685: # -------------------------------------------------------- Get user privileges
1.11      www      6686: 
                   6687: sub rolesinit {
1.1169    droeschl 6688:     my ($domain, $username) = @_;
                   6689:     my %userroles = ('user.login.time' => time);
                   6690:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6691: 
                   6692:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6693:     # also, blocking can be triggered by an activating timer
                   6694:     # it's saved in the user's %env.
                   6695:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6696:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6697:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6698:         %timerintchk, %timerintenv);
                   6699: 
1.1162    raeburn  6700:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6701:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6702:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6703:     }
1.1169    droeschl 6704: 
1.1162    raeburn  6705:     foreach my $key (keys(%timerinterval)) {
                   6706:         my ($cid,$rest) = split(/\0/,$key);
                   6707:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6708:     }
1.1169    droeschl 6709: 
1.11      www      6710:     my %allroles=();
1.1162    raeburn  6711:     my %allgroups=();
1.11      www      6712: 
1.1274    raeburn  6713:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6714:         my $role = $rolesdump{$area};
                   6715:         $area =~ s/\_\w\w$//;
                   6716: 
                   6717:         my ($trole, $tend, $tstart, $group_privs);
                   6718: 
                   6719:         if ($role =~ /^cr/) {
                   6720:         # Custom role, defined by a user 
                   6721:         # e.g., user.role.cr/msu/smith/mynewrole
                   6722:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6723:                 $trole = $1;
                   6724:                 ($tend, $tstart) = split('_', $2);
                   6725:             } else {
                   6726:                 $trole = $role;
                   6727:             }
                   6728:         } elsif ($role =~ m|^gr/|) {
                   6729:         # Role of member in a group, defined within a course/community
                   6730:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6731:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6732:             next if $tstart eq '-1';
                   6733:             ($trole, $group_privs) = split(/\//, $trole);
                   6734:             $group_privs = &unescape($group_privs);
                   6735:         } else {
                   6736:         # Just a normal role, defined in roles.tab
                   6737:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6738:         }
                   6739: 
                   6740:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6741:                  $username);
                   6742:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6743: 
                   6744:         # role expired or not available yet?
                   6745:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6746:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6747: 
                   6748:         next if $area eq '' or $trole eq '';
                   6749: 
                   6750:         my $spec = "$trole.$area";
                   6751:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6752: 
                   6753:         if ($trole =~ /^cr\//) {
                   6754:         # Custom role, defined by a user
                   6755:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6756:         } elsif ($trole eq 'gr') {
                   6757:         # Role of a member in a group, defined within a course/community
                   6758:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6759:             next;
                   6760:         } else {
                   6761:         # Normal role, defined in roles.tab
                   6762:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6763:         }
                   6764: 
                   6765:         my $cid = $tdomain.'_'.$trest;
                   6766:         unless ($firstaccchk{$cid}) {
                   6767:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6768:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6769:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6770:                         $coursetimerstarts{$cid}{$item}; 
                   6771:                 }
                   6772:             }
                   6773:             $firstaccchk{$cid} = 1;
                   6774:         }
                   6775:         unless ($timerintchk{$cid}) {
                   6776:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6777:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6778:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6779:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6780:                 }
1.12      www      6781:             }
1.1169    droeschl 6782:             $timerintchk{$cid} = 1;
1.191     harris41 6783:         }
1.11      www      6784:     }
1.1169    droeschl 6785: 
1.1341    raeburn  6786:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6787:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6788:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6789:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6790: 
1.1162    raeburn  6791:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6792: }
                   6793: 
1.567     raeburn  6794: sub set_arearole {
1.1215    raeburn  6795:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6796:     unless ($nolog) {
1.567     raeburn  6797: # log the associated role with the area
1.1215    raeburn  6798:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6799:     }
1.743     albertel 6800:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6801: }
                   6802: 
                   6803: sub custom_roleprivs {
                   6804:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6805:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6806:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6807:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6808:         my ($rdummy,$roledef)=
                   6809:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6810:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6811:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6812:             if (defined($syspriv)) {
1.1043    raeburn  6813:                 if ($trest =~ /^$match_community$/) {
                   6814:                     $syspriv =~ s/bre\&S//; 
                   6815:                 }
1.567     raeburn  6816:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6817:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6818:             }
                   6819:             if ($tdomain ne '') {
                   6820:                 if (defined($dompriv)) {
                   6821:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6822:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6823:                 }
                   6824:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6825:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6826:                         my $rolename = $1;
                   6827:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6828:                     }
1.567     raeburn  6829:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6830:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6831:                 }
                   6832:             }
                   6833:         }
                   6834:     }
                   6835: }
                   6836: 
1.1332    raeburn  6837: sub course_adhocrole_privs {
                   6838:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6839:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6840:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6841:         my (%currprivs,%storeprivs);
                   6842:         foreach my $item (split(/:/,$coursepriv)) {
                   6843:             my ($priv,$restrict) = split(/\&/,$item);
                   6844:             $currprivs{$priv} = $restrict;
                   6845:         }
                   6846:         my (%possadd,%possremove,%full);
                   6847:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6848:             my ($priv,$restrict)=split(/\&/,$item);
                   6849:             $full{$priv} = $restrict;
                   6850:         }
                   6851:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
1.1490  ! raeburn  6852:             next if ($item eq '');
        !          6853:             my ($rule,$rest) = split(/=/,$item);
        !          6854:             next unless (($rule eq 'off') || ($rule eq 'on'));
        !          6855:             foreach my $priv (split(/:/,$rest)) {
        !          6856:                 if ($priv ne '') {
        !          6857:                     if ($rule eq 'off') {
        !          6858:                         $possremove{$priv} = 1;
        !          6859:                     } else {
        !          6860:                         $possadd{$priv} = 1;
        !          6861:                     }
        !          6862:                 }
        !          6863:             }
        !          6864:         }
        !          6865:         foreach my $priv (sort(keys(%full))) {
        !          6866:             if (exists($currprivs{$priv})) {
        !          6867:                 unless (exists($possremove{$priv})) {
        !          6868:                     $storeprivs{$priv} = $currprivs{$priv};
        !          6869:                 }
        !          6870:             } elsif (exists($possadd{$priv})) {
        !          6871:                 $storeprivs{$priv} = $full{$priv};
        !          6872:             }
        !          6873:         }
        !          6874:         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
        !          6875:     }
        !          6876:     return $coursepriv;
1.1332    raeburn  6877: }
                   6878: 
1.678     raeburn  6879: sub group_roleprivs {
                   6880:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6881:     my $access = 1;
                   6882:     my $now = time;
                   6883:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6884:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6885:     if ($access) {
1.811     albertel 6886:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6887:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6888:     }
                   6889: }
1.567     raeburn  6890: 
                   6891: sub standard_roleprivs {
                   6892:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6893:     if (defined($pr{$trole.':s'})) {
                   6894:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6895:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6896:     }
                   6897:     if ($tdomain ne '') {
                   6898:         if (defined($pr{$trole.':d'})) {
                   6899:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6900:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6901:         }
                   6902:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6903:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6904:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6905:         }
                   6906:     }
                   6907: }
                   6908: 
                   6909: sub set_userprivs {
1.1064    raeburn  6910:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6911:     my $author=0;
                   6912:     my $adv=0;
1.1341    raeburn  6913:     my $rar=0;
1.678     raeburn  6914:     my %grouproles = ();
                   6915:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6916:         my @groupkeys; 
1.1000    raeburn  6917:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6918:             push(@groupkeys,$role);
                   6919:         }
                   6920:         if (ref($groups_roles) eq 'HASH') {
                   6921:             foreach my $key (keys(%{$groups_roles})) {
                   6922:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6923:                     push(@groupkeys,$key);
                   6924:                 }
                   6925:             }
                   6926:         }
                   6927:         if (@groupkeys > 0) {
                   6928:             foreach my $role (@groupkeys) {
                   6929:                 my ($trole,$area,$sec,$extendedarea);
                   6930:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6931:                     $trole = $1;
                   6932:                     $area = $2;
                   6933:                     $sec = $3;
                   6934:                     $extendedarea = $area.$sec;
                   6935:                     if (exists($$allgroups{$area})) {
                   6936:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6937:                             my $spec = $trole.'.'.$extendedarea;
                   6938:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6939:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6940:                         }
1.678     raeburn  6941:                     }
                   6942:                 }
                   6943:             }
                   6944:         }
                   6945:     }
1.800     albertel 6946:     foreach my $group (keys(%grouproles)) {
                   6947:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6948:     }
1.800     albertel 6949:     foreach my $role (keys(%{$allroles})) {
                   6950:         my %thesepriv;
1.941     raeburn  6951:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6952:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6953:             if ($item ne '') {
                   6954:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6955:                 if ($restrictions eq '') {
                   6956:                     $thesepriv{$privilege}='F';
                   6957:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6958:                     $thesepriv{$privilege}.=$restrictions;
                   6959:                 }
                   6960:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6961:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6962:             }
                   6963:         }
                   6964:         my $thesestr='';
1.1104    raeburn  6965:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6966: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6967: 	}
                   6968:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6969:     }
1.1341    raeburn  6970:     return ($author,$adv,$rar);
1.567     raeburn  6971: }
                   6972: 
1.994     raeburn  6973: sub role_status {
1.1104    raeburn  6974:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6975:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6976:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6977:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6978:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6979:             $$where = '/'.$two;
1.994     raeburn  6980:             $$trolecode=$$role.'.'.$$where;
                   6981:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6982:             $$tstatus='is';
1.1104    raeburn  6983:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6984:                 $$tstatus='future';
1.1034    raeburn  6985:                 if ($$tstart<$now) {
                   6986:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6987:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6988:                             my (%allroles,%allgroups,$group_privs,
                   6989:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6990:                             my %userroles = (
                   6991:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6992:                             );
1.1064    raeburn  6993:                             @rolecodes = ('cm'); 
1.1002    raeburn  6994:                             my $spec=$$role.'.'.$$where;
                   6995:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6996:                             if ($$role =~ /^cr\//) {
                   6997:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6998:                                 push(@rolecodes,'cr');
1.1002    raeburn  6999:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  7000:                                 push(@rolecodes,$$role);
1.1002    raeburn  7001:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   7002:                                                     $env{'user.name'});
1.1064    raeburn  7003:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  7004:                                 (undef,my $group_privs) = split(/\//,$trole);
                   7005:                                 $group_privs = &unescape($group_privs);
                   7006:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  7007:                                 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  7008:                                 &get_groups_roles($tdomain,$trest,
                   7009:                                                   \%course_roles,\@rolecodes,
                   7010:                                                   \%groups_roles);
1.1002    raeburn  7011:                             } else {
1.1064    raeburn  7012:                                 push(@rolecodes,$$role);
1.1002    raeburn  7013:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   7014:                             }
1.1341    raeburn  7015:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   7016:                                                                    \%groups_roles);
1.1064    raeburn  7017:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  7018:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  7019:                         }
                   7020:                     }
1.1034    raeburn  7021:                     $$tstatus = 'is';
1.1002    raeburn  7022:                 }
1.994     raeburn  7023:             }
                   7024:             if ($$tend) {
1.1104    raeburn  7025:                 if ($$tend<$update) {
1.994     raeburn  7026:                     $$tstatus='expired';
                   7027:                 } elsif ($$tend<$now) {
                   7028:                     $$tstatus='will_not';
                   7029:                 }
                   7030:             }
                   7031:         }
                   7032:     }
                   7033: }
                   7034: 
1.1104    raeburn  7035: sub get_groups_roles {
                   7036:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   7037:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   7038:                   (ref($rolecodes) eq 'ARRAY') && 
                   7039:                   (ref($groups_roles) eq 'HASH')); 
                   7040:     if (keys(%{$cdom_courseroles}) > 0) {
                   7041:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   7042:         if ($cdom ne '' && $cnum ne '') {
                   7043:             foreach my $key (keys(%{$cdom_courseroles})) {
                   7044:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   7045:                     my $crsrole = $1;
                   7046:                     my $crssec = $2;
                   7047:                     if ($crsrole =~ /^cr/) {
                   7048:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   7049:                             push(@{$rolecodes},'cr');
                   7050:                         }
                   7051:                     } else {
                   7052:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   7053:                             push(@{$rolecodes},$crsrole);
                   7054:                         }
                   7055:                     }
                   7056:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   7057:                     if ($crssec ne '') {
                   7058:                         $rolekey .= "/$crssec";
                   7059:                     }
                   7060:                     $rolekey .= './';
                   7061:                     $groups_roles->{$rolekey} = $rolecodes;
                   7062:                 }
                   7063:             }
                   7064:         }
                   7065:     }
                   7066:     return;
                   7067: }
                   7068: 
                   7069: sub delete_env_groupprivs {
                   7070:     my ($where,$courseroles,$possroles) = @_;
                   7071:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   7072:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   7073:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   7074:         %{$courseroles->{$udom}} =
                   7075:             &get_my_roles('','','userroles',['active'],
                   7076:                           $possroles,[$udom],1);
                   7077:     }
                   7078:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   7079:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   7080:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   7081:             my $area = '/'.$cdom.'/'.$cnum;
                   7082:             my $privkey = "user.priv.$crsrole.$area";
                   7083:             if ($crssec ne '') {
                   7084:                 $privkey .= '/'.$crssec;
                   7085:             }
                   7086:             $privkey .= ".$area/$group";
                   7087:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   7088:         }
                   7089:     }
                   7090:     return;
                   7091: }
                   7092: 
1.994     raeburn  7093: sub check_adhoc_privs {
1.1329    raeburn  7094:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  7095:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  7096:     if ($sec) {
                   7097:         $cckey .= '/'.$sec;
                   7098:     } 
1.1185    raeburn  7099:     my $setprivs;
1.994     raeburn  7100:     if ($env{$cckey}) {
                   7101:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  7102:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  7103:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  7104:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  7105:             $setprivs = 1;
1.994     raeburn  7106:         }
                   7107:     } else {
1.1330    raeburn  7108:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  7109:         $setprivs = 1;
1.994     raeburn  7110:     }
1.1185    raeburn  7111:     return $setprivs;
1.994     raeburn  7112: }
                   7113: 
                   7114: sub set_adhoc_privileges {
1.1326    raeburn  7115: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  7116:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  7117:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  7118:     if ($sec ne '') {
                   7119:         $area .= '/'.$sec;
                   7120:     }
1.994     raeburn  7121:     my $spec = $role.'.'.$area;
                   7122:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  7123:                                   $env{'user.name'},1);
1.1326    raeburn  7124:     my %rolehash = ();
1.1332    raeburn  7125:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   7126:         my $rolename = $1;
1.1326    raeburn  7127:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  7128:         my %domdef = &get_domain_defaults($dcdom);
                   7129:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   7130:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   7131:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   7132:             }
                   7133:         }
1.1326    raeburn  7134:     } else {
                   7135:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   7136:     }
1.1341    raeburn  7137:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  7138:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  7139:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402    raeburn  7140:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   7141:             ($caller eq 'tiny')) {
1.1088    raeburn  7142:         &appenv( {'request.role'        => $spec,
                   7143:                   'request.role.domain' => $dcdom,
1.1332    raeburn  7144:                   'request.course.sec'  => $sec,
1.1088    raeburn  7145:                  }
                   7146:                );
                   7147:         my $tadv=0;
                   7148:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   7149:         &appenv({'request.role.adv'    => $tadv});
                   7150:     }
1.994     raeburn  7151: }
                   7152: 
1.12      www      7153: # --------------------------------------------------------------- get interface
                   7154: 
                   7155: sub get {
1.131     albertel 7156:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7157:    my $items='';
1.800     albertel 7158:    foreach my $item (@$storearr) {
                   7159:        $items.=&escape($item).'&';
1.191     harris41 7160:    }
1.12      www      7161:    $items=~s/\&$//;
1.620     albertel 7162:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7163:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 7164:    my $uhome=&homeserver($uname,$udomain);
                   7165: 
1.133     albertel 7166:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7167:    my @pairs=split(/\&/,$rep);
1.273     albertel 7168:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   7169:      return @pairs;
                   7170:    }
1.15      www      7171:    my %returnhash=();
1.42      www      7172:    my $i=0;
1.800     albertel 7173:    foreach my $item (@$storearr) {
                   7174:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7175:       $i++;
1.191     harris41 7176:    }
1.15      www      7177:    return %returnhash;
1.27      www      7178: }
                   7179: 
                   7180: # --------------------------------------------------------------- del interface
                   7181: 
                   7182: sub del {
1.133     albertel 7183:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      7184:    my $items='';
1.800     albertel 7185:    foreach my $item (@$storearr) {
                   7186:        $items.=&escape($item).'&';
1.191     harris41 7187:    }
1.984     neumanie 7188: 
1.27      www      7189:    $items=~s/\&$//;
1.620     albertel 7190:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7191:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7192:    my $uhome=&homeserver($uname,$udomain);
                   7193:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7194: }
                   7195: 
                   7196: # -------------------------------------------------------------- dump interface
                   7197: 
1.1180    droeschl 7198: sub unserialize {
                   7199:     my ($rep, $escapedkeys) = @_;
                   7200: 
                   7201:     return {} if $rep =~ /^error/;
                   7202: 
                   7203:     my %returnhash=();
1.1252    raeburn  7204: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 7205: 	    my ($key, $value) = split(/=/, $item, 2);
                   7206: 	    $key = unescape($key) unless $escapedkeys;
                   7207: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  7208: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 7209: 	}
                   7210:     #return %returnhash;
                   7211:     return \%returnhash;
                   7212: }        
                   7213: 
                   7214: # see Lond::dump_with_regexp
                   7215: # if $escapedkeys hash keys won't get unescaped.
1.15      www      7216: sub dump {
1.1462    raeburn  7217:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755     albertel 7218:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7219:     if (!$uname) { $uname=$env{'user.name'}; }
                   7220:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 7221: 
1.1266    raeburn  7222:     if ($regexp) {
                   7223:         $regexp=&escape($regexp);
                   7224:     } else {
                   7225:         $regexp='.';
                   7226:     }
1.1180    droeschl 7227:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   7228:         # user is hosted on this machine
1.1266    raeburn  7229:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  7230:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 7231:         return %{unserialize($reply, $escapedkeys)};
                   7232:     }
1.1462    raeburn  7233:     my $rep;
                   7234:     if ($encrypt) {
                   7235:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.1463    raeburn  7236:     } else {
1.1462    raeburn  7237:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7238:     }
1.755     albertel 7239:     my @pairs=split(/\&/,$rep);
                   7240:     my %returnhash=();
1.1098    foxr     7241:     if (!($rep =~ /^error/ )) {
                   7242: 	foreach my $item (@pairs) {
                   7243: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 7244:         $key = unescape($key) unless $escapedkeys;
                   7245:         #$key = &unescape($key);
1.1098    foxr     7246: 	    next if ($key =~ /^error: 2 /);
                   7247: 	    $returnhash{$key}=&thaw_unescape($value);
                   7248: 	}
1.755     albertel 7249:     }
                   7250:     return %returnhash;
1.407     www      7251: }
                   7252: 
1.1098    foxr     7253: 
1.717     albertel 7254: # --------------------------------------------------------- dumpstore interface
                   7255: 
                   7256: sub dumpstore {
                   7257:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 7258:    # same as dump but keys must be escaped. They may contain colon separated
                   7259:    # lists of values that may themself contain colons (e.g. symbs).
                   7260:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7261: }
                   7262: 
1.407     www      7263: # -------------------------------------------------------------- keys interface
                   7264: 
                   7265: sub getkeys {
                   7266:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7267:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7268:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7269:    my $uhome=&homeserver($uname,$udomain);
                   7270:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7271:    my @keyarray=();
1.800     albertel 7272:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7273:       next if ($key =~ /^error: 2 /);
1.800     albertel 7274:       push(@keyarray,&unescape($key));
1.407     www      7275:    }
                   7276:    return @keyarray;
1.318     matthew  7277: }
                   7278: 
1.319     matthew  7279: # --------------------------------------------------------------- currentdump
                   7280: sub currentdump {
1.328     matthew  7281:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7282:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7283:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7284:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7285:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 7286:    my $rep;
                   7287: 
                   7288:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7289:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   7290:                    $courseid)));
                   7291:    } else {
                   7292:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7293:    }
                   7294: 
1.318     matthew  7295:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7296:    #
1.318     matthew  7297:    my %returnhash=();
1.319     matthew  7298:    #
1.1343    raeburn  7299:    if ($rep eq 'unknown_cmd') {
1.319     matthew  7300:        # an old lond will not know currentdump
                   7301:        # Do a dump and make it look like a currentdump
1.822     albertel 7302:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7303:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7304:        my %hash = @tmp;
                   7305:        @tmp=();
1.424     matthew  7306:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7307:    } else {
                   7308:        my @pairs=split(/\&/,$rep);
1.800     albertel 7309:        foreach my $pair (@pairs) {
                   7310:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7311:            my ($symb,$param) = split(/:/,$key);
                   7312:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7313:                                                         &thaw_unescape($value);
1.319     matthew  7314:        }
1.191     harris41 7315:    }
1.12      www      7316:    return %returnhash;
1.424     matthew  7317: }
                   7318: 
                   7319: sub convert_dump_to_currentdump{
                   7320:     my %hash = %{shift()};
                   7321:     my %returnhash;
                   7322:     # Code ripped from lond, essentially.  The only difference
                   7323:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7324:     # we might run in to problems with parameter names =~ /^v\./
                   7325:     while (my ($key,$value) = each(%hash)) {
                   7326:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7327: 	$symb  = &unescape($symb);
                   7328: 	$param = &unescape($param);
1.424     matthew  7329:         next if ($v eq 'version' || $symb eq 'keys');
                   7330:         next if (exists($returnhash{$symb}) &&
                   7331:                  exists($returnhash{$symb}->{$param}) &&
                   7332:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7333:         $returnhash{$symb}->{$param}=$value;
                   7334:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7335:     }
                   7336:     #
                   7337:     # Remove all of the keys in the hashes which keep track of
                   7338:     # the version of the parameter.
                   7339:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7340:         # use a foreach because we are going to delete from the hash.
                   7341:         foreach my $key (keys(%$param_hash)) {
                   7342:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7343:         }
                   7344:     }
                   7345:     return \%returnhash;
1.12      www      7346: }
                   7347: 
1.627     albertel 7348: # ------------------------------------------------------ critical inc interface
                   7349: 
                   7350: sub cinc {
                   7351:     return &inc(@_,'critical');
                   7352: }
                   7353: 
1.449     matthew  7354: # --------------------------------------------------------------- inc interface
                   7355: 
                   7356: sub inc {
1.627     albertel 7357:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7358:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7359:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7360:     my $uhome=&homeserver($uname,$udomain);
                   7361:     my $items='';
                   7362:     if (! ref($store)) {
                   7363:         # got a single value, so use that instead
                   7364:         $items = &escape($store).'=&';
                   7365:     } elsif (ref($store) eq 'SCALAR') {
                   7366:         $items = &escape($$store).'=&';        
                   7367:     } elsif (ref($store) eq 'ARRAY') {
                   7368:         $items = join('=&',map {&escape($_);} @{$store});
                   7369:     } elsif (ref($store) eq 'HASH') {
                   7370:         while (my($key,$value) = each(%{$store})) {
                   7371:             $items.= &escape($key).'='.&escape($value).'&';
                   7372:         }
                   7373:     }
                   7374:     $items=~s/\&$//;
1.627     albertel 7375:     if ($critical) {
                   7376: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7377:     } else {
                   7378: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7379:     }
1.449     matthew  7380: }
                   7381: 
1.12      www      7382: # --------------------------------------------------------------- put interface
                   7383: 
                   7384: sub put {
1.1462    raeburn  7385:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620     albertel 7386:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7387:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7388:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7389:    my $items='';
1.800     albertel 7390:    foreach my $item (keys(%$storehash)) {
                   7391:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7392:    }
1.12      www      7393:    $items=~s/\&$//;
1.1462    raeburn  7394:    if ($encrypt) {
                   7395:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
                   7396:    } else {
                   7397:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   7398:    }
1.47      www      7399: }
                   7400: 
1.631     albertel 7401: # ------------------------------------------------------------ newput interface
                   7402: 
                   7403: sub newput {
                   7404:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7405:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7406:    if (!$uname) { $uname=$env{'user.name'}; }
                   7407:    my $uhome=&homeserver($uname,$udomain);
                   7408:    my $items='';
                   7409:    foreach my $key (keys(%$storehash)) {
                   7410:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7411:    }
                   7412:    $items=~s/\&$//;
                   7413:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7414: }
                   7415: 
                   7416: # ---------------------------------------------------------  putstore interface
                   7417: 
1.524     raeburn  7418: sub putstore {
1.1269    raeburn  7419:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7420:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7421:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7422:    my $uhome=&homeserver($uname,$udomain);
                   7423:    my $items='';
1.715     albertel 7424:    foreach my $key (keys(%$storehash)) {
                   7425:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7426:    }
1.715     albertel 7427:    $items=~s/\&$//;
1.716     albertel 7428:    my $esc_symb=&escape($symb);
                   7429:    my $esc_v=&escape($version);
1.715     albertel 7430:    my $reply =
1.716     albertel 7431:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7432: 	      $uhome);
1.1269    raeburn  7433:    if (($tolog) && ($reply eq 'ok')) {
                   7434:        my $namevalue='';
                   7435:        foreach my $key (keys(%{$storehash})) {
                   7436:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7437:        }
1.1434    raeburn  7438:        my $ip = &get_requestor_ip();
                   7439:        $namevalue .= 'ip='.&escape($ip).
1.1269    raeburn  7440:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7441:                      '&version='.$esc_v.
                   7442:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7443:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7444:    }
1.715     albertel 7445:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7446:        # gfall back to way things use to be done
1.715     albertel 7447:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7448: 			    $uname);
1.524     raeburn  7449:    }
1.715     albertel 7450:    return $reply;
                   7451: }
                   7452: 
                   7453: sub old_putstore {
1.716     albertel 7454:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7455:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7456:     if (!$uname) { $uname=$env{'user.name'}; }
                   7457:     my $uhome=&homeserver($uname,$udomain);
                   7458:     my %newstorehash;
1.800     albertel 7459:     foreach my $item (keys(%$storehash)) {
                   7460: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7461: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7462:     }
                   7463:     my $items='';
                   7464:     my %allitems = ();
1.800     albertel 7465:     foreach my $item (keys(%newstorehash)) {
                   7466: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7467: 	    my $key = $1.':keys:'.$2;
                   7468: 	    $allitems{$key} .= $3.':';
                   7469: 	}
1.800     albertel 7470: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7471:     }
1.800     albertel 7472:     foreach my $item (keys(%allitems)) {
                   7473: 	$allitems{$item} =~ s/\:$//;
                   7474: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7475:     }
                   7476:     $items=~s/\&$//;
                   7477:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7478: }
                   7479: 
1.47      www      7480: # ------------------------------------------------------ critical put interface
                   7481: 
                   7482: sub cput {
1.134     albertel 7483:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7484:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7485:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7486:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7487:    my $items='';
1.800     albertel 7488:    foreach my $item (keys(%$storehash)) {
                   7489:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7490:    }
1.47      www      7491:    $items=~s/\&$//;
1.134     albertel 7492:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7493: }
                   7494: 
                   7495: # -------------------------------------------------------------- eget interface
                   7496: 
                   7497: sub eget {
1.133     albertel 7498:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7499:    my $items='';
1.800     albertel 7500:    foreach my $item (@$storearr) {
                   7501:        $items.=&escape($item).'&';
1.191     harris41 7502:    }
1.12      www      7503:    $items=~s/\&$//;
1.620     albertel 7504:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7505:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7506:    my $uhome=&homeserver($uname,$udomain);
                   7507:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7508:    my @pairs=split(/\&/,$rep);
                   7509:    my %returnhash=();
1.42      www      7510:    my $i=0;
1.800     albertel 7511:    foreach my $item (@$storearr) {
                   7512:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7513:       $i++;
1.191     harris41 7514:    }
1.12      www      7515:    return %returnhash;
                   7516: }
                   7517: 
1.667     albertel 7518: # ------------------------------------------------------------ tmpput interface
                   7519: sub tmpput {
1.802     raeburn  7520:     my ($storehash,$server,$context)=@_;
1.667     albertel 7521:     my $items='';
1.800     albertel 7522:     foreach my $item (keys(%$storehash)) {
                   7523: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7524:     }
                   7525:     $items=~s/\&$//;
1.802     raeburn  7526:     if (defined($context)) {
                   7527:         $items .= ':'.&escape($context);
                   7528:     }
1.667     albertel 7529:     return &reply("tmpput:$items",$server);
                   7530: }
                   7531: 
                   7532: # ------------------------------------------------------------ tmpget interface
                   7533: sub tmpget {
1.688     albertel 7534:     my ($token,$server)=@_;
                   7535:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7536:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7537:     my %returnhash;
1.1328    raeburn  7538:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7539:         return %returnhash;
                   7540:     }
1.667     albertel 7541:     foreach my $item (split(/\&/,$rep)) {
                   7542: 	my ($key,$value)=split(/=/,$item);
                   7543: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7544:     }
                   7545:     return %returnhash;
                   7546: }
                   7547: 
1.1113    raeburn  7548: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7549: sub tmpdel {
                   7550:     my ($token,$server)=@_;
                   7551:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7552:     return &reply("tmpdel:$token",$server);
                   7553: }
                   7554: 
1.1198    raeburn  7555: # ------------------------------------------------------------ get_timebased_id 
                   7556: 
                   7557: sub get_timebased_id {
                   7558:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7559:         $maxtries) = @_;
                   7560:     my ($newid,$error,$dellock);
                   7561:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   7562:         return ('','ok','invalid call to get suffix');
                   7563:     }
                   7564: 
                   7565: # set defaults for any optional args for which values were not supplied
                   7566:     if ($who eq '') {
                   7567:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7568:     }
                   7569:     if (!$locktries) {
                   7570:         $locktries = 3;
                   7571:     }
                   7572:     if (!$maxtries) {
                   7573:         $maxtries = 10;
                   7574:     }
                   7575:     
                   7576:     if (($cdom eq '') || ($cnum eq '')) {
                   7577:         if ($env{'request.course.id'}) {
                   7578:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7579:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7580:         }
                   7581:         if (($cdom eq '') || ($cnum eq '')) {
                   7582:             return ('','ok','call to get suffix not in course context');
                   7583:         }
                   7584:     }
                   7585: 
                   7586: # construct locking item
                   7587:     my $lockhash = {
                   7588:                       $prefix."\0".'locked_'.$keyid => $who,
                   7589:                    };
                   7590:     my $tries = 0;
                   7591: 
                   7592: # attempt to get lock on nohist_$namespace file
                   7593:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7594:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7595:         $tries ++;
                   7596:         sleep 1;
                   7597:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7598:     }
                   7599: 
                   7600: # attempt to get unique identifier, based on current timestamp
                   7601:     if ($gotlock eq 'ok') {
                   7602:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7603:         my $id = time;
                   7604:         $newid = $id;
1.1268    raeburn  7605:         if ($idtype eq 'addcode') {
                   7606:             $newid .= &sixnum_code();
                   7607:         }
1.1198    raeburn  7608:         my $idtries = 0;
                   7609:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7610:             if ($idtype eq 'concat') {
                   7611:                 $newid = $id.$idtries;
1.1268    raeburn  7612:             } elsif ($idtype eq 'addcode') {
                   7613:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  7614:             } else {
                   7615:                 $newid ++;
                   7616:             }
                   7617:             $idtries ++;
                   7618:         }
                   7619:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7620:             my %new_item =  (
                   7621:                               $prefix."\0".$newid => $who,
                   7622:                             );
                   7623:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7624:                                                  $cdom,$cnum);
                   7625:             if ($putresult ne 'ok') {
                   7626:                 undef($newid);
                   7627:                 $error = 'error saving new item: '.$putresult;
                   7628:             }
                   7629:         } else {
1.1268    raeburn  7630:              undef($newid);
1.1198    raeburn  7631:              $error = ('error: no unique suffix available for the new item ');
                   7632:         }
                   7633: #  remove lock
                   7634:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7635:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7636:     } else {
                   7637:         $error = "error: could not obtain lockfile\n";
                   7638:         $dellock = 'ok';
1.1276    raeburn  7639:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7640:             $dellock = 'nolock';
                   7641:         }
1.1198    raeburn  7642:     }
                   7643:     return ($newid,$dellock,$error);
                   7644: }
                   7645: 
1.1268    raeburn  7646: sub sixnum_code {
                   7647:     my $code;
                   7648:     for (0..6) {
                   7649:         $code .= int( rand(9) );
                   7650:     }
                   7651:     return $code;
                   7652: }
                   7653: 
1.765     albertel 7654: # -------------------------------------------------- portfolio access checking
                   7655: 
                   7656: sub portfolio_access {
1.1270    raeburn  7657:     my ($requrl,$clientip) = @_;
1.765     albertel 7658:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  7659:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7660:     if ($result) {
                   7661:         my %setters;
                   7662:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1473    raeburn  7663:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7664:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
                   7665:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7666:                 return 'B';
                   7667:             }
                   7668:         } else {
1.1473    raeburn  7669:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7670:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7671:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7672:                 return 'B';
                   7673:             }
                   7674:         }
                   7675:     }
1.765     albertel 7676:     if ($result eq 'ok') {
1.766     albertel 7677:        return 'F';
1.765     albertel 7678:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7679:        return 'A';
1.765     albertel 7680:     }
1.766     albertel 7681:     return '';
1.765     albertel 7682: }
                   7683: 
                   7684: sub get_portfolio_access {
1.1270    raeburn  7685:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7686: 
                   7687:     if (!ref($access_hash)) {
                   7688: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7689: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7690: 						   $file_name);
                   7691: 	$access_hash = $access_controls{$file_name};
                   7692:     }
                   7693: 
1.1270    raeburn  7694:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7695:     my $now = time;
                   7696:     if (ref($access_hash) eq 'HASH') {
                   7697:         foreach my $key (keys(%{$access_hash})) {
                   7698:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7699:             if ($start > $now) {
                   7700:                 next;
                   7701:             }
                   7702:             if ($end && $end<$now) {
                   7703:                 next;
                   7704:             }
                   7705:             if ($scope eq 'public') {
                   7706:                 $public = $key;
                   7707:                 last;
                   7708:             } elsif ($scope eq 'guest') {
                   7709:                 $guest = $key;
                   7710:             } elsif ($scope eq 'domains') {
                   7711:                 push(@domains,$key);
                   7712:             } elsif ($scope eq 'users') {
                   7713:                 push(@users,$key);
                   7714:             } elsif ($scope eq 'course') {
                   7715:                 push(@courses,$key);
                   7716:             } elsif ($scope eq 'group') {
                   7717:                 push(@groups,$key);
1.1270    raeburn  7718:             } elsif ($scope eq 'ip') {
                   7719:                 push(@ips,$key);
1.765     albertel 7720:             }
                   7721:         }
                   7722:         if ($public) {
                   7723:             return 'ok';
1.1270    raeburn  7724:         } elsif (@ips > 0) {
                   7725:             my $allowed;
                   7726:             foreach my $ipkey (@ips) {
                   7727:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7728:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7729:                         $allowed = 1;
                   7730:                         last; 
                   7731:                     }
                   7732:                 }
                   7733:             }
                   7734:             if ($allowed) {
                   7735:                 return 'ok';
                   7736:             }
1.765     albertel 7737:         }
                   7738:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7739:             if ($guest) {
                   7740:                 return $guest;
                   7741:             }
                   7742:         } else {
                   7743:             if (@domains > 0) {
                   7744:                 foreach my $domkey (@domains) {
                   7745:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7746:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7747:                             return 'ok';
                   7748:                         }
                   7749:                     }
                   7750:                 }
                   7751:             }
                   7752:             if (@users > 0) {
                   7753:                 foreach my $userkey (@users) {
1.865     raeburn  7754:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7755:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7756:                             if (ref($item) eq 'HASH') {
                   7757:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7758:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7759:                                     return 'ok';
                   7760:                                 }
                   7761:                             }
                   7762:                         }
                   7763:                     } 
1.765     albertel 7764:                 }
                   7765:             }
                   7766:             my %roleshash;
                   7767:             my @courses_and_groups = @courses;
                   7768:             push(@courses_and_groups,@groups); 
                   7769:             if (@courses_and_groups > 0) {
                   7770:                 my (%allgroups,%allroles); 
                   7771:                 my ($start,$end,$role,$sec,$group);
                   7772:                 foreach my $envkey (%env) {
1.1060    raeburn  7773:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7774:                         my $cid = $2.'_'.$3; 
                   7775:                         if ($1 eq 'gr') {
                   7776:                             $group = $4;
                   7777:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7778:                         } else {
                   7779:                             if ($4 eq '') {
                   7780:                                 $sec = 'none';
                   7781:                             } else {
                   7782:                                 $sec = $4;
                   7783:                             }
                   7784:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7785:                         }
1.811     albertel 7786:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7787:                         my $cid = $2.'_'.$3;
                   7788:                         if ($4 eq '') {
                   7789:                             $sec = 'none';
                   7790:                         } else {
                   7791:                             $sec = $4;
                   7792:                         }
                   7793:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7794:                     }
                   7795:                 }
                   7796:                 if (keys(%allroles) == 0) {
                   7797:                     return;
                   7798:                 }
                   7799:                 foreach my $key (@courses_and_groups) {
                   7800:                     my %content = %{$$access_hash{$key}};
                   7801:                     my $cnum = $content{'number'};
                   7802:                     my $cdom = $content{'domain'};
                   7803:                     my $cid = $cdom.'_'.$cnum;
                   7804:                     if (!exists($allroles{$cid})) {
                   7805:                         next;
                   7806:                     }    
                   7807:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7808:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7809:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7810:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7811:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7812:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7813:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7814:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7815:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7816:                                         if (grep/^all$/,@sections) {
                   7817:                                             return 'ok';
                   7818:                                         } else {
                   7819:                                             if (grep/^$sec$/,@sections) {
                   7820:                                                 return 'ok';
                   7821:                                             }
                   7822:                                         }
                   7823:                                     }
                   7824:                                 }
                   7825:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7826:                                     if (grep/^none$/,@groups) {
                   7827:                                         return 'ok';
                   7828:                                     }
                   7829:                                 } else {
                   7830:                                     if (grep/^all$/,@groups) {
                   7831:                                         return 'ok';
                   7832:                                     } 
                   7833:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7834:                                         if (grep/^$group$/,@groups) {
                   7835:                                             return 'ok';
                   7836:                                         }
                   7837:                                     }
                   7838:                                 } 
                   7839:                             }
                   7840:                         }
                   7841:                     }
                   7842:                 }
                   7843:             }
                   7844:             if ($guest) {
                   7845:                 return $guest;
                   7846:             }
                   7847:         }
                   7848:     }
                   7849:     return;
                   7850: }
                   7851: 
                   7852: sub course_group_datechecker {
                   7853:     my ($dates,$now,$status) = @_;
                   7854:     my ($start,$end) = split(/\./,$dates);
                   7855:     if (!$start && !$end) {
                   7856:         return 'ok';
                   7857:     }
                   7858:     if (grep/^active$/,@{$status}) {
                   7859:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7860:             return 'ok';
                   7861:         }
                   7862:     }
                   7863:     if (grep/^previous$/,@{$status}) {
                   7864:         if ($end > $now ) {
                   7865:             return 'ok';
                   7866:         }
                   7867:     }
                   7868:     if (grep/^future$/,@{$status}) {
                   7869:         if ($start > $now) {
                   7870:             return 'ok';
                   7871:         }
                   7872:     }
                   7873:     return; 
                   7874: }
                   7875: 
                   7876: sub parse_portfolio_url {
                   7877:     my ($url) = @_;
                   7878: 
                   7879:     my ($type,$udom,$unum,$group,$file_name);
                   7880:     
1.823     albertel 7881:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7882: 	$type = 1;
                   7883:         $udom = $1;
                   7884:         $unum = $2;
                   7885:         $file_name = $3;
1.823     albertel 7886:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7887: 	$type = 2;
                   7888:         $udom = $1;
                   7889:         $unum = $2;
                   7890:         $group = $3;
                   7891:         $file_name = $3.'/'.$4;
                   7892:     }
                   7893:     if (wantarray) {
                   7894: 	return ($type,$udom,$unum,$file_name,$group);
                   7895:     }
                   7896:     return $type;
                   7897: }
                   7898: 
                   7899: sub is_portfolio_url {
                   7900:     my ($url) = @_;
                   7901:     return scalar(&parse_portfolio_url($url));
                   7902: }
                   7903: 
1.798     raeburn  7904: sub is_portfolio_file {
                   7905:     my ($file) = @_;
1.820     raeburn  7906:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7907:         return 1;
                   7908:     }
                   7909:     return;
                   7910: }
                   7911: 
1.976     raeburn  7912: sub usertools_access {
1.1084    raeburn  7913:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7914:     my ($access,%tools);
                   7915:     if ($context eq '') {
                   7916:         $context = 'tools';
                   7917:     }
                   7918:     if ($context eq 'requestcourses') {
                   7919:         %tools = (
                   7920:                       official   => 1,
                   7921:                       unofficial => 1,
1.1006    raeburn  7922:                       community  => 1,
1.1246    raeburn  7923:                       textbook   => 1,
1.1305    raeburn  7924:                       placement  => 1,
1.1368    raeburn  7925:                       lti        => 1,
1.985     raeburn  7926:                  );
1.1183    raeburn  7927:     } elsif ($context eq 'requestauthor') {
                   7928:         %tools = (
                   7929:                       requestauthor => 1,
                   7930:                  );
1.985     raeburn  7931:     } else {
                   7932:         %tools = (
                   7933:                       aboutme   => 1,
                   7934:                       blog      => 1,
1.1177    raeburn  7935:                       webdav    => 1,
1.985     raeburn  7936:                       portfolio => 1,
1.1489    raeburn  7937:                       timezone  => 1,
1.985     raeburn  7938:                  );
                   7939:     }
1.976     raeburn  7940:     return if (!defined($tools{$tool}));
                   7941: 
1.1242    raeburn  7942:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7943:         $udom = $env{'user.domain'};
                   7944:         $uname = $env{'user.name'};
                   7945:     }
                   7946: 
1.978     raeburn  7947:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7948:         if ($action ne 'reload') {
1.985     raeburn  7949:             if ($context eq 'requestcourses') {
                   7950:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7951:             } elsif ($context eq 'requestauthor') {
                   7952:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7953:             } else {
                   7954:                 return $env{'environment.availabletools.'.$tool};
                   7955:             }
                   7956:         }
1.976     raeburn  7957:     }
                   7958: 
1.1183    raeburn  7959:     my ($toolstatus,$inststatus,$envkey);
                   7960:     if ($context eq 'requestauthor') {
                   7961:         $envkey = $context; 
                   7962:     } else {
                   7963:         $envkey = $context.'.'.$tool;
                   7964:     }
1.976     raeburn  7965: 
1.985     raeburn  7966:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7967:          ($action ne 'reload')) {
1.1183    raeburn  7968:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7969:         $inststatus = $env{'environment.inststatus'};
                   7970:     } else {
1.1084    raeburn  7971:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7972:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7973:             $inststatus = $userenvref->{'inststatus'};
                   7974:         } else {
1.1183    raeburn  7975:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7976:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7977:             $inststatus = $userenv{'inststatus'};
                   7978:         }
1.976     raeburn  7979:     }
                   7980: 
                   7981:     if ($toolstatus ne '') {
                   7982:         if ($toolstatus) {
                   7983:             $access = 1;
                   7984:         } else {
                   7985:             $access = 0;
                   7986:         }
                   7987:         return $access;
                   7988:     }
                   7989: 
1.1084    raeburn  7990:     my ($is_adv,%domdef);
                   7991:     if (ref($is_advref) eq 'HASH') {
                   7992:         $is_adv = $is_advref->{'is_adv'};
                   7993:     } else {
                   7994:         $is_adv = &is_advanced_user($udom,$uname);
                   7995:     }
                   7996:     if (ref($domdefref) eq 'HASH') {
                   7997:         %domdef = %{$domdefref};
                   7998:     } else {
                   7999:         %domdef = &get_domain_defaults($udom);
                   8000:     }
1.976     raeburn  8001:     if (ref($domdef{$tool}) eq 'HASH') {
                   8002:         if ($is_adv) {
                   8003:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   8004:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   8005:                     $access = 1;
                   8006:                 } else {
                   8007:                     $access = 0;
                   8008:                 }
                   8009:                 return $access;
                   8010:             }
                   8011:         }
                   8012:         if ($inststatus ne '') {
                   8013:             my ($hasaccess,$hasnoaccess);
                   8014:             foreach my $affiliation (split(/:/,$inststatus)) {
                   8015:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   8016:                     if ($domdef{$tool}{$affiliation}) {
                   8017:                         $hasaccess = 1;
                   8018:                     } else {
                   8019:                         $hasnoaccess = 1;
                   8020:                     }
                   8021:                 }
                   8022:             }
                   8023:             if ($hasaccess || $hasnoaccess) {
                   8024:                 if ($hasaccess) {
                   8025:                     $access = 1;
                   8026:                 } elsif ($hasnoaccess) {
                   8027:                     $access = 0; 
                   8028:                 }
                   8029:                 return $access;
                   8030:             }
                   8031:         } else {
                   8032:             if ($domdef{$tool}{'default'} ne '') {
                   8033:                 if ($domdef{$tool}{'default'}) {
                   8034:                     $access = 1;
                   8035:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   8036:                     $access = 0;
                   8037:                 }
                   8038:                 return $access;
                   8039:             }
                   8040:         }
                   8041:     } else {
1.1177    raeburn  8042:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  8043:             $access = 1;
                   8044:         } else {
                   8045:             $access = 0;
                   8046:         }
1.976     raeburn  8047:         return $access;
                   8048:     }
                   8049: }
                   8050: 
1.1050    raeburn  8051: sub is_course_owner {
                   8052:     my ($cdom,$cnum,$udom,$uname) = @_;
                   8053:     if (($udom eq '') || ($uname eq '')) {
                   8054:         $udom = $env{'user.domain'};
                   8055:         $uname = $env{'user.name'};
                   8056:     }
                   8057:     unless (($udom eq '') || ($uname eq '')) {
                   8058:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   8059:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   8060:                 return 1;
                   8061:             } else {
                   8062:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   8063:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   8064:                     return 1;
                   8065:                 }
                   8066:             }
                   8067:         }
                   8068:     }
                   8069:     return;
                   8070: }
                   8071: 
1.976     raeburn  8072: sub is_advanced_user {
                   8073:     my ($udom,$uname) = @_;
1.1085    raeburn  8074:     if ($udom ne '' && $uname ne '') {
                   8075:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  8076:             if (wantarray) {
                   8077:                 return ($env{'user.adv'},$env{'user.author'});
                   8078:             } else {
                   8079:                 return $env{'user.adv'};
                   8080:             }
1.1085    raeburn  8081:         }
                   8082:     }
1.976     raeburn  8083:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   8084:     my %allroles;
1.1128    raeburn  8085:     my ($is_adv,$is_author);
1.976     raeburn  8086:     foreach my $role (keys(%roleshash)) {
                   8087:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   8088:         my $area = '/'.$tdomain.'/'.$trest;
                   8089:         if ($sec ne '') {
                   8090:             $area .= '/'.$sec;
                   8091:         }
                   8092:         if (($area ne '') && ($trole ne '')) {
                   8093:             my $spec=$trole.'.'.$area;
                   8094:             if ($trole =~ /^cr\//) {
                   8095:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   8096:             } elsif ($trole ne 'gr') {
                   8097:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   8098:             }
1.1128    raeburn  8099:             if ($trole eq 'au') {
                   8100:                 $is_author = 1;
                   8101:             }
1.976     raeburn  8102:         }
                   8103:     }
                   8104:     foreach my $role (keys(%allroles)) {
                   8105:         last if ($is_adv);
                   8106:         foreach my $item (split(/:/,$allroles{$role})) {
                   8107:             if ($item ne '') {
                   8108:                 my ($privilege,$restrictions)=split(/&/,$item);
                   8109:                 if ($privilege eq 'adv') {
                   8110:                     $is_adv = 1;
                   8111:                     last;
                   8112:                 }
                   8113:             }
                   8114:         }
                   8115:     }
1.1128    raeburn  8116:     if (wantarray) {
                   8117:         return ($is_adv,$is_author);
                   8118:     }
1.976     raeburn  8119:     return $is_adv;
                   8120: }
1.798     raeburn  8121: 
1.1035    raeburn  8122: sub check_can_request {
1.1368    raeburn  8123:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  8124:     my $canreq = 0;
1.1368    raeburn  8125:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8126:         $uname = $env{'user.name'};
                   8127:         $udom = $env{'user.domain'};
                   8128:     }
1.1035    raeburn  8129:     my ($types,$typename) = &Apache::loncommon::course_types();
                   8130:     my @options = ('approval','validate','autolimit');
                   8131:     my $optregex = join('|',@options);
                   8132:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
1.1486    raeburn  8133:         my %willtrust;
1.1035    raeburn  8134:         foreach my $type (@{$types}) {
1.1368    raeburn  8135:             if (&usertools_access($uname,$udom,$type,undef,
                   8136:                                   'requestcourses')) {
1.1035    raeburn  8137:                 $canreq ++;
1.1036    raeburn  8138:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  8139:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  8140:                 }
1.1368    raeburn  8141:                 if ($dom eq $udom) {
1.1035    raeburn  8142:                     $can_request->{$type} = 1;
                   8143:                 }
                   8144:             }
1.1368    raeburn  8145:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   8146:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  8147:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   8148:                 if (@curr > 0) {
1.1036    raeburn  8149:                     foreach my $item (@curr) {
                   8150:                         if (ref($request_domains) eq 'HASH') {
                   8151:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   8152:                             if ($otherdom ne '') {
1.1486    raeburn  8153:                                 unless (exists($willtrust{$otherdom})) {
                   8154:                                     $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
                   8155:                                 }
                   8156:                                 if ($willtrust{$otherdom}) {
                   8157:                                     if (ref($request_domains->{$type}) eq 'ARRAY') {
                   8158:                                         unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   8159:                                             push(@{$request_domains->{$type}},$otherdom);
                   8160:                                         }
                   8161:                                     } else {
1.1036    raeburn  8162:                                         push(@{$request_domains->{$type}},$otherdom);
                   8163:                                     }
                   8164:                                 }
                   8165:                             }
                   8166:                         }
                   8167:                     }
1.1368    raeburn  8168:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  8169:                         $canreq ++;
1.1035    raeburn  8170:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   8171:                             $can_request->{$type} = 1;
                   8172:                         }
                   8173:                     }
                   8174:                 }
                   8175:             }
                   8176:         }
                   8177:     }
                   8178:     return $canreq;
                   8179: }
                   8180: 
1.341     www      8181: # ---------------------------------------------- Custom access rule evaluation
                   8182: 
                   8183: sub customaccess {
                   8184:     my ($priv,$uri)=@_;
1.807     albertel 8185:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      8186:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 8187:     $udom = &LONCAPA::clean_domain($udom);
                   8188:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      8189:     my $access=0;
1.800     albertel 8190:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 8191: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   8192: 	if ($type eq 'user') {
                   8193: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 8194: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 8195: 		if ($tdom) {
                   8196: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   8197: 		}
1.896     albertel 8198: 		if ($tuname) {
                   8199: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 8200: 		}
                   8201: 		$access=($effect eq 'allow');
                   8202: 		last;
                   8203: 	    }
                   8204: 	} else {
                   8205: 	    if ($role) {
                   8206: 		if ($role ne $urole) { next; }
                   8207: 	    }
                   8208: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   8209: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   8210: 		if ($tdom) {
                   8211: 		    if ($tdom ne $udom) { next; }
                   8212: 		}
                   8213: 		if ($tcrs) {
                   8214: 		    if ($tcrs ne $ucrs) { next; }
                   8215: 		}
                   8216: 		if ($tsec) {
                   8217: 		    if ($tsec ne $usec) { next; }
                   8218: 		}
                   8219: 		$access=($effect eq 'allow');
                   8220: 		last;
                   8221: 	    }
                   8222: 	    if ($realm eq '' && $role eq '') {
                   8223: 		$access=($effect eq 'allow');
                   8224: 	    }
1.402     bowersj2 8225: 	}
1.341     www      8226:     }
                   8227:     return $access;
                   8228: }
                   8229: 
1.103     harris41 8230: # ------------------------------------------------- Check for a user privilege
1.12      www      8231: 
                   8232: sub allowed {
1.1461    raeburn  8233:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705     albertel 8234:     my $ver_orguri=$uri;
1.439     www      8235:     $uri=&deversion($uri);
1.152     www      8236:     my $orguri=$uri;
1.52      www      8237:     $uri=&declutter($uri);
1.809     raeburn  8238: 
1.810     raeburn  8239:     if ($priv eq 'evb') {
1.1478    raeburn  8240: # Evade communication block restrictions for specified role in a course or domain
1.810     raeburn  8241:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   8242:             return $1;
                   8243:         } else {
                   8244:             return;
                   8245:         }
                   8246:     }
                   8247: 
1.620     albertel 8248:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      8249: # Free bre access to adm and meta resources
1.1436    raeburn  8250:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 8251: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   8252: 	&& ($priv eq 'bre')) {
1.14      www      8253: 	return 'F';
1.159     www      8254:     }
                   8255: 
1.545     banghart 8256: # Free bre access to user's own portfolio contents
1.714     raeburn  8257:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  8258:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  8259: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8260:         my %setters;
1.1473    raeburn  8261:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   8262:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   8263:         if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  8264:             return 'B';
                   8265:         } else {
                   8266:             return 'F';
                   8267:         }
1.545     banghart 8268:     }
                   8269: 
1.762     raeburn  8270: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8271:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8272:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8273:         if (exists($env{'request.course.id'})) {
                   8274:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8275:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8276:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8277:                 my $courseprivid=$env{'request.course.id'};
                   8278:                 $courseprivid=~s/\_/\//;
                   8279:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8280:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8281:                     return $1; 
1.762     raeburn  8282:                 } else {
                   8283:                     if ($env{'request.course.sec'}) {
                   8284:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8285:                     }
                   8286:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8287:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8288:                         return $2;
                   8289:                     }
1.714     raeburn  8290:                 }
                   8291:             }
                   8292:         }
                   8293:     }
                   8294: 
1.159     www      8295: # Free bre to public access
                   8296: 
                   8297:     if ($priv eq 'bre') {
1.1362    raeburn  8298:         my $copyright;
                   8299:         unless ($uri =~ /ext\.tool/) {
                   8300:             $copyright=&metadata($uri,'copyright');
                   8301:         }
1.620     albertel 8302: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8303:            return 'F'; 
                   8304:         }
1.238     www      8305:         if ($copyright eq 'priv') {
                   8306:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8307: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8308: 		return '';
                   8309:             }
                   8310:         }
                   8311:         if ($copyright eq 'domain') {
                   8312:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8313: 	    unless (($env{'user.domain'} eq $1) ||
                   8314:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8315: 		return '';
                   8316:             }
1.262     matthew  8317:         }
1.620     albertel 8318:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8319:             # Library role, so allow browsing of resources in this domain.
                   8320:             return 'F';
1.238     www      8321:         }
1.341     www      8322:         if ($copyright eq 'custom') {
                   8323: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8324:         }
1.14      www      8325:     }
1.264     matthew  8326:     # Domain coordinator is trying to create a course
1.620     albertel 8327:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8328:         # uri is the requested domain in this case.
                   8329:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8330:         # a role of dc for the domain in question.
1.620     albertel 8331:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8332:     }
1.29      www      8333: 
1.52      www      8334:     my $thisallowed='';
                   8335:     my $statecond=0;
                   8336:     my $courseprivid='';
                   8337: 
1.1039    raeburn  8338:     my $ownaccess;
1.1043    raeburn  8339:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8340:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8341:         if ($uri eq '') {
                   8342:             $ownaccess = 1;
                   8343:         } else {
                   8344:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8345:                 my $udom = $env{'user.domain'};
                   8346:                 my $uname = $env{'user.name'};
                   8347:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8348:                     $ownaccess = 1;
1.1040    raeburn  8349:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8350:                     unless ($uri =~ m{\.\./}) {
                   8351:                         $ownaccess = 1;
                   8352:                     }
                   8353:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8354:                     my $now = time;
                   8355:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8356:                         my $adom = $1;
                   8357:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8358:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1452    raeburn  8359:                                 my ($start,$end) = split(/\./,$env{$key});
                   8360:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  8361:                                     $ownaccess = 1;
                   8362:                                     last;
                   8363:                                 }
                   8364:                             }
                   8365:                         }
                   8366:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8367:                         my $adom = $1;
                   8368:                         my $aname = $2;
1.1042    raeburn  8369:                         foreach my $role ('ca','aa') { 
                   8370:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8371:                                 my ($start,$end) =
1.1452    raeburn  8372:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8373:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8374:                                     $ownaccess = 1;
                   8375:                                     last;
                   8376:                                 }
1.1039    raeburn  8377:                             }
                   8378:                         }
                   8379:                     }
                   8380:                 }
                   8381:             }
                   8382:         }
                   8383:     }
                   8384: 
1.52      www      8385: # Course
                   8386: 
1.620     albertel 8387:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8388:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8389:             $thisallowed.=$1;
                   8390:         }
1.52      www      8391:     }
1.29      www      8392: 
1.52      www      8393: # Domain
                   8394: 
1.620     albertel 8395:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8396:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8397:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8398:             $thisallowed.=$1;
                   8399:         }
1.12      www      8400:     }
1.52      www      8401: 
1.1141    raeburn  8402: # User who is not author or co-author might still be able to edit
                   8403: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8404:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8405:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8406:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8407:             $thisallowed.=$1;
                   8408:         }
                   8409:     }
                   8410: 
1.52      www      8411: # Course: uri itself is a course
1.66      www      8412:     my $courseuri=$uri;
                   8413:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8414:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8415: 
1.620     albertel 8416:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8417:        =~/\Q$priv\E\&([^\:]*)/) {
1.1409    raeburn  8418:         if ($priv eq 'mip') {
                   8419:             my $rem = $1;
                   8420:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8421:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8422:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8423:                 if ($cdom ne '') {
1.1410    raeburn  8424:                     my %passwdconf = &get_passwdconf($cdom);
                   8425:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8426:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8427:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8428:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8429:                                 unless (@inststatuses) {
                   8430:                                     @inststatuses = ('default');
                   8431:                                 }
                   8432:                                 foreach my $status (@inststatuses) {
                   8433:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8434:                                         $thisallowed.=$rem;
                   8435:                                     }
                   8436:                                 }
                   8437:                             }
                   8438:                         }
1.1409    raeburn  8439:                     }
                   8440:                 }
                   8441:             }
                   8442:         } else {
                   8443:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8444:                 $thisallowed.=$1;
                   8445:             }
1.1039    raeburn  8446:         }
1.12      www      8447:     }
1.29      www      8448: 
1.665     albertel 8449: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8450: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8451:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8452: 	$thisallowed='';
1.671     raeburn  8453:         my ($match)=&is_on_map($uri);
                   8454:         if ($match) {
                   8455:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8456:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  8457:                 my $value = $1;
1.1461    raeburn  8458:                 my $deeplinkblock;
                   8459:                 unless ($nodeeplinkcheck) {
                   8460:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8461:                 }
1.1402    raeburn  8462:                 if ($deeplinkblock) {
                   8463:                     $thisallowed='D';
                   8464:                 } elsif ($noblockcheck) {
1.1281    raeburn  8465:                     $thisallowed.=$value;
1.1162    raeburn  8466:                 } else {
1.1424    raeburn  8467:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281    raeburn  8468:                     if (@blockers > 0) {
                   8469:                         $thisallowed = 'B';
                   8470:                     } else {
                   8471:                         $thisallowed.=$value;
                   8472:                     }
1.1162    raeburn  8473:                 }
1.671     raeburn  8474:             }
                   8475:         } else {
1.705     albertel 8476:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8477:             if ($refuri) {
                   8478:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8479:                     $thisallowed='F';
1.671     raeburn  8480:                 } else {
                   8481:                     $refuri=&declutter($refuri);
                   8482:                     my ($match) = &is_on_map($refuri);
                   8483:                     if ($match) {
1.1461    raeburn  8484:                         my $deeplinkblock;
                   8485:                         unless ($nodeeplinkcheck) {
                   8486:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8487:                         }
1.1402    raeburn  8488:                         if ($deeplinkblock) {
                   8489:                             $thisallowed='D';
                   8490:                         } elsif ($noblockcheck) {
1.1281    raeburn  8491:                             $thisallowed='F';
1.1162    raeburn  8492:                         } else {
1.1426    raeburn  8493:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281    raeburn  8494:                             if (@blockers > 0) {
                   8495:                                 $thisallowed = 'B';
                   8496:                             } else {
                   8497:                                 $thisallowed='F';
                   8498:                             }
1.1162    raeburn  8499:                         }
1.671     raeburn  8500:                     }
1.669     raeburn  8501:                 }
1.671     raeburn  8502:             }
                   8503:         }
1.314     www      8504:     }
1.492     albertel 8505: 
1.766     albertel 8506:     if ($priv eq 'bre'
                   8507: 	&& $thisallowed ne 'F' 
                   8508: 	&& $thisallowed ne '2'
                   8509: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  8510: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8511:     }
1.1250    raeburn  8512: 
1.52      www      8513: # Full access at system, domain or course-wide level? Exit.
1.29      www      8514:     if ($thisallowed=~/F/) {
                   8515: 	return 'F';
                   8516:     }
                   8517: 
1.52      www      8518: # If this is generating or modifying users, exit with special codes
1.29      www      8519: 
1.643     www      8520:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8521: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8522: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8523: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8524: 	    unless ($auname) { return $thisallowed; }
                   8525: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8526: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8527: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8528: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8529: 	}
1.52      www      8530: 	return $thisallowed;
                   8531:     }
                   8532: #
1.103     harris41 8533: # Gathered so far: system, domain and course wide privileges
1.52      www      8534: #
                   8535: # Course: See if uri or referer is an individual resource that is part of 
                   8536: # the course
                   8537: 
1.620     albertel 8538:     if ($env{'request.course.id'}) {
1.232     www      8539: 
1.1409    raeburn  8540: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8541: 
                   8542:         if ($priv eq 'mip') {
                   8543:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8544:                 return $thisallowed;
                   8545:             } else {
                   8546:                 return '';
                   8547:             }
                   8548:         }
                   8549: 
1.620     albertel 8550:        $courseprivid=$env{'request.course.id'};
                   8551:        if ($env{'request.course.sec'}) {
                   8552:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8553:        }
                   8554:        $courseprivid=~s/\_/\//;
                   8555:        my $checkreferer=1;
1.232     www      8556:        my ($match,$cond)=&is_on_map($uri);
                   8557:        if ($match) {
                   8558:            $statecond=$cond;
1.620     albertel 8559:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8560:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8561:                my $value = $1;
                   8562:                if ($priv eq 'bre') {
1.1461    raeburn  8563:                    my $deeplinkblock;
                   8564:                    unless ($nodeeplinkcheck) {
                   8565:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8566:                    }
1.1458    raeburn  8567:                    if ($deeplinkblock) {
                   8568:                        $thisallowed = 'D';
                   8569:                    } elsif ($noblockcheck) {
1.1281    raeburn  8570:                        $thisallowed.=$value;
1.1162    raeburn  8571:                    } else {
1.1424    raeburn  8572:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281    raeburn  8573:                        if (@blockers > 0) {
                   8574:                            $thisallowed = 'B';
                   8575:                        } else {
                   8576:                            $thisallowed.=$value;
                   8577:                        }
1.1162    raeburn  8578:                    }
                   8579:                } else {
                   8580:                    $thisallowed.=$value;
                   8581:                }
1.52      www      8582:                $checkreferer=0;
                   8583:            }
1.29      www      8584:        }
1.1424    raeburn  8585: 
1.148     www      8586:        if ($checkreferer) {
1.620     albertel 8587: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8588:             unless ($refuri) {
1.800     albertel 8589:                 foreach my $key (keys(%env)) {
                   8590: 		    if ($key=~/^httpref\..*\*/) {
                   8591: 			my $pattern=$key;
1.156     www      8592:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8593:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8594:                         $pattern=~s/\//\\\//g;
1.152     www      8595:                         if ($orguri=~/$pattern/) {
1.800     albertel 8596: 			    $refuri=$env{$key};
1.148     www      8597:                         }
                   8598:                     }
1.191     harris41 8599:                 }
1.148     www      8600:             }
1.232     www      8601: 
1.148     www      8602:          if ($refuri) { 
1.152     www      8603: 	  $refuri=&declutter($refuri);
1.232     www      8604:           my ($match,$cond)=&is_on_map($refuri);
                   8605:             if ($match) {
                   8606:               my $refstatecond=$cond;
1.620     albertel 8607:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8608:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8609:                   my $value = $1;
                   8610:                   if ($priv eq 'bre') {
1.1461    raeburn  8611:                       my $deeplinkblock;
                   8612:                       unless ($nodeeplinkcheck) {
                   8613:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8614:                       }
1.1402    raeburn  8615:                       if ($deeplinkblock) {
                   8616:                           $thisallowed = 'D';
                   8617:                       } elsif ($noblockcheck) {
1.1281    raeburn  8618:                           $thisallowed.=$value;
1.1162    raeburn  8619:                       } else {
1.1426    raeburn  8620:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281    raeburn  8621:                           if (@blockers > 0) {
                   8622:                               $thisallowed = 'B';
                   8623:                           } else {
                   8624:                               $thisallowed.=$value;
                   8625:                           }
1.1162    raeburn  8626:                       }
                   8627:                   } else {
                   8628:                       $thisallowed.=$value;
                   8629:                   }
1.53      www      8630:                   $uri=$refuri;
                   8631:                   $statecond=$refstatecond;
1.52      www      8632:               }
                   8633:           }
1.148     www      8634:         }
1.29      www      8635:        }
1.52      www      8636:    }
1.29      www      8637: 
1.52      www      8638: #
1.103     harris41 8639: # Gathered now: all privileges that could apply, and condition number
1.52      www      8640: # 
                   8641: #
                   8642: # Full or no access?
                   8643: #
1.29      www      8644: 
1.52      www      8645:     if ($thisallowed=~/F/) {
                   8646: 	return 'F';
                   8647:     }
1.29      www      8648: 
1.52      www      8649:     unless ($thisallowed) {
                   8650:         return '';
                   8651:     }
1.29      www      8652: 
1.52      www      8653: # Restrictions exist, deal with them
                   8654: #
                   8655: #   C:according to course preferences
                   8656: #   R:according to resource settings
                   8657: #   L:unless locked
                   8658: #   X:according to user session state
                   8659: #
                   8660: 
                   8661: # Possibly locked functionality, check all courses
1.1454    raeburn  8662: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      8663: # Locks might take effect only after 10 minutes cache expiration for other
1.1454    raeburn  8664: # courses, and 2 minutes for current course, in which user has st or ta role
                   8665: # which is neither expired nor a future role (unless current course).
1.52      www      8666: 
1.1454    raeburn  8667:     my ($needlockcheck,$now,$crsonly);
1.52      www      8668:     if ($thisallowed=~/L/) {
1.1454    raeburn  8669:         $now = time;
                   8670:         if ($priv eq 'bre') {
                   8671:             if ($uri ne '') {
                   8672:                 if ($orguri =~ m{^/+res/}) {
                   8673:                     if ($uri =~ m{^lib/templates/}) {
                   8674:                         if ($env{'request.course.id'}) {
                   8675:                             $crsonly = 1;
                   8676:                             $needlockcheck = 1;
                   8677:                         }
                   8678:                     } else {
                   8679:                         $needlockcheck = 1;
                   8680:                     }
                   8681:                 } elsif ($env{'request.course.id'}) {
                   8682:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   8683:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   8684:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   8685:                         $crsonly = 1;
                   8686:                     }
                   8687:                     $needlockcheck = 1;
                   8688:                 }
                   8689:             }
                   8690:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   8691:             $needlockcheck = 1;
                   8692:         }
                   8693:     }
                   8694:     if ($needlockcheck) {
1.1453    raeburn  8695:         foreach my $envkey (keys(%env)) {
1.54      www      8696:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8697:                my $courseid=$2;
                   8698:                my $roleid=$1.'.'.$2;
1.92      www      8699:                $courseid=~s/^\///;
1.1453    raeburn  8700:                unless ($env{'request.role'} eq $roleid) {
                   8701:                    my ($start,$end) = split(/\./,$env{$envkey});
                   8702:                    next unless (($now >= $start) && (!$end || $end > $now));
                   8703:                }
1.54      www      8704:                my $expiretime=600;
1.620     albertel 8705:                if ($env{'request.role'} eq $roleid) {
1.54      www      8706: 		  $expiretime=120;
                   8707:                }
                   8708: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8709:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8710:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8711: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8712:                }
1.620     albertel 8713:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8714:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8715: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8716:                        &log($env{'user.domain'},$env{'user.name'},
                   8717:                             $env{'user.home'},
1.57      www      8718:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8719:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8720:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8721: 		       return '';
                   8722:                    }
                   8723:                }
1.620     albertel 8724:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8725:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1455    raeburn  8726: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 8727:                        &log($env{'user.domain'},$env{'user.name'},
                   8728:                             $env{'user.home'},
1.57      www      8729:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8730:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8731:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8732: 		       return '';
                   8733:                    }
                   8734:                }
                   8735: 	   }
1.29      www      8736:        }
1.52      www      8737:     }
1.1424    raeburn  8738: 
1.52      www      8739: #
                   8740: # Rest of the restrictions depend on selected course
                   8741: #
                   8742: 
1.620     albertel 8743:     unless ($env{'request.course.id'}) {
1.766     albertel 8744: 	if ($thisallowed eq 'A') {
                   8745: 	    return 'A';
1.814     raeburn  8746:         } elsif ($thisallowed eq 'B') {
                   8747:             return 'B';
1.766     albertel 8748: 	} else {
                   8749: 	    return '1';
                   8750: 	}
1.52      www      8751:     }
1.29      www      8752: 
1.52      www      8753: #
                   8754: # Now user is definitely in a course
                   8755: #
1.53      www      8756: 
                   8757: 
                   8758: # Course preferences
                   8759: 
                   8760:    if ($thisallowed=~/C/) {
1.620     albertel 8761:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8762:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8763:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8764: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  8765: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8766: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8767: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8768: 			$env{'request.course.id'});
                   8769: 	   }
1.237     www      8770:            return '';
                   8771:        }
                   8772: 
1.620     albertel 8773:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8774: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  8775: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8776: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8777: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8778: 			$env{'request.course.id'});
                   8779: 	   }
1.54      www      8780:            return '';
                   8781:        }
1.53      www      8782:    }
                   8783: 
                   8784: # Resource preferences
                   8785: 
                   8786:    if ($thisallowed=~/R/) {
1.620     albertel 8787:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8788:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8789: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8790: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8791: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8792: 	   }
                   8793: 	   return '';
1.54      www      8794:        }
1.53      www      8795:    }
1.30      www      8796: 
1.1461    raeburn  8797: # Restricted for deeplinked session?
                   8798: 
                   8799:     if ($env{'request.deeplink.login'}) {
                   8800:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
                   8801:             if (!$symb) { $symb=&symbread($uri,1); }
                   8802:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
                   8803:                 return '';
                   8804:             }
                   8805:         }
                   8806:     }
                   8807: 
1.246     www      8808: # Restricted by state or randomout?
1.30      www      8809: 
1.52      www      8810:    if ($thisallowed=~/X/) {
1.620     albertel 8811:       if ($env{'acc.randomout'}) {
1.579     albertel 8812: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8813:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8814:             return ''; 
                   8815:          }
1.247     www      8816:       }
                   8817:       if (&condval($statecond)) {
1.52      www      8818: 	 return '2';
                   8819:       } else {
                   8820:          return '';
                   8821:       }
                   8822:    }
1.30      www      8823: 
1.766     albertel 8824:     if ($thisallowed eq 'A') {
                   8825: 	return 'A';
1.814     raeburn  8826:     } elsif ($thisallowed eq 'B') {
                   8827:         return 'B';
1.1402    raeburn  8828:     } elsif ($thisallowed eq 'D') {
                   8829:         return 'D';
1.766     albertel 8830:     }
1.52      www      8831:    return 'F';
1.232     www      8832: }
1.1162    raeburn  8833: 
1.1192    raeburn  8834: # ------------------------------------------- Check construction space access
                   8835: 
                   8836: sub constructaccess {
                   8837:     my ($url,$setpriv)=@_;
                   8838: 
                   8839: # We do not allow editing of previous versions of files
                   8840:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8841: 
                   8842: # Get username and domain from URL
                   8843:     my ($ownername,$ownerdomain,$ownerhome);
                   8844: 
                   8845:     ($ownerdomain,$ownername) =
1.1325    raeburn  8846:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  8847: 
                   8848: # The URL does not really point to any authorspace, forget it
                   8849:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8850: 
                   8851: # Now we need to see if the user has access to the authorspace of
                   8852: # $ownername at $ownerdomain
                   8853: 
                   8854:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8855: # Real author for this?
                   8856:        $ownerhome = $env{'user.home'};
                   8857:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8858:           return ($ownername,$ownerdomain,$ownerhome);
                   8859:        }
                   8860:     } else {
                   8861: # Co-author for this?
                   8862:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8863:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8864:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8865:             return ($ownername,$ownerdomain,$ownerhome);
                   8866:         }
1.1312    raeburn  8867:         if ($env{'request.course.id'}) {
                   8868:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   8869:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   8870:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   8871:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   8872:                     return ($ownername,$ownerdomain,$ownerhome);
                   8873:                 }
                   8874:             }
                   8875:         }
1.1192    raeburn  8876:     }
                   8877: 
                   8878: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8879: # we might as well leave
                   8880:    unless ($setpriv) { return ''; }
                   8881: 
                   8882: # Backdoor access?
                   8883:     my $allowed=&allowed('eco',$ownerdomain);
                   8884: # Nope
                   8885:     unless ($allowed) { return ''; }
                   8886: # Looks like we may have access, but could be locked by the owner of the construction space
                   8887:     if ($allowed eq 'U') {
                   8888:         my %blocked=&get('environment',['domcoord.author'],
                   8889:                          $ownerdomain,$ownername);
                   8890: # Is blocked by owner
                   8891:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8892:     }
                   8893:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8894: # Grant temporary access
                   8895:         my $then=$env{'user.login.time'};
1.1209    raeburn  8896:         my $update=$env{'user.update.time'};
1.1192    raeburn  8897:         if (!$update) { $update = $then; }
                   8898:         my $refresh=$env{'user.refresh.time'};
                   8899:         if (!$refresh) { $refresh = $update; }
                   8900:         my $now = time;
                   8901:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8902:                            $now,'ca','constructaccess');
                   8903:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8904:         return($ownername,$ownerdomain,$ownerhome);
                   8905:     }
                   8906: # No business here
                   8907:     return '';
                   8908: }
                   8909: 
1.1282    raeburn  8910: # ----------------------------------------------------------- Content Blocking
                   8911: 
                   8912: {
                   8913: # Caches for faster Course Contents display where content blocking
                   8914: # is in operation (i.e., interval param set) for timed quiz.
                   8915: #
                   8916: # User for whom data are being temporarily cached.
                   8917: my $cacheduser='';
1.1424    raeburn  8918: # Course for which data are being temporarily cached.
                   8919: my $cachedcid='';
1.1282    raeburn  8920: # Cached blockers for this user (a hash of blocking items). 
                   8921: my %cachedblockers=();
                   8922: # When the data were last cached.
                   8923: my $cachedlast='';
                   8924: 
                   8925: sub load_all_blockers {
1.1427    raeburn  8926:     my ($uname,$udom)=@_;
1.1282    raeburn  8927:     if (($uname ne '') && ($udom ne '')) { 
                   8928:         if (($cacheduser eq $uname.':'.$udom) &&
1.1424    raeburn  8929:             ($cachedcid eq $env{'request.course.id'}) &&
1.1427    raeburn  8930:             (abs($cachedlast-time)<5)) {
1.1282    raeburn  8931:             return;
                   8932:         }
                   8933:     }
                   8934:     $cachedlast=time;
                   8935:     $cacheduser=$uname.':'.$udom;
1.1424    raeburn  8936:     $cachedcid=$env{'request.course.id'};
1.1427    raeburn  8937:     %cachedblockers = &get_commblock_resources();
1.1424    raeburn  8938:     return;
1.1282    raeburn  8939: }
                   8940: 
1.1162    raeburn  8941: sub get_comm_blocks {
                   8942:     my ($cdom,$cnum) = @_;
                   8943:     if ($cdom eq '' || $cnum eq '') {
                   8944:         return unless ($env{'request.course.id'});
                   8945:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8946:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8947:     }
                   8948:     my %commblocks;
                   8949:     my $hashid=$cdom.'_'.$cnum;
                   8950:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8951:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8952:         %commblocks = %{$blocksref};
                   8953:     } else {
                   8954:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8955:         my $cachetime = 600;
                   8956:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8957:     }
                   8958:     return %commblocks;
                   8959: }
                   8960: 
1.1282    raeburn  8961: sub get_commblock_resources {
                   8962:     my ($blocks) = @_;
                   8963:     my %blockers = ();
                   8964:     return %blockers unless ($env{'request.course.id'});
1.1470    raeburn  8965:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8966:     if ($env{'request.course.sec'}) {
                   8967:         $courseurl .= '/'.$env{'request.course.sec'};
                   8968:     }
                   8969:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  8970:     my %commblocks;
                   8971:     if (ref($blocks) eq 'HASH') {
                   8972:         %commblocks = %{$blocks};
                   8973:     } else {
                   8974:         %commblocks = &get_comm_blocks();
                   8975:     }
1.1282    raeburn  8976:     return %blockers unless (keys(%commblocks) > 0); 
                   8977:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8978:     return %blockers unless (ref($navmap));
1.1162    raeburn  8979:     my $now = time;
                   8980:     foreach my $block (keys(%commblocks)) {
                   8981:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8982:             my ($start,$end) = ($1,$2);
                   8983:             if ($start <= $now && $end >= $now) {
                   8984:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8985:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8986:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8987:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8988:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8989:                             }
                   8990:                         }
                   8991:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8992:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8993:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8994:                             }
                   8995:                         }
                   8996:                     }
                   8997:                 }
                   8998:             }
                   8999:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   9000:             my $item = $1;
                   9001:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   9002:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1471    raeburn  9003:                     my (@interval,$mapname);
1.1282    raeburn  9004:                     my $type = 'map';
                   9005:                     if ($item eq 'course') {
                   9006:                         $type = 'course';
                   9007:                         @interval=&EXT("resource.0.interval");
                   9008:                     } else {
                   9009:                         if ($item =~ /___\d+___/) {
                   9010:                             $type = 'resource';
                   9011:                             @interval=&EXT("resource.0.interval",$item);
1.1162    raeburn  9012:                         } else {
1.1471    raeburn  9013:                             $mapname = &deversion($item);
                   9014:                             if (ref($navmap)) {
                   9015:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
                   9016:                                 @interval = ($timelimit,'map');
1.1162    raeburn  9017:                             }
                   9018:                         }
1.1282    raeburn  9019:                     }
1.1310    raeburn  9020:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  9021:                         my $timelimit = $1; 
1.1282    raeburn  9022:                         my $first_access;
                   9023:                         if ($type eq 'resource') {
                   9024:                             $first_access=&get_first_access($interval[1],$item);
                   9025:                         } elsif ($type eq 'map') {
                   9026:                             $first_access=&get_first_access($interval[1],undef,$item);
                   9027:                         } else {
                   9028:                             $first_access=&get_first_access($interval[1]);
                   9029:                         }
                   9030:                         if ($first_access) {
1.1292    raeburn  9031:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  9032:                             if ($timesup > $now) {
                   9033:                                 my $activeblock;
1.1471    raeburn  9034:                                 if ($type eq 'resource') {
                   9035:                                     if (ref($navmap)) {
                   9036:                                         my $res = $navmap->getBySymb($item);
                   9037:                                         if ($res->answerable()) {
                   9038:                                             $activeblock = 1;
                   9039:                                         }
                   9040:                                     }
                   9041:                                 } elsif ($type eq 'map') {
                   9042:                                     my $mapsymb = &symbread($mapname,1);
                   9043:                                     if (($mapsymb) && (ref($navmap))) {
                   9044:                                         my $mapres = $navmap->getBySymb($mapsymb);
                   9045:                                         if (ref($mapres)) {
                   9046:                                             my $first = $mapres->map_start();
                   9047:                                             my $finish = $mapres->map_finish();
                   9048:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   9049:                                             if (ref($it)) {
                   9050:                                                 my $res;
                   9051:                                                 while ($res = $it->next(undef,1)) {
                   9052:                                                     next unless (ref($res));
                   9053:                                                     my $symb = $res->symb();
                   9054:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
                   9055:                                                     @interval=&EXT("resource.0.interval",$symb);
                   9056:                                                     if ($interval[1] eq 'map') {
                   9057:                                                         if ($res->answerable()) {
                   9058:                                                             $activeblock = 1;
                   9059:                                                             last;
                   9060:                                                         }
                   9061:                                                     }
                   9062:                                                 }
                   9063:                                             }
                   9064:                                         }
1.1282    raeburn  9065:                                     }
                   9066:                                 }
                   9067:                                 if ($activeblock) {
                   9068:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   9069:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   9070:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   9071:                                          }
                   9072:                                     }
                   9073:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   9074:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   9075:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  9076:                                         }
1.1162    raeburn  9077:                                     }
                   9078:                                 }
                   9079:                             }
                   9080:                         }
                   9081:                     }
                   9082:                 }
                   9083:             }
                   9084:         }
                   9085:     }
1.1282    raeburn  9086:     return %blockers;
1.1162    raeburn  9087: }
                   9088: 
1.1282    raeburn  9089: sub has_comm_blocking {
1.1427    raeburn  9090:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1282    raeburn  9091:     my @blockers;
                   9092:     return unless ($env{'request.course.id'});
                   9093:     return unless ($priv eq 'bre');
                   9094:     return if ($env{'request.state'} eq 'construct');
1.1470    raeburn  9095:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   9096:     if ($env{'request.course.sec'}) {
                   9097:         $courseurl .= '/'.$env{'request.course.sec'};
                   9098:     }
                   9099:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1427    raeburn  9100:     my %blockinfo;
                   9101:     if (ref($blocks) eq 'HASH') {
                   9102:         %blockinfo = &get_commblock_resources($blocks);
                   9103:     } else {
                   9104:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   9105:         %blockinfo = %cachedblockers;
                   9106:     }
                   9107:     return unless (keys(%blockinfo) > 0);
1.1282    raeburn  9108:     my (%possibles,@symbs);
                   9109:     if (!$symb) {
1.1427    raeburn  9110:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  9111:     }
1.1282    raeburn  9112:     if ($symb) {
                   9113:         @symbs = ($symb);
                   9114:     } elsif (keys(%possibles)) { 
                   9115:         @symbs = keys(%possibles);
                   9116:     }
                   9117:     my $noblock;
                   9118:     foreach my $symb (@symbs) {
                   9119:         last if ($noblock);
                   9120:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1427    raeburn  9121:         foreach my $block (keys(%blockinfo)) {
1.1282    raeburn  9122:             if ($block =~ /^firstaccess____(.+)$/) {
                   9123:                 my $item = $1;
1.1424    raeburn  9124:                 unless ($blocked) {
                   9125:                     if (($item eq $map) || ($item eq $symb)) {
                   9126:                         $noblock = 1;
                   9127:                         last;
                   9128:                     }
1.1282    raeburn  9129:                 }
                   9130:             }
1.1427    raeburn  9131:             if (ref($blockinfo{$block}) eq 'HASH') {
                   9132:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   9133:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1282    raeburn  9134:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9135:                             push(@blockers,$block);
                   9136:                         }
                   9137:                     }
                   9138:                 }
1.1427    raeburn  9139:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   9140:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1424    raeburn  9141:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9142:                             push(@blockers,$block);
                   9143:                         }
1.1282    raeburn  9144:                     }
                   9145:                 }
1.1162    raeburn  9146:             }
                   9147:         }
                   9148:     }
1.1424    raeburn  9149:     unless ($noblock) { 
                   9150:         return @blockers;
                   9151:     }
                   9152:     return;
1.1282    raeburn  9153: }
1.1162    raeburn  9154: }
                   9155: 
1.1402    raeburn  9156: sub deeplink_check {
                   9157:     my ($priv,$symb,$uri) = @_;
                   9158:     return unless ($env{'request.course.id'});
                   9159:     return unless ($priv eq 'bre');
                   9160:     return if ($env{'request.state'} eq 'construct');
                   9161:     return if ($env{'request.role.adv'});
                   9162:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9163:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9164:     my (%possibles,@symbs);
                   9165:     if (!$symb) {
                   9166:         $symb = &symbread($uri,1,1,1,\%possibles);
                   9167:     }
                   9168:     if ($symb) {
                   9169:         @symbs = ($symb);
                   9170:     } elsif (keys(%possibles)) {
                   9171:         @symbs = keys(%possibles);
                   9172:     }
                   9173: 
1.1461    raeburn  9174:     my ($deeplink_symb,$allow);
                   9175:     if ($env{'request.deeplink.login'}) {
                   9176:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
1.1402    raeburn  9177:     }
                   9178:     foreach my $symb (@symbs) {
                   9179:         last if ($allow);
                   9180:         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   9181:         if ($deeplink eq '') {
                   9182:             $allow = 1;
                   9183:         } else {
1.1463    raeburn  9184:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
                   9185:             if ($state ne 'only') {
1.1402    raeburn  9186:                 $allow = 1;
1.1463    raeburn  9187:             } else {
                   9188:                 my $check_deeplink_entry;
                   9189:                 if ($protect ne 'none') {
                   9190:                     my ($acctype,$item) = split(/:/,$protect);
                   9191:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
                   9192:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
                   9193:                             $check_deeplink_entry = 1
                   9194:                         }
                   9195:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
                   9196:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
                   9197:                             $check_deeplink_entry = 1;
                   9198:                         }
                   9199:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   9200:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   9201:                             $check_deeplink_entry = 1;
                   9202:                         }
                   9203:                     }
                   9204:                 }
                   9205:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
1.1402    raeburn  9206:                     if ($scope eq 'res') {
1.1461    raeburn  9207:                         if ($symb eq $deeplink_symb) {
1.1402    raeburn  9208:                             $allow = 1;
                   9209:                         }
1.1459    raeburn  9210:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
1.1463    raeburn  9211:                         my ($map_from_symb,$map_from_login);
1.1461    raeburn  9212:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
                   9213:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9214:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
                   9215:                         } else {
                   9216:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
                   9217:                         }
1.1459    raeburn  9218:                         if (($map_from_symb) && ($map_from_login)) {
                   9219:                             if ($map_from_symb eq $map_from_login) {
                   9220:                                 $allow = 1;
                   9221:                             } elsif ($scope eq 'rec') {
                   9222:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
                   9223:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
                   9224:                                     $allow = 1;
                   9225:                                 }
                   9226:                             }
                   9227:                         }
1.1402    raeburn  9228:                     }
                   9229:                 }
                   9230:             }
                   9231:         }
                   9232:     }
                   9233:     return if ($allow);
                   9234:     return 1;
                   9235: }
                   9236: 
1.1282    raeburn  9237: # -------------------------------- Deversion and split uri into path an filename   
                   9238: 
1.1133    foxr     9239: #
1.1282    raeburn  9240: #   Removes the version from a URI and
1.1133    foxr     9241: #   splits it in to its filename and path to the filename.
                   9242: #   Seems like File::Basename could have done this more clearly.
                   9243: #   Parameters:
                   9244: #      $uri   - input URI
                   9245: #   Returns:
                   9246: #     Two element list consisting of 
                   9247: #     $pathname  - the URI up to and excluding the trailing /
                   9248: #     $filename  - The part of the URI following the last /
                   9249: #  NOTE:
                   9250: #    Another realization of this is simply:
                   9251: #    use File::Basename;
                   9252: #    ...
                   9253: #    $uri = shift;
                   9254: #    $filename = basename($uri);
                   9255: #    $path     = dirname($uri);
                   9256: #    return ($filename, $path);
                   9257: #
                   9258: #     The implementation below is probably faster however.
                   9259: #
1.710     albertel 9260: sub split_uri_for_cond {
                   9261:     my $uri=&deversion(&declutter(shift));
                   9262:     my @uriparts=split(/\//,$uri);
                   9263:     my $filename=pop(@uriparts);
                   9264:     my $pathname=join('/',@uriparts);
                   9265:     return ($pathname,$filename);
                   9266: }
1.232     www      9267: # --------------------------------------------------- Is a resource on the map?
                   9268: 
                   9269: sub is_on_map {
1.710     albertel 9270:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 9271:     #Trying to find the conditional for the file
1.620     albertel 9272:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 9273: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      9274:     if ($match) {
1.289     bowersj2 9275: 	return (1,$1);
                   9276:     } else {
1.434     www      9277: 	return (0,0);
1.289     bowersj2 9278:     }
1.12      www      9279: }
                   9280: 
1.427     www      9281: # --------------------------------------------------------- Get symb from alias
                   9282: 
                   9283: sub get_symb_from_alias {
                   9284:     my $symb=shift;
                   9285:     my ($map,$resid,$url)=&decode_symb($symb);
                   9286: # Already is a symb
                   9287:     if ($url) { return $symb; }
                   9288: # Must be an alias
                   9289:     my $aliassymb='';
                   9290:     my %bighash;
1.620     albertel 9291:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      9292:                             &GDBM_READER(),0640)) {
                   9293:         my $rid=$bighash{'mapalias_'.$symb};
                   9294: 	if ($rid) {
                   9295: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 9296: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   9297: 				    $resid,$bighash{'src_'.$rid});
1.427     www      9298: 	}
                   9299:         untie %bighash;
                   9300:     }
                   9301:     return $aliassymb;
                   9302: }
                   9303: 
1.12      www      9304: # ----------------------------------------------------------------- Define Role
                   9305: 
                   9306: sub definerole {
                   9307:   if (allowed('mcr','/')) {
1.1326    raeburn  9308:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9309:     foreach my $role (split(':',$sysrole)) {
                   9310: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9311:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9312:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9313: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9314:                return "refused:s:$crole&$cqual"; 
                   9315:             }
                   9316:         }
1.191     harris41 9317:     }
1.800     albertel 9318:     foreach my $role (split(':',$domrole)) {
                   9319: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9320:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9321:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9322: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9323:                return "refused:d:$crole&$cqual"; 
                   9324:             }
                   9325:         }
1.191     harris41 9326:     }
1.800     albertel 9327:     foreach my $role (split(':',$courole)) {
                   9328: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9329:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9330:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9331: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9332:                return "refused:c:$crole&$cqual"; 
                   9333:             }
                   9334:         }
1.191     harris41 9335:     }
1.1326    raeburn  9336:     my $uhome;
                   9337:     if (($uname ne '') && ($udom ne '')) {
                   9338:         $uhome = &homeserver($uname,$udom);
                   9339:         return $uhome if ($uhome eq 'no_host');
                   9340:     } else {
                   9341:         $uname = $env{'user.name'};
                   9342:         $udom = $env{'user.domain'};
                   9343:         $uhome = $env{'user.home'};
                   9344:     }
1.620     albertel 9345:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  9346:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9347:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  9348:     return reply($command,$uhome);
1.12      www      9349:   } else {
                   9350:     return 'refused';
                   9351:   }
1.105     harris41 9352: }
                   9353: 
                   9354: # ---------------- Make a metadata query against the network of library servers
                   9355: 
                   9356: sub metadata_query {
1.1237    raeburn  9357:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9358:     my %rhash;
1.845     albertel 9359:     my %libserv = &all_library();
1.244     matthew  9360:     my @server_list = (defined($server_array) ? @$server_array
                   9361:                                               : keys(%libserv) );
                   9362:     for my $server (@server_list) {
1.1237    raeburn  9363:         my $domains = ''; 
                   9364:         if (ref($domains_hash) eq 'HASH') {
                   9365:             $domains = $domains_hash->{$server}; 
                   9366:         }
1.118     harris41 9367: 	unless ($custom or $customshow) {
1.1237    raeburn  9368: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9369: 	    $rhash{$server}=$reply;
                   9370: 	}
                   9371: 	else {
                   9372: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  9373: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9374: 			     $server);
                   9375: 	    $rhash{$server}=$reply;
                   9376: 	}
1.112     harris41 9377:     }
1.118     harris41 9378:     return \%rhash;
1.240     www      9379: }
                   9380: 
                   9381: # ----------------------------------------- Send log queries and wait for reply
                   9382: 
                   9383: sub log_query {
                   9384:     my ($uname,$udom,$query,%filters)=@_;
                   9385:     my $uhome=&homeserver($uname,$udom);
                   9386:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9387:     my $uhost=&hostname($uhome);
1.800     albertel 9388:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9389:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9390:                        $uhome);
1.479     albertel 9391:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9392:     return get_query_reply($queryid);
                   9393: }
                   9394: 
1.818     raeburn  9395: # -------------------------- Update MySQL table for portfolio file
                   9396: 
                   9397: sub update_portfolio_table {
1.821     raeburn  9398:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9399:     if ($group ne '') {
                   9400:         $file_name =~s /^\Q$group\E//;
                   9401:     }
1.818     raeburn  9402:     my $homeserver = &homeserver($uname,$udom);
                   9403:     my $queryid=
1.821     raeburn  9404:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9405:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9406:     my $reply = &get_query_reply($queryid);
                   9407:     return $reply;
                   9408: }
                   9409: 
1.899     raeburn  9410: # -------------------------- Update MySQL allusers table
                   9411: 
                   9412: sub update_allusers_table {
                   9413:     my ($uname,$udom,$names) = @_;
                   9414:     my $homeserver = &homeserver($uname,$udom);
                   9415:     my $queryid=
                   9416:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9417:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9418:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9419:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9420:                'generation='.&escape($names->{'generation'}).'%%'.
                   9421:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9422:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9423:     return;
1.899     raeburn  9424: }
                   9425: 
1.508     raeburn  9426: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9427: 
                   9428: sub fetch_enrollment_query {
1.511     raeburn  9429:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  9430:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9431:     my $maxtries = 1;
1.508     raeburn  9432:     if ($context eq 'automated') {
                   9433:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  9434:         $sleep = 2;
                   9435:         $loopmax = 100;
1.547     raeburn  9436:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9437:     } else {
                   9438:         $homeserver = &homeserver($cnum,$dom);
                   9439:     }
1.838     albertel 9440:     my $host=&hostname($homeserver);
1.506     raeburn  9441:     my $cmd = '';
1.1000    raeburn  9442:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9443:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9444:     }
                   9445:     $cmd =~ s/%%$//;
                   9446:     $cmd = &escape($cmd);
                   9447:     my $query = 'fetchenrollment';
1.620     albertel 9448:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9449:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9450:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9451:         return 'error: '.$queryid;
                   9452:     }
1.1317    raeburn  9453:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9454:     my $tries = 1;
                   9455:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  9456:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9457:         $tries ++;
                   9458:     }
1.526     raeburn  9459:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9460:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9461:     } else {
1.901     albertel 9462:         my @responses = split(/:/,$reply);
1.1322    raeburn  9463:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9464:             foreach my $line (@responses) {
                   9465:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9466:                 $$replyref{$key} = $value;
                   9467:             }
                   9468:         } else {
1.1117    foxr     9469:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9470:             foreach my $line (@responses) {
                   9471:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9472:                 $$replyref{$key} = $value;
                   9473:                 if ($value > 0) {
1.800     albertel 9474:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9475:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9476:                         my $destname = $pathname.'/'.$filename;
                   9477:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9478:                         if ($xml_classlist =~ /^error/) {
                   9479:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9480:                         } else {
1.1359    raeburn  9481:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9482:                                 print FILE &unescape($xml_classlist);
                   9483:                                 close(FILE);
1.526     raeburn  9484:                             } else {
                   9485:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9486:                             }
                   9487:                         }
                   9488:                     }
                   9489:                 }
                   9490:             }
                   9491:         }
                   9492:         return 'ok';
                   9493:     }
                   9494:     return 'error';
                   9495: }
                   9496: 
1.242     www      9497: sub get_query_reply {
1.1471    raeburn  9498:     my ($queryid,$sleep,$loopmax) = @_;
1.1317    raeburn  9499:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9500:         $sleep = 0.2;
                   9501:     }
                   9502:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9503:         $loopmax = 100;
                   9504:     }
1.1117    foxr     9505:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9506:     my $reply='';
1.1317    raeburn  9507:     for (1..$loopmax) {
                   9508: 	sleep($sleep);
1.240     www      9509:         if (-e $replyfile.'.end') {
1.1359    raeburn  9510: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9511: 		$reply = join('',<$fh>);
                   9512: 		close($fh);
1.240     www      9513: 	   } else { return 'error: reply_file_error'; }
1.242     www      9514:            return &unescape($reply);
                   9515: 	}
1.240     www      9516:     }
1.242     www      9517:     return 'timeout:'.$queryid;
1.240     www      9518: }
                   9519: 
                   9520: sub courselog_query {
1.241     www      9521: #
                   9522: # possible filters:
                   9523: # url: url or symb
                   9524: # username
                   9525: # domain
                   9526: # action: view, submit, grade
                   9527: # start: timestamp
                   9528: # end: timestamp
                   9529: #
1.240     www      9530:     my (%filters)=@_;
1.620     albertel 9531:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9532:     if ($filters{'url'}) {
                   9533: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9534:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9535:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9536:     }
1.620     albertel 9537:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9538:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9539:     return &log_query($cname,$cdom,'courselog',%filters);
                   9540: }
                   9541: 
                   9542: sub userlog_query {
1.858     raeburn  9543: #
                   9544: # possible filters:
                   9545: # action: log check role
                   9546: # start: timestamp
                   9547: # end: timestamp
                   9548: #
1.240     www      9549:     my ($uname,$udom,%filters)=@_;
                   9550:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9551: }
                   9552: 
1.506     raeburn  9553: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9554: 
                   9555: sub auto_run {
1.508     raeburn  9556:     my ($cnum,$cdom) = @_;
1.876     raeburn  9557:     my $response = 0;
                   9558:     my $settings;
                   9559:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9560:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9561:         $settings = $domconfig{'autoenroll'};
                   9562:         if ($settings->{'run'} eq '1') {
                   9563:             $response = 1;
                   9564:         }
                   9565:     } else {
1.934     raeburn  9566:         my $homeserver;
                   9567:         if (&is_course($cdom,$cnum)) {
                   9568:             $homeserver = &homeserver($cnum,$cdom);
                   9569:         } else {
                   9570:             $homeserver = &domain($cdom,'primary');
                   9571:         }
                   9572:         if ($homeserver ne 'no_host') {
                   9573:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9574:         }
1.876     raeburn  9575:     }
1.506     raeburn  9576:     return $response;
                   9577: }
1.776     albertel 9578: 
1.506     raeburn  9579: sub auto_get_sections {
1.508     raeburn  9580:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9581:     my $homeserver;
                   9582:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9583:         $homeserver = &homeserver($cnum,$cdom);
                   9584:     }
                   9585:     if (!defined($homeserver)) { 
                   9586:         if ($cdom =~ /^$match_domain$/) {
                   9587:             $homeserver = &domain($cdom,'primary');
                   9588:         }
                   9589:     }
                   9590:     my @secs;
                   9591:     if (defined($homeserver)) {
                   9592:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9593:         unless ($response eq 'refused') {
                   9594:             @secs = split(/:/,$response);
                   9595:         }
1.506     raeburn  9596:     }
                   9597:     return @secs;
                   9598: }
1.776     albertel 9599: 
1.506     raeburn  9600: sub auto_new_course {
1.1099    raeburn  9601:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9602:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9603:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9604:     return $response;
                   9605: }
1.776     albertel 9606: 
1.506     raeburn  9607: sub auto_validate_courseID {
1.508     raeburn  9608:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9609:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9610:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9611:     return $response;
                   9612: }
1.776     albertel 9613: 
1.1007    raeburn  9614: sub auto_validate_instcode {
1.1020    raeburn  9615:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9616:     my ($homeserver,$response);
                   9617:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9618:         $homeserver = &homeserver($cnum,$cdom);
                   9619:     }
                   9620:     if (!defined($homeserver)) {
                   9621:         if ($cdom =~ /^$match_domain$/) {
                   9622:             $homeserver = &domain($cdom,'primary');
                   9623:         }
                   9624:     }
1.1065    raeburn  9625:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9626:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  9627:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9628:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9629: }
                   9630: 
1.1444    raeburn  9631: sub auto_validate_inst_crosslist {
                   9632:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   9633:     my ($homeserver,$response);
                   9634:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9635:         $homeserver = &homeserver($cnum,$cdom);
                   9636:     }
                   9637:     if (!defined($homeserver)) {
                   9638:         if ($cdom =~ /^$match_domain$/) {
                   9639:             $homeserver = &domain($cdom,'primary');
                   9640:         }
                   9641:     }
                   9642:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   9643:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   9644:                          &escape($instcode).':'.&escape($inst_xlist).':'.
1.1445    raeburn  9645:                          &escape($coowner),$homeserver);
1.1444    raeburn  9646:     }
                   9647:     return $response;
                   9648: }
                   9649: 
1.506     raeburn  9650: sub auto_create_password {
1.873     raeburn  9651:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9652:     my ($homeserver,$response);
1.506     raeburn  9653:     my $create_passwd = 0;
                   9654:     my $authchk = '';
1.873     raeburn  9655:     if ($udom =~ /^$match_domain$/) {
                   9656:         $homeserver = &domain($udom,'primary');
                   9657:     }
                   9658:     if ($homeserver eq '') {
                   9659:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9660:             $homeserver = &homeserver($cnum,$cdom);
                   9661:         }
                   9662:     }
                   9663:     if ($homeserver eq '') {
                   9664:         $authchk = 'nodomain';
1.506     raeburn  9665:     } else {
1.873     raeburn  9666:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9667:         if ($response eq 'refused') {
                   9668:             $authchk = 'refused';
                   9669:         } else {
1.901     albertel 9670:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9671:         }
1.506     raeburn  9672:     }
                   9673:     return ($authparam,$create_passwd,$authchk);
                   9674: }
                   9675: 
1.706     raeburn  9676: sub auto_photo_permission {
                   9677:     my ($cnum,$cdom,$students) = @_;
                   9678:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9679:     my ($outcome,$perm_reqd,$conditions) = 
                   9680: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9681:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9682: 	return (undef,undef);
                   9683:     }
1.706     raeburn  9684:     return ($outcome,$perm_reqd,$conditions);
                   9685: }
                   9686: 
                   9687: sub auto_checkphotos {
                   9688:     my ($uname,$udom,$pid) = @_;
                   9689:     my $homeserver = &homeserver($uname,$udom);
                   9690:     my ($result,$resulttype);
                   9691:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9692: 				   &escape($uname).':'.&escape($pid),
                   9693: 				   $homeserver));
1.709     albertel 9694:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9695: 	return (undef,undef);
                   9696:     }
1.706     raeburn  9697:     if ($outcome) {
                   9698:         ($result,$resulttype) = split(/:/,$outcome);
                   9699:     } 
                   9700:     return ($result,$resulttype);
                   9701: }
                   9702: 
                   9703: sub auto_photochoice {
                   9704:     my ($cnum,$cdom) = @_;
                   9705:     my $homeserver = &homeserver($cnum,$cdom);
                   9706:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9707: 						       &escape($cdom),
                   9708: 						       $homeserver)));
1.709     albertel 9709:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9710: 	return (undef,undef);
                   9711:     }
1.706     raeburn  9712:     return ($update,$comment);
                   9713: }
                   9714: 
                   9715: sub auto_photoupdate {
                   9716:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9717:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9718:     my $host=&hostname($homeserver);
1.706     raeburn  9719:     my $cmd = '';
                   9720:     my $maxtries = 1;
1.800     albertel 9721:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9722:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9723:     }
                   9724:     $cmd =~ s/%%$//;
                   9725:     $cmd = &escape($cmd);
                   9726:     my $query = 'institutionalphotos';
                   9727:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9728:     unless ($queryid=~/^\Q$host\E\_/) {
                   9729:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9730:         return 'error: '.$queryid;
                   9731:     }
                   9732:     my $reply = &get_query_reply($queryid);
                   9733:     my $tries = 1;
                   9734:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9735:         $reply = &get_query_reply($queryid);
                   9736:         $tries ++;
                   9737:     }
                   9738:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9739:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9740:     } else {
                   9741:         my @responses = split(/:/,$reply);
                   9742:         my $outcome = shift(@responses); 
                   9743:         foreach my $item (@responses) {
                   9744:             my ($key,$value) = split(/=/,$item);
                   9745:             $$photo{$key} = $value;
                   9746:         }
                   9747:         return $outcome;
                   9748:     }
                   9749:     return 'error';
                   9750: }
                   9751: 
1.521     raeburn  9752: sub auto_instcode_format {
1.793     albertel 9753:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9754: 	$cat_order) = @_;
1.521     raeburn  9755:     my $courses = '';
1.772     raeburn  9756:     my @homeservers;
1.521     raeburn  9757:     if ($caller eq 'global') {
1.841     albertel 9758: 	my %servers = &get_servers($codedom,'library');
                   9759: 	foreach my $tryserver (keys(%servers)) {
                   9760: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9761: 		push(@homeservers,$tryserver);
                   9762: 	    }
1.584     raeburn  9763:         }
1.1022    raeburn  9764:     } elsif ($caller eq 'requests') {
                   9765:         if ($codedom =~ /^$match_domain$/) {
                   9766:             my $chome = &domain($codedom,'primary');
                   9767:             unless ($chome eq 'no_host') {
                   9768:                 push(@homeservers,$chome);
                   9769:             }
                   9770:         }
1.521     raeburn  9771:     } else {
1.772     raeburn  9772:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9773:     }
1.793     albertel 9774:     foreach my $code (keys(%{$instcodes})) {
                   9775:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9776:     }
                   9777:     chop($courses);
1.772     raeburn  9778:     my $ok_response = 0;
                   9779:     my $response;
                   9780:     while (@homeservers > 0 && $ok_response == 0) {
                   9781:         my $server = shift(@homeservers); 
                   9782:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9783:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9784:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9785: 		split(/:/,$response);
1.772     raeburn  9786:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9787:             push(@{$codetitles},&str2array($codetitles_str));
                   9788:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9789:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9790:             $ok_response = 1;
                   9791:         }
                   9792:     }
                   9793:     if ($ok_response) {
1.521     raeburn  9794:         return 'ok';
1.772     raeburn  9795:     } else {
                   9796:         return $response;
1.521     raeburn  9797:     }
                   9798: }
                   9799: 
1.792     raeburn  9800: sub auto_instcode_defaults {
                   9801:     my ($domain,$returnhash,$code_order) = @_;
                   9802:     my @homeservers;
1.841     albertel 9803: 
                   9804:     my %servers = &get_servers($domain,'library');
                   9805:     foreach my $tryserver (keys(%servers)) {
                   9806: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9807: 	    push(@homeservers,$tryserver);
                   9808: 	}
1.792     raeburn  9809:     }
1.841     albertel 9810: 
1.792     raeburn  9811:     my $response;
1.841     albertel 9812:     foreach my $server (@homeservers) {
1.792     raeburn  9813:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9814:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9815: 	
                   9816: 	foreach my $pair (split(/\&/,$response)) {
                   9817: 	    my ($name,$value)=split(/\=/,$pair);
                   9818: 	    if ($name eq 'code_order') {
                   9819: 		@{$code_order} = split(/\&/,&unescape($value));
                   9820: 	    } else {
                   9821: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9822: 	    }
                   9823: 	}
                   9824: 	return 'ok';
1.792     raeburn  9825:     }
1.841     albertel 9826: 
                   9827:     return $response;
1.1003    raeburn  9828: }
                   9829: 
                   9830: sub auto_possible_instcodes {
1.1007    raeburn  9831:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9832:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9833:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9834:         return;
                   9835:     }
1.1003    raeburn  9836:     my (@homeservers,$uhome);
                   9837:     if (defined(&domain($domain,'primary'))) {
                   9838:         $uhome=&domain($domain,'primary');
                   9839:         push(@homeservers,&domain($domain,'primary'));
                   9840:     } else {
                   9841:         my %servers = &get_servers($domain,'library');
                   9842:         foreach my $tryserver (keys(%servers)) {
                   9843:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9844:                 push(@homeservers,$tryserver);
                   9845:             }
                   9846:         }
                   9847:     }
                   9848:     my $response;
                   9849:     foreach my $server (@homeservers) {
                   9850:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9851:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9852:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9853:             split(':',$response);
                   9854:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9855:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9856:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9857:             my ($name,$value)=split('=',$item);
                   9858:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9859:         }
                   9860:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9861:             my ($name,$value)=split('=',$item);
                   9862:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9863:         }
                   9864:         return 'ok';
                   9865:     }
                   9866:     return $response;
                   9867: }
1.792     raeburn  9868: 
1.1010    raeburn  9869: sub auto_courserequest_checks {
                   9870:     my ($dom) = @_;
1.1020    raeburn  9871:     my ($homeserver,%validations);
                   9872:     if ($dom =~ /^$match_domain$/) {
                   9873:         $homeserver = &domain($dom,'primary');
                   9874:     }
                   9875:     unless ($homeserver eq 'no_host') {
                   9876:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9877:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9878:             my @items = split(/&/,$response);
                   9879:             foreach my $item (@items) {
                   9880:                 my ($key,$value) = split('=',$item);
                   9881:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9882:             }
                   9883:         }
                   9884:     }
1.1010    raeburn  9885:     return %validations; 
                   9886: }
                   9887: 
1.1020    raeburn  9888: sub auto_courserequest_validation {
1.1255    raeburn  9889:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9890:     my ($homeserver,$response);
                   9891:     if ($dom =~ /^$match_domain$/) {
                   9892:         $homeserver = &domain($dom,'primary');
                   9893:     }
1.1255    raeburn  9894:     unless ($homeserver eq 'no_host') {
                   9895:         my $customdata;
                   9896:         if (ref($custominfo) eq 'HASH') {
                   9897:             $customdata = &freeze_escape($custominfo);
                   9898:         }
1.1020    raeburn  9899:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9900:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  9901:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9902:                                     $customdata,$homeserver));
1.1020    raeburn  9903:     }
                   9904:     return $response;
                   9905: }
                   9906: 
1.777     albertel 9907: sub auto_validate_class_sec {
1.918     raeburn  9908:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9909:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9910:     my $ownerlist;
                   9911:     if (ref($owners) eq 'ARRAY') {
                   9912:         $ownerlist = join(',',@{$owners});
                   9913:     } else {
                   9914:         $ownerlist = $owners;
                   9915:     }
1.773     raeburn  9916:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9917:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9918:     return $response;
                   9919: }
                   9920: 
1.1460    raeburn  9921: sub auto_instsec_reformat {
                   9922:     my ($cdom,$action,$instsecref) = @_;
                   9923:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   9924:     my @homeservers;
                   9925:     if (defined(&domain($cdom,'primary'))) {
                   9926:         push(@homeservers,&domain($cdom,'primary'));
                   9927:     } else {
                   9928:         my %servers = &get_servers($cdom,'library');
                   9929:         foreach my $tryserver (keys(%servers)) {
                   9930:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9931:                 push(@homeservers,$tryserver);
                   9932:             }
                   9933:         }
                   9934:     }
                   9935:     my $response;
                   9936:     my %reformatted = %{$instsecref};
                   9937:     foreach my $server (@homeservers) {
                   9938:         if (ref($instsecref) eq 'HASH') {
                   9939:             my $info = &freeze_escape($instsecref);
                   9940:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   9941:                                 $action.':'.$info,$server);
                   9942:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   9943:             my @items = split(/&/,$response);
                   9944:             foreach my $item (@items) {
                   9945:                 my ($key,$value) = split(/=/,$item);
                   9946:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   9947:             }
                   9948:         }
                   9949:     }
                   9950:     return %reformatted;
                   9951: }
                   9952: 
1.1367    raeburn  9953: sub auto_validate_instclasses {
                   9954:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9955:     my ($homeserver,%validations);
                   9956:     $homeserver = &homeserver($cnum,$cdom);
                   9957:     unless ($homeserver eq 'no_host') {
                   9958:         my $ownerlist;
                   9959:         if (ref($owners) eq 'ARRAY') {
                   9960:             $ownerlist = join(',',@{$owners});
                   9961:         } else {
                   9962:             $ownerlist = $owners;
                   9963:         }
                   9964:         if (ref($classesref) eq 'HASH') {
                   9965:             my $classes = &freeze_escape($classesref);
                   9966:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9967:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9968:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9969:                 my @items = split(/&/,$response);
                   9970:                 foreach my $item (@items) {
                   9971:                     my ($key,$value) = split('=',$item);
                   9972:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9973:                 }
                   9974:             }
                   9975:         }
                   9976:     }
                   9977:     return %validations;
                   9978: }
                   9979: 
1.1248    raeburn  9980: sub auto_crsreq_update {
                   9981:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  9982:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  9983:     my ($homeserver,%crsreqresponse);
                   9984:     if ($cdom =~ /^$match_domain$/) {
                   9985:         $homeserver = &domain($cdom,'primary');
                   9986:     }
                   9987:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9988:         my $info;
                   9989:         if (ref($inbound) eq 'HASH') {
                   9990:             $info = &freeze_escape($inbound);
                   9991:         }
                   9992:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9993:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9994:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  9995:                             &escape($title).':'.&escape($code).':'.
                   9996:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   9997:                             $homeserver);
1.1248    raeburn  9998:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9999:             my @items = split(/&/,$response);
                   10000:             foreach my $item (@items) {
                   10001:                 my ($key,$value) = split('=',$item);
                   10002:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   10003:             }
                   10004:         }
                   10005:     }
                   10006:     return \%crsreqresponse;
                   10007: }
                   10008: 
1.1305    raeburn  10009: sub auto_export_grades {
1.1309    raeburn  10010:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   10011:     my ($homeserver,%exportresponse);
                   10012:     if ($cdom =~ /^$match_domain$/) {
                   10013:         $homeserver = &domain($cdom,'primary');
                   10014:     }
                   10015:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   10016:         my $info;
                   10017:         if (ref($inforef) eq 'HASH') {
                   10018:             $info = &freeze_escape($inforef);
                   10019:         }
                   10020:         if (ref($gradesref) eq 'HASH') {
                   10021:             my $grades = &freeze_escape($gradesref);
                   10022:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   10023:                                 $info.':'.$grades,$homeserver);
                   10024:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   10025:                 my @items = split(/&/,$response);
                   10026:                 foreach my $item (@items) {
                   10027:                     my ($key,$value) = split('=',$item);
                   10028:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   10029:                 }
                   10030:             }
                   10031:         }
                   10032:     }
                   10033:     return \%exportresponse;
1.1305    raeburn  10034: }
                   10035: 
1.1287    raeburn  10036: sub check_instcode_cloning {
                   10037:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   10038:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   10039:         return;
                   10040:     }
                   10041:     my $canclone;
                   10042:     if (@{$code_order} > 0) {
                   10043:         my $instcoderegexp ='^';
                   10044:         my @clonecodes = split(/\&/,$cloner);
                   10045:         foreach my $item (@{$code_order}) {
                   10046:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   10047:                 foreach my $pair (@clonecodes) {
                   10048:                     my ($key,$val) = split(/\=/,$pair,2);
                   10049:                     $val = &unescape($val);
                   10050:                     if ($key eq $item) {
                   10051:                         $instcoderegexp .= '('.$val.')';
                   10052:                         last;
                   10053:                     }
                   10054:                 }
                   10055:             } else {
                   10056:                 $instcoderegexp .= $codedefaults->{$item};
                   10057:             }
                   10058:         }
                   10059:         $instcoderegexp .= '$';
                   10060:         my (@from,@to);
                   10061:         eval {
                   10062:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10063:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10064:         };
                   10065:         if ((@from > 0) && (@to > 0)) {
                   10066:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10067:             if (!@diffs) {
                   10068:                 $canclone = 1;
                   10069:             }
                   10070:         }
                   10071:     }
                   10072:     return $canclone;
                   10073: }
                   10074: 
                   10075: sub default_instcode_cloning {
                   10076:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   10077:     my (%codedefaults,@code_order,$canclone);
                   10078:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   10079:         %codedefaults = %{$codedefaultsref};
                   10080:         @code_order = @{$codeorderref};
                   10081:     } elsif ($clonedom) {
                   10082:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   10083:     }
                   10084:     if (($domdefclone) && (@code_order)) {
                   10085:         my @clonecodes = split(/\+/,$domdefclone);
                   10086:         my $instcoderegexp ='^';
                   10087:         foreach my $item (@code_order) {
                   10088:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   10089:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   10090:             } else {
                   10091:                 $instcoderegexp .= $codedefaults{$item};
                   10092:             }
                   10093:         }
                   10094:         $instcoderegexp .= '$';
                   10095:         my (@from,@to);
                   10096:         eval {
                   10097:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10098:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10099:         };
                   10100:         if ((@from > 0) && (@to > 0)) {
                   10101:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10102:             if (!@diffs) {
                   10103:                 $canclone = 1;
                   10104:             }
                   10105:         }
                   10106:     }
                   10107:     return $canclone;
                   10108: }
                   10109: 
1.679     raeburn  10110: # ------------------------------------------------------- Course Group routines
                   10111: 
                   10112: sub get_coursegroups {
1.809     raeburn  10113:     my ($cdom,$cnum,$group,$namespace) = @_;
                   10114:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  10115: }
                   10116: 
1.679     raeburn  10117: sub modify_coursegroup {
                   10118:     my ($cdom,$cnum,$groupsettings) = @_;
                   10119:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   10120: }
                   10121: 
1.809     raeburn  10122: sub toggle_coursegroup_status {
                   10123:     my ($cdom,$cnum,$group,$action) = @_;
                   10124:     my ($from_namespace,$to_namespace);
                   10125:     if ($action eq 'delete') {
                   10126:         $from_namespace = 'coursegroups';
                   10127:         $to_namespace = 'deleted_groups';
                   10128:     } else {
                   10129:         $from_namespace = 'deleted_groups';
                   10130:         $to_namespace = 'coursegroups';
                   10131:     }
                   10132:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  10133:     if (my $tmp = &error(%curr_group)) {
                   10134:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   10135:         return ('read error',$tmp);
                   10136:     } else {
                   10137:         my %savedsettings = %curr_group; 
1.809     raeburn  10138:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  10139:         my $deloutcome;
                   10140:         if ($result eq 'ok') {
1.809     raeburn  10141:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  10142:         } else {
                   10143:             return ('write error',$result);
                   10144:         }
                   10145:         if ($deloutcome eq 'ok') {
                   10146:             return 'ok';
                   10147:         } else {
                   10148:             return ('delete error',$deloutcome);
                   10149:         }
                   10150:     }
                   10151: }
                   10152: 
1.679     raeburn  10153: sub modify_group_roles {
1.957     raeburn  10154:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  10155:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   10156:     my $role = 'gr/'.&escape($userprivs);
                   10157:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  10158:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  10159:     if ($result eq 'ok') {
                   10160:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   10161:     }
1.679     raeburn  10162:     return $result;
                   10163: }
                   10164: 
                   10165: sub modify_coursegroup_membership {
                   10166:     my ($cdom,$cnum,$membership) = @_;
                   10167:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   10168:     return $result;
                   10169: }
                   10170: 
1.682     raeburn  10171: sub get_active_groups {
                   10172:     my ($udom,$uname,$cdom,$cnum) = @_;
                   10173:     my $now = time;
                   10174:     my %groups = ();
                   10175:     foreach my $key (keys(%env)) {
1.811     albertel 10176:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  10177:             my ($start,$end) = split(/\./,$env{$key});
                   10178:             if (($end!=0) && ($end<$now)) { next; }
                   10179:             if (($start!=0) && ($start>$now)) { next; }
                   10180:             if ($1 eq $cdom && $2 eq $cnum) {
                   10181:                 $groups{$3} = $env{$key} ;
                   10182:             }
                   10183:         }
                   10184:     }
                   10185:     return %groups;
                   10186: }
                   10187: 
1.683     raeburn  10188: sub get_group_membership {
                   10189:     my ($cdom,$cnum,$group) = @_;
                   10190:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   10191: }
                   10192: 
                   10193: sub get_users_groups {
                   10194:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  10195:     my @usersgroups;
1.683     raeburn  10196:     my $cachetime=1800;
                   10197: 
                   10198:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  10199:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   10200:     if (defined($cached)) {
1.734     albertel 10201:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  10202:     } else {  
                   10203:         $grouplist = '';
1.816     raeburn  10204:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  10205:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  10206:         my $access_end = $env{'course.'.$courseid.
                   10207:                               '.default_enrollment_end_date'};
                   10208:         my $now = time;
                   10209:         foreach my $key (keys(%roleshash)) {
                   10210:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   10211:                 my $group = $1;
                   10212:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   10213:                     my $start = $2;
                   10214:                     my $end = $1;
                   10215:                     if ($start == -1) { next; } # deleted from group
                   10216:                     if (($start!=0) && ($start>$now)) { next; }
                   10217:                     if (($end!=0) && ($end<$now)) {
                   10218:                         if ($access_end && $access_end < $now) {
                   10219:                             if ($access_end - $end < 86400) {
                   10220:                                 push(@usersgroups,$group);
1.733     raeburn  10221:                             }
                   10222:                         }
1.817     raeburn  10223:                         next;
1.733     raeburn  10224:                     }
1.817     raeburn  10225:                     push(@usersgroups,$group);
1.683     raeburn  10226:                 }
                   10227:             }
                   10228:         }
1.817     raeburn  10229:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   10230:         $grouplist = join(':',@usersgroups);
                   10231:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  10232:     }
1.733     raeburn  10233:     return @usersgroups;
1.683     raeburn  10234: }
                   10235: 
                   10236: sub devalidate_getgroups_cache {
                   10237:     my ($udom,$uname,$cdom,$cnum)=@_;
                   10238:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 10239: 
1.683     raeburn  10240:     my $hashid="$udom:$uname:$courseid";
                   10241:     &devalidate_cache_new('getgroups',$hashid);
                   10242: }
                   10243: 
1.12      www      10244: # ------------------------------------------------------------------ Plain Text
                   10245: 
                   10246: sub plaintext {
1.988     raeburn  10247:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  10248:     if ($short =~ m{^cr/}) {
1.758     albertel 10249: 	return (split('/',$short))[-1];
                   10250:     }
1.742     raeburn  10251:     if (!defined($cid)) {
                   10252:         $cid = $env{'request.course.id'};
                   10253:     }
                   10254:     my %rolenames = (
1.1008    raeburn  10255:                       Course    => 'std',
                   10256:                       Community => 'alt1',
1.1305    raeburn  10257:                       Placement => 'std',
1.742     raeburn  10258:                     );
1.1037    raeburn  10259:     if ($cid ne '') {
                   10260:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   10261:             unless ($forcedefault) {
                   10262:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   10263:                 &Apache::lonlocal::mt_escape(\$roletext);
                   10264:                 return &Apache::lonlocal::mt($roletext);
                   10265:             }
                   10266:         }
                   10267:     }
                   10268:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   10269:         (defined($rolenames{$type})) && 
                   10270:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  10271:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  10272:     } elsif ($cid ne '') {
                   10273:         my $crstype = $env{'course.'.$cid.'.type'};
                   10274:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   10275:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   10276:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   10277:         }
1.742     raeburn  10278:     }
1.1037    raeburn  10279:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      10280: }
                   10281: 
                   10282: # ----------------------------------------------------------------- Assign Role
                   10283: 
                   10284: sub assignrole {
1.957     raeburn  10285:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   10286:         $context)=@_;
1.21      www      10287:     my $mrole;
                   10288:     if ($role =~ /^cr\//) {
1.393     www      10289:         my $cwosec=$url;
1.811     albertel 10290:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      10291: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  10292:            my $refused = 1;
                   10293:            if ($context eq 'requestcourses') {
                   10294:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   10295:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   10296:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   10297:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10298:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10299:                            if ($crsenv{'internal.courseowner'} eq
                   10300:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   10301:                                $refused = '';
                   10302:                            }
                   10303:                        }
                   10304:                    }
                   10305:                }
                   10306:            }
                   10307:            if ($refused) {
                   10308:                &logthis('Refused custom assignrole: '.
                   10309:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   10310:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   10311:                return 'refused';
                   10312:            }
1.104     www      10313:         }
1.21      www      10314:         $mrole='cr';
1.678     raeburn  10315:     } elsif ($role =~ /^gr\//) {
                   10316:         my $cwogrp=$url;
1.811     albertel 10317:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  10318:         unless (&allowed('mdg',$cwogrp)) {
                   10319:             &logthis('Refused group assignrole: '.
                   10320:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   10321:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   10322:             return 'refused';
                   10323:         }
                   10324:         $mrole='gr';
1.21      www      10325:     } else {
1.82      www      10326:         my $cwosec=$url;
1.811     albertel 10327:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  10328:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   10329:             my $refused;
                   10330:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   10331:                 if (!(&allowed('c'.$role,$url))) {
                   10332:                     $refused = 1;
                   10333:                 }
                   10334:             } else {
                   10335:                 $refused = 1;
                   10336:             }
1.947     raeburn  10337:             if ($refused) {
1.1045    raeburn  10338:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377    raeburn  10339:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  10340:                     my %crsenv;
                   10341:                     if ($role eq 'cc' || $role eq 'co') {
                   10342:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10343:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   10344:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   10345:                                 if ($crsenv{'internal.courseowner'} eq 
                   10346:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10347:                                     $refused = '';
                   10348:                                 }
                   10349:                             }
                   10350:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   10351:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   10352:                                 if ($crsenv{'internal.courseowner'} eq 
                   10353:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10354:                                     $refused = '';
                   10355:                                 }
                   10356:                             }
                   10357:                         }
                   10358:                     }
1.1368    raeburn  10359:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   10360:                     if ($role eq 'st') {
                   10361:                         $refused = '';
1.1377    raeburn  10362:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  10363:                         $refused = '';
                   10364:                     }
1.1017    raeburn  10365:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10366:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10367:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10368:                         my $wrongcc;
                   10369:                         if ($cnum =~ /^$match_community$/) {
                   10370:                             $wrongcc = 1 if ($role eq 'cc');
                   10371:                         } else {
                   10372:                             $wrongcc = 1 if ($role eq 'co');
                   10373:                         }
                   10374:                         unless ($wrongcc) {
                   10375:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10376:                             if ($crsenv{'internal.courseowner'} eq 
                   10377:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10378:                                 $refused = '';
                   10379:                             }
1.1017    raeburn  10380:                         }
                   10381:                     }
1.1183    raeburn  10382:                 } elsif ($context eq 'requestauthor') {
                   10383:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   10384:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10385:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10386:                             $refused = '';
                   10387:                         } else {
                   10388:                             my %domdefaults = &get_domain_defaults($udom);
                   10389:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10390:                                 my $checkbystatus;
                   10391:                                 if ($env{'user.adv'}) { 
                   10392:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10393:                                     if ($disposition eq 'automatic') {
                   10394:                                         $refused = '';
                   10395:                                     } elsif ($disposition eq '') {
                   10396:                                         $checkbystatus = 1;
                   10397:                                     } 
                   10398:                                 } else {
                   10399:                                     $checkbystatus = 1;
                   10400:                                 }
                   10401:                                 if ($checkbystatus) {
                   10402:                                     if ($env{'environment.inststatus'}) {
                   10403:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10404:                                         foreach my $type (@inststatuses) {
                   10405:                                             if (($type ne '') &&
                   10406:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10407:                                                 $refused = '';
                   10408:                                             }
                   10409:                                         }
                   10410:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10411:                                         $refused = '';
                   10412:                                     }
                   10413:                                 }
                   10414:                             }
                   10415:                         }
                   10416:                     }
1.1017    raeburn  10417:                 }
                   10418:                 if ($refused) {
1.947     raeburn  10419:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10420:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10421: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10422:                     return 'refused';
                   10423:                 }
1.932     raeburn  10424:             }
1.1131    raeburn  10425:         } elsif ($role eq 'au') {
                   10426:             if ($url ne '/'.$udom.'/') {
                   10427:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10428:                          ' to assign author role for '.$uname.':'.$udom.
                   10429:                          ' in domain: '.$url.' refused (wrong domain).');
                   10430:                 return 'refused';
                   10431:             }
1.104     www      10432:         }
1.21      www      10433:         $mrole=$role;
                   10434:     }
1.620     albertel 10435:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10436:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10437:     if ($end) { $command.='_'.$end; }
1.21      www      10438:     if ($start) {
                   10439: 	if ($end) { 
1.81      www      10440:            $command.='_'.$start; 
1.21      www      10441:         } else {
1.81      www      10442:            $command.='_0_'.$start;
1.21      www      10443:         }
                   10444:     }
1.739     raeburn  10445:     my $origstart = $start;
                   10446:     my $origend = $end;
1.957     raeburn  10447:     my $delflag;
1.357     www      10448: # actually delete
                   10449:     if ($deleteflag) {
1.373     www      10450: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10451: # modify command to delete the role
1.620     albertel 10452:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10453:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10454: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10455: # set start and finish to negative values for userrolelog
                   10456:            $start=-1;
                   10457:            $end=-1;
1.957     raeburn  10458:            $delflag = 1;
1.357     www      10459:         }
                   10460:     }
                   10461: # send command
1.349     www      10462:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      10463: # log new user role if status is ok
1.349     www      10464:     if ($answer eq 'ok') {
1.663     raeburn  10465: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  10466:         if (($role eq 'cc') || ($role eq 'in') ||
                   10467:             ($role eq 'ep') || ($role eq 'ad') ||
                   10468:             ($role eq 'ta') || ($role eq 'st') ||
                   10469:             ($role=~/^cr/) || ($role eq 'gr') ||
                   10470:             ($role eq 'co')) {
1.1200    raeburn  10471: # for course roles, perform group memberships changes triggered by role change.
                   10472:             unless ($role =~ /^gr/) {
                   10473:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10474:                                                  $origstart,$selfenroll,$context);
                   10475:             }
1.1184    raeburn  10476:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10477:                            $selfenroll,$context);
                   10478:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  10479:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10480:                  ($role eq 'da')) {
1.1184    raeburn  10481:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10482:                            $context);
                   10483:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10484:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10485:                              $context); 
                   10486:         }
1.1053    raeburn  10487:         if ($role eq 'cc') {
                   10488:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10489:         }
1.349     www      10490:     }
                   10491:     return $answer;
1.169     harris41 10492: }
                   10493: 
1.1053    raeburn  10494: sub autoupdate_coowners {
                   10495:     my ($url,$end,$start,$uname,$udom) = @_;
                   10496:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10497:     if (($cdom ne '') && ($cnum ne '')) {
                   10498:         my $now = time;
                   10499:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10500:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10501:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10502:             my $instcode = $coursehash{'internal.coursecode'};
1.1444    raeburn  10503:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  10504:             if ($instcode ne '') {
1.1056    raeburn  10505:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10506:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10507:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10508:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1444    raeburn  10509:                         unless ($result eq 'valid') {
                   10510:                             if ($xlists ne '') {
                   10511:                                 foreach my $xlist (split(',',$xlists)) {
                   10512:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   10513:                                     $result =
1.1446    raeburn  10514:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   10515:                                                                       $inst_crosslist,$uname.':'.$udom);
                   10516:                                     last if ($result eq 'valid');
1.1444    raeburn  10517:                                 }
                   10518:                             }
                   10519:                         }
1.1056    raeburn  10520:                         if ($result eq 'valid') {
                   10521:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10522:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10523:                                     push(@newcoowners,$coowner);
                   10524:                                 }
                   10525:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10526:                                     push(@newcoowners,$uname.':'.$udom);
                   10527:                                 }
                   10528:                                 @newcoowners = sort(@newcoowners);
                   10529:                             } else {
                   10530:                                 push(@newcoowners,$uname.':'.$udom);
                   10531:                             }
1.1444    raeburn  10532:                         } elsif ($coursehash{'internal.co-owners'}) {
                   10533:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10534:                                 unless ($coowner eq $uname.':'.$udom) {
                   10535:                                     push(@newcoowners,$coowner);
1.1053    raeburn  10536:                                 }
1.1444    raeburn  10537:                             }
                   10538:                             unless (@newcoowners > 0) {
                   10539:                                 $delcoowners = 1;
                   10540:                                 $coowners = '';
1.1053    raeburn  10541:                             }
                   10542:                         }
                   10543:                         if (@newcoowners || $delcoowners) {
                   10544:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10545:                                             $delcoowners,@newcoowners);
                   10546:                         }
                   10547:                     }
                   10548:                 }
                   10549:             }
                   10550:         }
                   10551:     }
                   10552: }
                   10553: 
                   10554: sub store_coowners {
                   10555:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10556:     my $cid = $cdom.'_'.$cnum;
                   10557:     my ($coowners,$delresult,$putresult);
                   10558:     if (@newcoowners) {
                   10559:         $coowners = join(',',@newcoowners);
                   10560:         my %coownershash = (
                   10561:                             'internal.co-owners' => $coowners,
                   10562:                            );
                   10563:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10564:         if ($putresult eq 'ok') {
                   10565:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10566:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10567:             }
                   10568:         }
                   10569:     }
                   10570:     if ($delcoowners) {
                   10571:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10572:         if ($delresult eq 'ok') {
                   10573:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10574:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10575:             }
                   10576:         }
                   10577:     }
                   10578:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10579:         my %crsinfo =
                   10580:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10581:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10582:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10583:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10584:         }
                   10585:     }
                   10586: }
                   10587: 
1.169     harris41 10588: # -------------------------------------------------- Modify user authentication
1.197     www      10589: # Overrides without validation
                   10590: 
1.169     harris41 10591: sub modifyuserauth {
                   10592:     my ($udom,$uname,$umode,$upass)=@_;
                   10593:     my $uhome=&homeserver($uname,$udom);
1.1409    raeburn  10594:     my $allowed;
                   10595:     if (&allowed('mau',$udom)) {
                   10596:         $allowed = 1;
                   10597:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10598:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10599:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10600:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10601:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10602:         if (($cdom ne '') && ($cnum ne '')) {
                   10603:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10604:             if ($is_owner) {
                   10605:                 $allowed = 1;
                   10606:             }
                   10607:         }
                   10608:     }
                   10609:     unless ($allowed) { return 'refused'; }
1.197     www      10610:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10611:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10612:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10613:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10614: 		     &escape($upass),$uhome);
1.1434    raeburn  10615:     my $ip = &get_requestor_ip();
1.620     albertel 10616:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10617:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1434    raeburn  10618:          '(Remote '.$ip.'): '.$reply);
1.197     www      10619:     &log($udom,,$uname,$uhome,
1.620     albertel 10620:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10621:                                      $env{'user.name'}.', '.$umode.
1.1435    raeburn  10622:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10623:     unless ($reply eq 'ok') {
1.197     www      10624:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10625: 	return 'error: '.$reply;
                   10626:     }   
1.170     harris41 10627:     return 'ok';
1.80      www      10628: }
                   10629: 
1.81      www      10630: # --------------------------------------------------------------- Modify a user
1.80      www      10631: 
1.81      www      10632: sub modifyuser {
1.206     matthew  10633:     my ($udom,    $uname, $uid,
                   10634:         $umode,   $upass, $first,
                   10635:         $middle,  $last,  $gene,
1.1058    raeburn  10636:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10637:     $udom= &LONCAPA::clean_domain($udom);
                   10638:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10639:     my $showcandelete = 'none';
                   10640:     if (ref($candelete) eq 'ARRAY') {
                   10641:         if (@{$candelete} > 0) {
                   10642:             $showcandelete = join(', ',@{$candelete});
                   10643:         }
                   10644:     }
1.81      www      10645:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10646:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10647: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10648:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10649:                                      ' desiredhome not specified'). 
1.620     albertel 10650:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10651:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10652:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10653:     my $newuser;
                   10654:     if ($uhome eq 'no_host') {
                   10655:         $newuser = 1;
1.1368    raeburn  10656:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   10657:                 ($umode eq 'lti')) {
                   10658:             return 'error: more information needed to create new user';
                   10659:         }
1.1075    raeburn  10660:     }
1.80      www      10661: # ----------------------------------------------------------------- Create User
1.406     albertel 10662:     if (($uhome eq 'no_host') && 
1.1368    raeburn  10663: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      10664:         my $unhome='';
1.844     albertel 10665:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10666:             $unhome = $desiredhome;
1.620     albertel 10667: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10668: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10669:         } else { # load balancing routine for determining $unhome
1.81      www      10670:             my $loadm=10000000;
1.841     albertel 10671: 	    my %servers = &get_servers($udom,'library');
                   10672: 	    foreach my $tryserver (keys(%servers)) {
                   10673: 		my $answer=reply('load',$tryserver);
                   10674: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10675: 		    $loadm=$answer;
                   10676: 		    $unhome=$tryserver;
                   10677: 		}
1.80      www      10678: 	    }
                   10679:         }
                   10680:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10681: 	    return 'error: unable to find a home server for '.$uname.
                   10682:                    ' in domain '.$udom;
1.80      www      10683:         }
                   10684:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10685:                          &escape($upass),$unhome);
                   10686: 	unless ($reply eq 'ok') {
                   10687:             return 'error: '.$reply;
                   10688:         }   
1.230     stredwic 10689:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10690:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10691: 	    return 'error: unable verify users home machine.';
1.80      www      10692:         }
1.209     matthew  10693:     }   # End of creation of new user
1.80      www      10694: # ---------------------------------------------------------------------- Add ID
                   10695:     if ($uid) {
                   10696:        $uid=~tr/A-Z/a-z/;
                   10697:        my %uidhash=&idrget($udom,$uname);
1.196     www      10698:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10699:          && (!$forceid)) {
1.80      www      10700: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10701: 	      return 'error: user id "'.$uid.'" does not match '.
                   10702:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10703:           }
                   10704:        } else {
1.1300    raeburn  10705: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      10706:        }
                   10707:     }
                   10708: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10709:     my @tmp=&get('environment',
1.899     raeburn  10710: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10711:                     'permanentemail','inststatus'],
1.134     albertel 10712: 		   $udom,$uname);
1.1075    raeburn  10713:     my (%names,%oldnames);
1.313     matthew  10714:     if ($tmp[0] =~ m/^error:.*/) { 
                   10715:         %names=(); 
                   10716:     } else {
                   10717:         %names = @tmp;
1.1075    raeburn  10718:         %oldnames = %names;
1.313     matthew  10719:     }
1.388     www      10720: #
1.1058    raeburn  10721: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10722: # of users did not contain them), do not overwrite existing values
                   10723: # unless field is in $candelete array ref.  
                   10724: #
                   10725: 
                   10726:     my @fields = ('firstname','middlename','lastname','generation',
                   10727:                   'permanentemail','id');
                   10728:     my %newvalues;
                   10729:     if (ref($candelete) eq 'ARRAY') {
                   10730:         foreach my $field (@fields) {
                   10731:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10732:                 if ($field eq 'firstname') {
                   10733:                     $names{$field} = $first;
                   10734:                 } elsif ($field eq 'middlename') {
                   10735:                     $names{$field} = $middle;
                   10736:                 } elsif ($field eq 'lastname') {
                   10737:                     $names{$field} = $last;
                   10738:                 } elsif ($field eq 'generation') { 
                   10739:                     $names{$field} = $gene;
                   10740:                 } elsif ($field eq 'permanentemail') {
                   10741:                     $names{$field} = $email;
                   10742:                 } elsif ($field eq 'id') {
                   10743:                     $names{$field}  = $uid;
                   10744:                 }
                   10745:             }
                   10746:         }
                   10747:     }
1.388     www      10748:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10749:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10750:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10751:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10752:     if ($email) {
                   10753:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10754:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10755:     }
1.899     raeburn  10756:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10757:     if (defined($inststatus)) {
                   10758:         $names{'inststatus'} = '';
                   10759:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10760:         if (ref($usertypes) eq 'HASH') {
                   10761:             my @okstatuses; 
                   10762:             foreach my $item (split(/:/,$inststatus)) {
                   10763:                 if (defined($usertypes->{$item})) {
                   10764:                     push(@okstatuses,$item);  
                   10765:                 }
                   10766:             }
                   10767:             if (@okstatuses) {
                   10768:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10769:             }
                   10770:         }
                   10771:     }
1.1075    raeburn  10772:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10773:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10774:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10775:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10776:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10777:     } else {
                   10778:         $logmsg .= ' during self creation';
                   10779:     }
1.1075    raeburn  10780:     my $changed;
                   10781:     if ($newuser) {
                   10782:         $changed = 1;
                   10783:     } else {
                   10784:         foreach my $field (@fields) {
                   10785:             if ($names{$field} ne $oldnames{$field}) {
                   10786:                 $changed = 1;
                   10787:                 last;
                   10788:             }
                   10789:         }
                   10790:     }
                   10791:     unless ($changed) {
                   10792:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10793:         &logthis($logmsg);
                   10794:         return 'ok';
                   10795:     }
                   10796:     my $reply = &put('environment', \%names, $udom,$uname);
                   10797:     if ($reply ne 'ok') { 
                   10798:         return 'error: '.$reply;
                   10799:     }
1.1087    raeburn  10800:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10801:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10802:     }
1.1075    raeburn  10803:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10804:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10805:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10806:     &logthis($logmsg);
1.134     albertel 10807:     return 'ok';
1.80      www      10808: }
                   10809: 
1.81      www      10810: # -------------------------------------------------------------- Modify student
1.80      www      10811: 
1.81      www      10812: sub modifystudent {
                   10813:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10814:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  10815:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10816:     if (!$cid) {
1.620     albertel 10817: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10818: 	    return 'not_in_class';
                   10819: 	}
1.80      www      10820:     }
                   10821: # --------------------------------------------------------------- Make the user
1.81      www      10822:     my $reply=&modifyuser
1.209     matthew  10823: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10824:          $desiredhome,$email,$inststatus);
1.80      www      10825:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10826:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  10827:     # student's environment
1.297     matthew  10828:     $uid = undef if (!$forceid);
1.455     albertel 10829:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  10830:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  10831:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10832:     return $reply;
                   10833: }
                   10834: 
                   10835: sub modify_student_enrollment {
1.1216    raeburn  10836:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  10837:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10838:     my ($cdom,$cnum,$chome);
                   10839:     if (!$cid) {
1.620     albertel 10840: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10841: 	    return 'not_in_class';
                   10842: 	}
1.620     albertel 10843: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10844: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10845:     } else {
                   10846: 	($cdom,$cnum)=split(/_/,$cid);
                   10847:     }
1.620     albertel 10848:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10849:     if (!$chome) {
1.457     raeburn  10850: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10851:     }
1.455     albertel 10852:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10853:     # Make sure the user exists
1.81      www      10854:     my $uhome=&homeserver($uname,$udom);
                   10855:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10856: 	return 'error: no such user';
                   10857:     }
1.297     matthew  10858:     # Get student data if we were not given enough information
                   10859:     if (!defined($first)  || $first  eq '' || 
                   10860:         !defined($last)   || $last   eq '' || 
                   10861:         !defined($uid)    || $uid    eq '' || 
                   10862:         !defined($middle) || $middle eq '' || 
                   10863:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10864:         # They did not supply us with enough data to enroll the student, so
                   10865:         # we need to pick up more information.
1.297     matthew  10866:         my %tmp = &get('environment',
1.294     matthew  10867:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10868:                        ,$udom,$uname);
                   10869: 
1.800     albertel 10870:         #foreach my $key (keys(%tmp)) {
                   10871:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10872:         #}
1.294     matthew  10873:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10874:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10875:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10876:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10877:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10878:     }
1.556     albertel 10879:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10880:     my $user = "$uname:$udom";
                   10881:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10882:     my $reply=cput('classlist',
1.1148    raeburn  10883: 		   {$user => 
1.1314    raeburn  10884: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10885: 		   $cdom,$cnum);
1.1148    raeburn  10886:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10887:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10888:     } else { 
1.81      www      10889: 	return 'error: '.$reply;
                   10890:     }
1.297     matthew  10891:     # Add student role to user
1.83      www      10892:     my $uurl='/'.$cid;
1.81      www      10893:     $uurl=~s/\_/\//g;
                   10894:     if ($usec) {
                   10895: 	$uurl.='/'.$usec;
                   10896:     }
1.1148    raeburn  10897:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10898:                              $selfenroll,$context);
                   10899:     if ($result ne 'ok') {
                   10900:         if ($old_entry{$user} ne '') {
                   10901:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10902:         } else {
                   10903:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10904:         }
                   10905:     }
                   10906:     return $result; 
1.21      www      10907: }
                   10908: 
1.556     albertel 10909: sub format_name {
                   10910:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10911:     my $name;
                   10912:     if ($first ne 'lastname') {
                   10913: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10914:     } else {
                   10915: 	if ($lastname=~/\S/) {
                   10916: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10917: 	    $name=~s/\s+,/,/;
                   10918: 	} else {
                   10919: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10920: 	}
                   10921:     }
                   10922:     $name=~s/^\s+//;
                   10923:     $name=~s/\s+$//;
                   10924:     $name=~s/\s+/ /g;
                   10925:     return $name;
                   10926: }
                   10927: 
1.84      www      10928: # ------------------------------------------------- Write to course preferences
                   10929: 
                   10930: sub writecoursepref {
                   10931:     my ($courseid,%prefs)=@_;
                   10932:     $courseid=~s/^\///;
                   10933:     $courseid=~s/\_/\//g;
                   10934:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10935:     my $chome=homeserver($cnum,$cdomain);
                   10936:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10937: 	return 'error: no such course';
                   10938:     }
                   10939:     my $cstring='';
1.800     albertel 10940:     foreach my $pref (keys(%prefs)) {
                   10941: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10942:     }
1.84      www      10943:     $cstring=~s/\&$//;
                   10944:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10945: }
                   10946: 
                   10947: # ---------------------------------------------------------- Make/modify course
                   10948: 
                   10949: sub createcourse {
1.741     raeburn  10950:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1423    raeburn  10951:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10952:     $url=&declutter($url);
                   10953:     my $cid='';
1.1028    raeburn  10954:     if ($context eq 'requestcourses') {
                   10955:         my $can_create = 0;
                   10956:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10957:         if ($udom eq $ownerdom) {
1.1423    raeburn  10958:             my $reload;
                   10959:             if (($callercontext eq 'auto') &&
                   10960:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10961:                 $reload = 'reload';
                   10962:             }
                   10963:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10964:                                   $context)) {
                   10965:                 $can_create = 1;
                   10966:             }
                   10967:         } else {
                   10968:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10969:                                            $category);
                   10970:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10971:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10972:                 if (@curr > 0) {
                   10973:                     my @options = qw(approval validate autolimit);
                   10974:                     my $optregex = join('|',@options);
                   10975:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10976:                         $can_create = 1;
                   10977:                     }
                   10978:                 }
                   10979:             }
                   10980:         }
                   10981:         if ($can_create) {
                   10982:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10983:                 unless (&allowed('ccc',$udom)) {
                   10984:                     return 'refused'; 
                   10985:                 }
1.1017    raeburn  10986:             }
                   10987:         } else {
                   10988:             return 'refused';
                   10989:         }
1.1028    raeburn  10990:     } elsif (!&allowed('ccc',$udom)) {
                   10991:         return 'refused';
1.84      www      10992:     }
1.1011    raeburn  10993: # --------------------------------------------------------------- Get Unique ID
                   10994:     my $uname;
                   10995:     if ($cnum =~ /^$match_courseid$/) {
                   10996:         my $chome=&homeserver($cnum,$udom,'true');
                   10997:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10998:             $uname = $cnum;
                   10999:         } else {
1.1038    raeburn  11000:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  11001:         }
                   11002:     } else {
1.1038    raeburn  11003:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  11004:     }
                   11005:     return $uname if ($uname =~ /^error/);
                   11006: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  11007:     if (!defined($course_server)) {
                   11008:         if (defined(&domain($udom,'primary'))) {
                   11009:             $course_server = &domain($udom,'primary');
                   11010:         } else {
                   11011:             $course_server = $env{'user.home'}; 
                   11012:         }
                   11013:     }
                   11014:     my %host_servers =
                   11015:         &Apache::lonnet::get_servers($udom,'library');
                   11016:     unless ($host_servers{$course_server}) {
                   11017:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  11018:     }
1.84      www      11019: # ------------------------------------------------------------- Make the course
                   11020:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  11021:                       $course_server);
1.84      www      11022:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  11023:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      11024:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   11025: 	return 'error: no such course';
                   11026:     }
1.271     www      11027: # ----------------------------------------------------------------- Course made
1.516     raeburn  11028: # log existence
1.1029    raeburn  11029:     my $now = time;
1.918     raeburn  11030:     my $newcourse = {
                   11031:                     $udom.'_'.$uname => {
1.921     raeburn  11032:                                      description => $description,
                   11033:                                      inst_code   => $inst_code,
                   11034:                                      owner       => $course_owner,
                   11035:                                      type        => $crstype,
1.1029    raeburn  11036:                                      creator     => $env{'user.name'}.':'.
                   11037:                                                     $env{'user.domain'},
                   11038:                                      created     => $now,
                   11039:                                      context     => $context,
1.918     raeburn  11040:                                                 },
                   11041:                     };
1.921     raeburn  11042:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      11043: # set toplevel url
1.271     www      11044:     my $topurl=$url;
                   11045:     unless ($nonstandard) {
                   11046: # ------------------------------------------ For standard courses, make top url
                   11047:         my $mapurl=&clutter($url);
1.278     www      11048:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 11049:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      11050: <map>
                   11051: <resource id="1" type="start"></resource>
                   11052: <resource id="2" src="$mapurl"></resource>
                   11053: <resource id="3" type="finish"></resource>
                   11054: <link index="1" from="1" to="2"></link>
                   11055: <link index="2" from="2" to="3"></link>
                   11056: </map>
                   11057: ENDINITMAP
                   11058:         $topurl=&declutter(
1.638     albertel 11059:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      11060:                           );
                   11061:     }
                   11062: # ----------------------------------------------------------- Write preferences
1.84      www      11063:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  11064:                      ('description'              => $description,
                   11065:                       'url'                      => $topurl,
                   11066:                       'internal.creator'         => $env{'user.name'}.':'.
                   11067:                                                     $env{'user.domain'},
                   11068:                       'internal.created'         => $now,
                   11069:                       'internal.creationcontext' => $context)
                   11070:                     );
1.84      www      11071:     return '/'.$udom.'/'.$uname;
                   11072: }
                   11073: 
1.1011    raeburn  11074: # ------------------------------------------------------------------- Create ID
                   11075: sub generate_coursenum {
1.1038    raeburn  11076:     my ($udom,$crstype) = @_;
1.1011    raeburn  11077:     my $domdesc = &domain($udom);
                   11078:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  11079:     my $first;
                   11080:     if ($crstype eq 'Community') {
                   11081:         $first = '0';
                   11082:     } else {
                   11083:         $first = int(1+rand(9)); 
                   11084:     } 
                   11085:     my $uname=$first.
1.1011    raeburn  11086:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11087:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11088:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11089: # ----------------------------------------------- Make sure that does not exist
                   11090:     my $uhome=&homeserver($uname,$udom,'true');
                   11091:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  11092:         if ($crstype eq 'Community') {
                   11093:             $first = '0';
                   11094:         } else {
                   11095:             $first = int(1+rand(9));
                   11096:         }
                   11097:         $uname=$first.
1.1011    raeburn  11098:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11099:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11100:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11101:         $uhome=&homeserver($uname,$udom,'true');
                   11102:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   11103:             return 'error: unable to generate unique course-ID';
                   11104:         }
                   11105:     }
                   11106:     return $uname;
                   11107: }
                   11108: 
1.813     albertel 11109: sub is_course {
1.1167    droeschl 11110:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   11111:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   11112: 
1.1381    raeburn  11113:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   11114:     my $uhome=&homeserver($cnum,$cdom);
                   11115:     my $iscourse;
                   11116:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  11117:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  11118:     } else {
                   11119:         my $hashid = $cdom.':'.$cnum;
                   11120:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   11121:         unless (defined($cached)) {
                   11122:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   11123:                                         $cnum,undef,undef,'.');
                   11124:             $iscourse = 0;
                   11125:             if (exists($courses{$cdom.'_'.$cnum})) {
                   11126:                 $iscourse = 1;
                   11127:             }
                   11128:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   11129:         }
                   11130:     }
                   11131:     return unless ($iscourse);
1.1167    droeschl 11132:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 11133: }
                   11134: 
1.1015    raeburn  11135: sub store_userdata {
                   11136:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  11137:     my $result;
1.1016    raeburn  11138:     if ($datakey ne '') {
1.1013    raeburn  11139:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  11140:             if ($udom eq '' || $uname eq '') {
                   11141:                 $udom = $env{'user.domain'};
                   11142:                 $uname = $env{'user.name'};
                   11143:             }
                   11144:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  11145:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   11146:                 $result = 'error: no_host';
                   11147:             } else {
1.1434    raeburn  11148:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  11149:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   11150: 
                   11151:                 my $namevalue='';
                   11152:                 foreach my $key (keys(%{$storehash})) {
                   11153:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   11154:                 }
                   11155:                 $namevalue=~s/\&$//;
1.1224    raeburn  11156:                 unless ($namespace eq 'courserequests') {
                   11157:                     $datakey = &escape($datakey);
                   11158:                 }
1.1105    raeburn  11159:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   11160:                                   $namevalue,$uhome);
1.1013    raeburn  11161:             }
                   11162:         } else {
                   11163:             $result = 'error: data to store was not a hash reference'; 
                   11164:         }
                   11165:     } else {
                   11166:         $result= 'error: invalid requestkey'; 
                   11167:     }
                   11168:     return $result;
                   11169: }
                   11170: 
1.21      www      11171: # ---------------------------------------------------------- Assign Custom Role
                   11172: 
                   11173: sub assigncustomrole {
1.957     raeburn  11174:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11175:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  11176:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      11177: }
                   11178: 
                   11179: # ----------------------------------------------------------------- Revoke Role
                   11180: 
                   11181: sub revokerole {
1.957     raeburn  11182:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11183:     my $now=time;
1.965     raeburn  11184:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      11185: }
                   11186: 
                   11187: # ---------------------------------------------------------- Revoke Custom Role
                   11188: 
                   11189: sub revokecustomrole {
1.957     raeburn  11190:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11191:     my $now=time;
1.357     www      11192:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  11193:            $deleteflag,$selfenroll,$context);
1.17      www      11194: }
                   11195: 
1.533     banghart 11196: # ------------------------------------------------------------ Disk usage
1.535     albertel 11197: sub diskusage {
1.955     raeburn  11198:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   11199:     $directorypath =~ s/\/$//;
                   11200:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   11201:                        .&escape($getpropath).':'.&escape($uname).':'
                   11202:                        .&escape($udom),homeserver($uname,$udom));
                   11203:     if ($listing eq 'unknown_cmd') {
                   11204:         if ($getpropath) {
                   11205:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   11206:         }
                   11207:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   11208:     }
1.514     albertel 11209:     return $listing;
1.512     banghart 11210: }
                   11211: 
1.566     banghart 11212: sub is_locked {
1.1096    raeburn  11213:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 11214:     my @check;
                   11215:     my $is_locked;
1.1093    raeburn  11216:     push (@check,$file_name);
1.613     albertel 11217:     my %locked = &get('file_permissions',\@check,
1.620     albertel 11218: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 11219:     my ($tmp)=keys(%locked);
                   11220:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  11221:     
1.566     banghart 11222:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  11223:         $is_locked = 'false';
                   11224:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  11225:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  11226:                $is_locked = 'true';
1.1096    raeburn  11227:                if (ref($which) eq 'ARRAY') {
                   11228:                    push(@{$which},$entry);
                   11229:                } else {
                   11230:                    last;
                   11231:                }
1.745     raeburn  11232:            }
                   11233:        }
1.566     banghart 11234:     } else {
                   11235:         $is_locked = 'false';
                   11236:     }
1.1093    raeburn  11237:     return $is_locked;
1.566     banghart 11238: }
                   11239: 
1.759     albertel 11240: sub declutter_portfile {
                   11241:     my ($file) = @_;
1.833     albertel 11242:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 11243:     return $file;
                   11244: }
                   11245: 
1.559     banghart 11246: # ------------------------------------------------------------- Mark as Read Only
                   11247: 
                   11248: sub mark_as_readonly {
                   11249:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 11250:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11251:     my ($tmp)=keys(%current_permissions);
                   11252:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 11253:     foreach my $file (@{$files}) {
1.759     albertel 11254: 	$file = &declutter_portfile($file);
1.561     banghart 11255:         push(@{$current_permissions{$file}},$what);
1.559     banghart 11256:     }
1.613     albertel 11257:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11258:     return;
                   11259: }
                   11260: 
1.572     banghart 11261: # ------------------------------------------------------------Save Selected Files
                   11262: 
                   11263: sub save_selected_files {
                   11264:     my ($user, $path, @files) = @_;
                   11265:     my $filename = $user."savedfiles";
1.573     banghart 11266:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  11267:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 11268:     foreach my $file (@files) {
1.620     albertel 11269:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 11270:     }
                   11271:     foreach my $file (@other_files) {
1.574     banghart 11272:         print (OUT $file."\n");
1.572     banghart 11273:     }
1.574     banghart 11274:     close (OUT);
1.572     banghart 11275:     return 'ok';
                   11276: }
                   11277: 
1.574     banghart 11278: sub clear_selected_files {
                   11279:     my ($user) = @_;
                   11280:     my $filename = $user."savedfiles";
1.1359    raeburn  11281:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 11282:     print (OUT undef);
                   11283:     close (OUT);
                   11284:     return ("ok");    
                   11285: }
                   11286: 
1.572     banghart 11287: sub files_in_path {
                   11288:     my ($user, $path) = @_;
                   11289:     my $filename = $user."savedfiles";
                   11290:     my %return_files;
1.1359    raeburn  11291:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 11292:     while (my $line_in = <IN>) {
1.574     banghart 11293:         chomp ($line_in);
                   11294:         my @paths_and_file = split (m!/!, $line_in);
                   11295:         my $file_part = pop (@paths_and_file);
                   11296:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 11297:         $path_part.='/';
                   11298:         my $path_and_file = $path_part.$file_part;
                   11299:         if ($path_part eq $path) {
                   11300:             $return_files{$file_part}= 'selected';
                   11301:         }
                   11302:     }
1.574     banghart 11303:     close (IN);
                   11304:     return (\%return_files);
1.572     banghart 11305: }
                   11306: 
                   11307: # called in portfolio select mode, to show files selected NOT in current directory
                   11308: sub files_not_in_path {
                   11309:     my ($user, $path) = @_;
                   11310:     my $filename = $user."savedfiles";
                   11311:     my @return_files;
                   11312:     my $path_part;
1.1359    raeburn  11313:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 11314:     while (my $line = <IN>) {
1.572     banghart 11315:         #ok, I know it's clunky, but I want it to work
1.800     albertel 11316:         my @paths_and_file = split(m|/|, $line);
                   11317:         my $file_part = pop(@paths_and_file);
                   11318:         chomp($file_part);
                   11319:         my $path_part = join('/', @paths_and_file);
1.572     banghart 11320:         $path_part .= '/';
                   11321:         my $path_and_file = $path_part.$file_part;
                   11322:         if ($path_part ne $path) {
1.800     albertel 11323:             push(@return_files, ($path_and_file));
1.572     banghart 11324:         }
                   11325:     }
1.800     albertel 11326:     close(OUT);
1.574     banghart 11327:     return (@return_files);
1.572     banghart 11328: }
                   11329: 
1.1273    raeburn  11330: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   11331:  
                   11332: sub portfiles_versioning {
                   11333:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   11334:     my $portfolio_root = '/userfiles/portfolio';
                   11335:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   11336:     foreach my $file (@{$portfiles}) {
                   11337:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   11338:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   11339:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   11340:         my $getpropath = 1;
                   11341:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   11342:                                              $stu_name,$getpropath);
                   11343:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   11344:         my $new_answer = 
                   11345:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   11346:         if ($new_answer ne 'problem getting file') {
                   11347:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   11348:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   11349:                               [$symb,$env{'request.course.id'},'graded']);
                   11350:         }
                   11351:     }
                   11352: }
                   11353: 
                   11354: sub get_next_version {
                   11355:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   11356:     my $version;
                   11357:     if (ref($dir_list) eq 'ARRAY') {
                   11358:         foreach my $row (@{$dir_list}) {
                   11359:             my ($file) = split(/\&/,$row,2);
                   11360:             my ($file_name,$file_version,$file_ext) =
                   11361:                 &file_name_version_ext($file);
                   11362:             if (($file_name eq $answer_name) &&
                   11363:                 ($file_ext eq $answer_ext)) {
                   11364:                      # gets here if filename and extension match,
                   11365:                      # regardless of version
                   11366:                 if ($file_version ne '') {
                   11367:                     # a versioned file is found  so save it for later
                   11368:                     if ($file_version > $version) {
                   11369:                         $version = $file_version;
                   11370:                     }
                   11371:                 }
                   11372:             }
                   11373:         }
                   11374:     }
                   11375:     $version ++;
                   11376:     return($version);
                   11377: }
                   11378: 
                   11379: sub version_selected_portfile {
                   11380:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   11381:     my ($answer_name,$answer_ver,$answer_ext) =
                   11382:         &file_name_version_ext($file_name);
                   11383:     my $new_answer;
                   11384:     $env{'form.copy'} =
                   11385:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   11386:     if($env{'form.copy'} eq '-1') {
                   11387:         $new_answer = 'problem getting file';
                   11388:     } else {
                   11389:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   11390:         my $copy_result = 
                   11391:             &finishuserfileupload($stu_name,$domain,'copy',
                   11392:                                   '/portfolio'.$directory.$new_answer);
                   11393:     }
                   11394:     undef($env{'form.copy'});
                   11395:     return ($new_answer);
                   11396: }
                   11397: 
                   11398: sub file_name_version_ext {
                   11399:     my ($file)=@_;
                   11400:     my @file_parts = split(/\./, $file);
                   11401:     my ($name,$version,$ext);
                   11402:     if (@file_parts > 1) {
                   11403:         $ext=pop(@file_parts);
                   11404:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   11405:             $version=pop(@file_parts);
                   11406:         }
                   11407:         $name=join('.',@file_parts);
                   11408:     } else {
                   11409:         $name=join('.',@file_parts);
                   11410:     }
                   11411:     return($name,$version,$ext);
                   11412: }
                   11413: 
1.745     raeburn  11414: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11415: 
1.745     raeburn  11416: sub get_portfile_permissions {
                   11417:     my ($domain,$user) = @_;
1.613     albertel 11418:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11419:     my ($tmp)=keys(%current_permissions);
                   11420:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11421:     return \%current_permissions;
                   11422: }
                   11423: 
                   11424: #---------------------------------------------Get portfolio file access controls
                   11425: 
1.749     raeburn  11426: sub get_access_controls {
1.745     raeburn  11427:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11428:     my %access;
                   11429:     my $real_file = $file;
                   11430:     $file =~ s/\.meta$//;
1.745     raeburn  11431:     if (defined($file)) {
1.749     raeburn  11432:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11433:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11434:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11435:             }
                   11436:         }
1.745     raeburn  11437:     } else {
1.749     raeburn  11438:         foreach my $key (keys(%{$current_permissions})) {
                   11439:             if ($key =~ /\0accesscontrol$/) {
                   11440:                 if (defined($group)) {
                   11441:                     if ($key !~ m-^\Q$group\E/-) {
                   11442:                         next;
                   11443:                     }
                   11444:                 }
                   11445:                 my ($fullpath) = split(/\0/,$key);
                   11446:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11447:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11448:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11449:                     }
                   11450:                 }
                   11451:             }
                   11452:         }
                   11453:     }
                   11454:     return %access;
                   11455: }
                   11456: 
                   11457: sub modify_access_controls {
                   11458:     my ($file_name,$changes,$domain,$user)=@_;
                   11459:     my ($outcome,$deloutcome);
                   11460:     my %store_permissions;
                   11461:     my %new_values;
                   11462:     my %new_control;
                   11463:     my %translation;
                   11464:     my @deletions = ();
                   11465:     my $now = time;
                   11466:     if (exists($$changes{'activate'})) {
                   11467:         if (ref($$changes{'activate'}) eq 'HASH') {
                   11468:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   11469:             my $numnew = scalar(@newitems);
                   11470:             for (my $i=0; $i<$numnew; $i++) {
                   11471:                 my $newkey = $newitems[$i];
                   11472:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  11473:                 if ($newkey =~ /^\d+:/) { 
                   11474:                     $newkey =~ s/^(\d+)/$newid/;
                   11475:                     $translation{$1} = $newid;
                   11476:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   11477:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   11478:                     $translation{$1} = $newid;
                   11479:                 }
1.749     raeburn  11480:                 $new_values{$file_name."\0".$newkey} = 
                   11481:                                           $$changes{'activate'}{$newitems[$i]};
                   11482:                 $new_control{$newkey} = $now;
                   11483:             }
                   11484:         }
                   11485:     }
                   11486:     my %todelete;
                   11487:     my %changed_items;
                   11488:     foreach my $action ('delete','update') {
                   11489:         if (exists($$changes{$action})) {
                   11490:             if (ref($$changes{$action}) eq 'HASH') {
                   11491:                 foreach my $key (keys(%{$$changes{$action}})) {
                   11492:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   11493:                     if ($action eq 'delete') { 
                   11494:                         $todelete{$itemnum} = 1;
                   11495:                     } else {
                   11496:                         $changed_items{$itemnum} = $key;
                   11497:                     }
                   11498:                 }
1.745     raeburn  11499:             }
                   11500:         }
1.749     raeburn  11501:     }
                   11502:     # get lock on access controls for file.
                   11503:     my $lockhash = {
                   11504:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   11505:                                                        ':'.$env{'user.domain'},
                   11506:                    }; 
                   11507:     my $tries = 0;
                   11508:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11509:    
1.1288    damieng  11510:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  11511:         $tries ++;
1.1289    damieng  11512:         sleep(0.1);
1.749     raeburn  11513:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11514:     }
                   11515:     if ($gotlock eq 'ok') {
                   11516:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   11517:         my ($tmp)=keys(%curr_permissions);
                   11518:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   11519:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   11520:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   11521:             if (ref($curr_controls) eq 'HASH') {
                   11522:                 foreach my $control_item (keys(%{$curr_controls})) {
                   11523:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   11524:                     if (defined($todelete{$itemnum})) {
                   11525:                         push(@deletions,$file_name."\0".$control_item);
                   11526:                     } else {
                   11527:                         if (defined($changed_items{$itemnum})) {
                   11528:                             $new_control{$changed_items{$itemnum}} = $now;
                   11529:                             push(@deletions,$file_name."\0".$control_item);
                   11530:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   11531:                         } else {
                   11532:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   11533:                         }
                   11534:                     }
1.745     raeburn  11535:                 }
                   11536:             }
                   11537:         }
1.970     raeburn  11538:         my ($group);
                   11539:         if (&is_course($domain,$user)) {
                   11540:             ($group,my $file) = split(/\//,$file_name,2);
                   11541:         }
1.749     raeburn  11542:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   11543:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   11544:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   11545:         #  remove lock
                   11546:         my @del_lock = ($file_name."\0".'locked_access_records');
                   11547:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  11548:         my $sqlresult =
1.970     raeburn  11549:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  11550:                                     $group);
1.749     raeburn  11551:     } else {
                   11552:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  11553:     }
1.749     raeburn  11554:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  11555: }
                   11556: 
1.827     raeburn  11557: sub make_public_indefinitely {
1.1271    raeburn  11558:     my (@requrl) = @_;
                   11559:     return &automated_portfile_access('public',\@requrl);
                   11560: }
                   11561: 
                   11562: sub automated_portfile_access {
                   11563:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  11564:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   11565:         return 'invalid';
                   11566:     }
1.1271    raeburn  11567:     my %urls;
                   11568:     if (ref($addsref) eq 'ARRAY') {
                   11569:         foreach my $requrl (@{$addsref}) {
                   11570:             if (&is_portfolio_url($requrl)) {
                   11571:                 unless (exists($urls{$requrl})) {
                   11572:                     $urls{$requrl} = 'add';
                   11573:                 }
                   11574:             }
                   11575:         }
                   11576:     }
                   11577:     if (ref($delsref) eq 'ARRAY') {
                   11578:         foreach my $requrl (@{$delsref}) { 
                   11579:             if (&is_portfolio_url($requrl)) {
                   11580:                 unless (exists($urls{$requrl})) {
                   11581:                     $urls{$requrl} = 'delete'; 
                   11582:                 }
                   11583:             }
                   11584:         }
                   11585:     }
                   11586:     unless (keys(%urls)) {
                   11587:         return 'invalid';
                   11588:     }
                   11589:     my $ip;
                   11590:     if ($accesstype eq 'ip') {
                   11591:         if (ref($info) eq 'HASH') {
                   11592:             if ($info->{'ip'} ne '') {
                   11593:                 $ip = $info->{'ip'};
                   11594:             }
                   11595:         }
                   11596:         if ($ip eq '') {
                   11597:             return 'invalid';
                   11598:         }
                   11599:     }
                   11600:     my $errors;
1.827     raeburn  11601:     my $now = time;
1.1271    raeburn  11602:     my %current_perms;
                   11603:     foreach my $requrl (sort(keys(%urls))) {
                   11604:         my $action;
                   11605:         if ($urls{$requrl} eq 'add') {
                   11606:             $action = 'activate';
                   11607:         } else {
                   11608:             $action = 'none';
                   11609:         }
                   11610:         my $aclnum = 0;
1.827     raeburn  11611:         my (undef,$udom,$unum,$file_name,$group) =
                   11612:             &parse_portfolio_url($requrl);
1.1271    raeburn  11613:         unless (exists($current_perms{$unum.':'.$udom})) {
                   11614:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   11615:         }
                   11616:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  11617:                                                    $group,$file_name);
                   11618:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11619:             my ($num,$scope,$end,$start) = 
                   11620:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  11621:             if ($scope eq $accesstype) {
                   11622:                 if (($start <= $now) && ($end == 0)) {
                   11623:                     if ($accesstype eq 'ip') {
                   11624:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   11625:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   11626:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   11627:                                     if ($urls{$requrl} eq 'add') {
                   11628:                                         $action = 'none';
                   11629:                                         last;
                   11630:                                     } else {
                   11631:                                         $action = 'delete';
                   11632:                                         $aclnum = $num;
                   11633:                                         last;
                   11634:                                     }
                   11635:                                 }
                   11636:                             }
                   11637:                         }
                   11638:                     } elsif ($accesstype eq 'public') {
                   11639:                         if ($urls{$requrl} eq 'add') {
                   11640:                             $action = 'none';
                   11641:                             last;
                   11642:                         } else {
                   11643:                             $action = 'delete';
                   11644:                             $aclnum = $num;
                   11645:                             last;
                   11646:                         }
                   11647:                     }
                   11648:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  11649:                     $action = 'update';
                   11650:                     $aclnum = $num;
1.1271    raeburn  11651:                     last;
1.827     raeburn  11652:                 }
                   11653:             }
                   11654:         }
                   11655:         if ($action eq 'none') {
1.1271    raeburn  11656:             next;
1.827     raeburn  11657:         } else {
                   11658:             my %changes;
                   11659:             my $newend = 0;
                   11660:             my $newstart = $now;
1.1271    raeburn  11661:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  11662:             $changes{$action}{$newkey} = {
1.1271    raeburn  11663:                 type => $accesstype,
1.827     raeburn  11664:                 time => {
                   11665:                     start => $newstart,
                   11666:                     end   => $newend,
                   11667:                 },
                   11668:             };
1.1271    raeburn  11669:             if ($accesstype eq 'ip') {
                   11670:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   11671:             }
1.827     raeburn  11672:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11673:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  11674:             unless ($outcome eq 'ok') {
                   11675:                 $errors .= $outcome.' ';
                   11676:             }
1.827     raeburn  11677:         }
1.1271    raeburn  11678:     }
                   11679:     if ($errors) {
                   11680:         $errors =~ s/\s$//;
                   11681:         return $errors;
1.827     raeburn  11682:     } else {
1.1271    raeburn  11683:         return 'ok';
1.827     raeburn  11684:     }
                   11685: }
                   11686: 
1.745     raeburn  11687: #------------------------------------------------------Get Marked as Read Only
                   11688: 
                   11689: sub get_marked_as_readonly {
                   11690:     my ($domain,$user,$what,$group) = @_;
                   11691:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11692:     my @readonly_files;
1.629     banghart 11693:     my $cmp1=$what;
                   11694:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11695:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11696:         if (defined($group)) {
                   11697:             if ($file_name !~ m-^\Q$group\E/-) {
                   11698:                 next;
                   11699:             }
                   11700:         }
1.561     banghart 11701:         if (ref($value) eq "ARRAY"){
                   11702:             foreach my $stored_what (@{$value}) {
1.629     banghart 11703:                 my $cmp2=$stored_what;
1.759     albertel 11704:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11705:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11706:                 }
1.629     banghart 11707:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11708:                     push(@readonly_files, $file_name);
1.745     raeburn  11709:                     last;
1.563     banghart 11710:                 } elsif (!defined($what)) {
                   11711:                     push(@readonly_files, $file_name);
1.745     raeburn  11712:                     last;
1.561     banghart 11713:                 }
                   11714:             }
1.745     raeburn  11715:         }
1.561     banghart 11716:     }
                   11717:     return @readonly_files;
                   11718: }
1.577     banghart 11719: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11720: 
1.577     banghart 11721: sub get_marked_as_readonly_hash {
1.745     raeburn  11722:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11723:     my %readonly_files;
1.745     raeburn  11724:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11725:         if (defined($group)) {
                   11726:             if ($file_name !~ m-^\Q$group\E/-) {
                   11727:                 next;
                   11728:             }
                   11729:         }
1.577     banghart 11730:         if (ref($value) eq "ARRAY"){
                   11731:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11732:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11733:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11734:                         if ($lock_descriptor eq 'graded') {
                   11735:                             $readonly_files{$file_name} = 'graded';
                   11736:                         } elsif ($lock_descriptor eq 'handback') {
                   11737:                             $readonly_files{$file_name} = 'handback';
                   11738:                         } else {
                   11739:                             if (!exists($readonly_files{$file_name})) {
                   11740:                                 $readonly_files{$file_name} = 'locked';
                   11741:                             }
                   11742:                         }
1.745     raeburn  11743:                     }
1.750     banghart 11744:                 } 
1.577     banghart 11745:             }
                   11746:         } 
                   11747:     }
                   11748:     return %readonly_files;
                   11749: }
1.559     banghart 11750: # ------------------------------------------------------------ Unmark as Read Only
                   11751: 
                   11752: sub unmark_as_readonly {
1.629     banghart 11753:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11754:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11755:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11756:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11757:     my $symb_crs = $what;
                   11758:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11759:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11760:     my ($tmp)=keys(%current_permissions);
                   11761:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11762:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11763:     foreach my $file (@readonly_files) {
1.759     albertel 11764: 	my $clean_file = &declutter_portfile($file);
                   11765: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11766: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11767:         my @new_locks;
                   11768:         my @del_keys;
                   11769:         if (ref($current_locks) eq "ARRAY"){
                   11770:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11771:                 my $compare=$locker;
1.749     raeburn  11772:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11773:                     $compare=join('',@{$locker});
1.746     raeburn  11774:                     if ($compare ne $symb_crs) {
                   11775:                         push(@new_locks, $locker);
                   11776:                     }
1.563     banghart 11777:                 }
                   11778:             }
1.650     albertel 11779:             if (scalar(@new_locks) > 0) {
1.563     banghart 11780:                 $current_permissions{$file} = \@new_locks;
                   11781:             } else {
                   11782:                 push(@del_keys, $file);
1.613     albertel 11783:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11784:                 delete($current_permissions{$file});
1.563     banghart 11785:             }
                   11786:         }
1.561     banghart 11787:     }
1.613     albertel 11788:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11789:     return;
                   11790: }
1.512     banghart 11791: 
1.17      www      11792: # ------------------------------------------------------------ Directory lister
                   11793: 
                   11794: sub dirlist {
1.955     raeburn  11795:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11796:     $uri=~s/^\///;
                   11797:     $uri=~s/\/$//;
1.253     stredwic 11798:     my ($udom, $uname);
1.955     raeburn  11799:     if ($getuserdir) {
1.253     stredwic 11800:         $udom = $userdomain;
                   11801:         $uname = $username;
1.955     raeburn  11802:     } else {
                   11803:         (undef,$udom,$uname)=split(/\//,$uri);
                   11804:         if(defined($userdomain)) {
                   11805:             $udom = $userdomain;
                   11806:         }
                   11807:         if(defined($username)) {
                   11808:             $uname = $username;
                   11809:         }
1.253     stredwic 11810:     }
1.955     raeburn  11811:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11812: 
1.955     raeburn  11813:     $dirRoot = $perlvar{'lonDocRoot'};
                   11814:     if (defined($getpropath)) {
                   11815:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11816:         $dirRoot =~ s/\/$//;
1.955     raeburn  11817:     } elsif (defined($getuserdir)) {
                   11818:         my $subdir=$uname.'__';
                   11819:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11820:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11821:                    ."/$udom/$subdir/$uname";
                   11822:     } elsif (defined($alternateRoot)) {
                   11823:         $dirRoot = $alternateRoot;
1.751     banghart 11824:     }
1.253     stredwic 11825: 
                   11826:     if($udom) {
                   11827:         if($uname) {
1.1135    raeburn  11828:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11829:             if ($uhome eq 'no_host') {
                   11830:                 return ([],'no_host');
                   11831:             }
1.955     raeburn  11832:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11833:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11834:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11835:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11836:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11837:             } else {
                   11838:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11839:             }
1.605     matthew  11840:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11841:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11842:                 @listing_results = split(/:/,$listing);
                   11843:             } else {
                   11844:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11845:             }
1.1135    raeburn  11846:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11847:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11848:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11849:                 return ([],$listing);
                   11850:             } else {
                   11851:                 return (\@listing_results);
1.1135    raeburn  11852:             }
1.955     raeburn  11853:         } elsif(!$alternateRoot) {
1.1136    raeburn  11854:             my (%allusers,%listerror);
1.841     albertel 11855: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11856:  	    foreach my $tryserver (keys(%servers)) {
                   11857:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11858:                                   &escape($udom),$tryserver);
                   11859:                 if ($listing eq 'unknown_cmd') {
                   11860: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11861: 				      $udom, $tryserver);
                   11862:                 } else {
                   11863:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11864:                 }
1.841     albertel 11865: 		if ($listing eq 'unknown_cmd') {
                   11866: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11867: 				      $udom, $tryserver);
                   11868: 		    @listing_results = split(/:/,$listing);
                   11869: 		} else {
                   11870: 		    @listing_results =
                   11871: 			map { &unescape($_); } split(/:/,$listing);
                   11872: 		}
1.1136    raeburn  11873:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11874:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11875:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11876:                     $listerror{$tryserver} = $listing;
                   11877:                 } else {
1.841     albertel 11878: 		    foreach my $line (@listing_results) {
                   11879: 			my ($entry) = split(/&/,$line,2);
                   11880: 			$allusers{$entry} = 1;
                   11881: 		    }
                   11882: 		}
1.253     stredwic 11883:             }
1.1136    raeburn  11884:             my @alluserslist=();
1.800     albertel 11885:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11886:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11887:             }
1.1318    droeschl 11888: 
                   11889:             if (!%listerror) {
                   11890:                 # no errors
                   11891:                 return (\@alluserslist);
                   11892:             } elsif (scalar(keys(%servers)) == 1) {
                   11893:                 # one library server, one error 
                   11894:                 my ($key) = keys(%listerror);
                   11895:                 return (\@alluserslist, $listerror{$key});
                   11896:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11897:                 # con_lost indicates that we might miss data from at least one
                   11898:                 # library server
                   11899:                 return (\@alluserslist, 'con_lost');
                   11900:             } else {
                   11901:                 # multiple library servers and no con_lost -> data should be
                   11902:                 # complete. 
                   11903:                 return (\@alluserslist);
                   11904:             }
                   11905: 
1.253     stredwic 11906:         } else {
1.1136    raeburn  11907:             return ([],'missing username');
1.253     stredwic 11908:         }
1.955     raeburn  11909:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11910:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11911:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11912:         return (\@all_domains);
1.955     raeburn  11913:     } else {
1.1136    raeburn  11914:         return ([],'missing domain');
1.275     stredwic 11915:     }
                   11916: }
                   11917: 
                   11918: # --------------------------------------------- GetFileTimestamp
                   11919: # This function utilizes dirlist and returns the date stamp for
                   11920: # when it was last modified.  It will also return an error of -1
                   11921: # if an error occurs
                   11922: 
                   11923: sub GetFileTimestamp {
1.955     raeburn  11924:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11925:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11926:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11927:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11928:                                     undef,$getuserdir);
                   11929:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11930:         return -1;
                   11931:     }
                   11932:     if (ref($fileref) eq 'ARRAY') {
                   11933:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11934:         # @stats contains first the filename, then the stat output
                   11935:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11936:     } else {
                   11937:         return -1;
1.253     stredwic 11938:     }
1.26      www      11939: }
                   11940: 
1.712     albertel 11941: sub stat_file {
                   11942:     my ($uri) = @_;
1.787     albertel 11943:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11944: 
1.955     raeburn  11945:     my ($udom,$uname,$file);
1.712     albertel 11946:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11947: 	($udom,$uname,$file) =
1.811     albertel 11948: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11949: 	$file = 'userfiles/'.$file;
                   11950:     }
                   11951:     if ($uri =~ m-^/res/-) {
                   11952: 	($udom,$uname) = 
1.807     albertel 11953: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11954: 	$file = $uri;
                   11955:     }
                   11956: 
                   11957:     if (!$udom || !$uname || !$file) {
                   11958: 	# unable to handle the uri
                   11959: 	return ();
                   11960:     }
1.956     raeburn  11961:     my $getpropath;
                   11962:     if ($file =~ /^userfiles\//) {
                   11963:         $getpropath = 1;
                   11964:     }
1.1136    raeburn  11965:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11966:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11967:         return ();
                   11968:     } else {
                   11969:         if (ref($listref) eq 'ARRAY') {
                   11970:             my @stats = split('&',$listref->[0]);
                   11971: 	    shift(@stats); #filename is first
                   11972: 	    return @stats;
                   11973:         }
1.712     albertel 11974:     }
                   11975:     return ();
                   11976: }
                   11977: 
1.1313    raeburn  11978: # --------------------------------------------------------- recursedirs
                   11979: # Recursive function to traverse either a specific user's Authoring Space
                   11980: # or corresponding Published Resource Space, and populate the hash ref:
                   11981: # $dirhashref with URLs of all directories, and if $filehashref hash
                   11982: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   11983: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   11984: # files in Authoring Space.
                   11985: #
                   11986: # Inputs:
                   11987: #
                   11988: # $is_home - true if current server is home server for user's space
                   11989: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   11990: # $docroot - Document root (i.e., /home/httpd/html
                   11991: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   11992: # $relpath - Current path (relative to top level).
                   11993: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   11994: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   11995: #
                   11996: # Returns: nothing
                   11997: #
                   11998: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   11999: #
                   12000: # Currently used by interface/londocs.pm to create linked select boxes for
                   12001: # directory and filename to import a Course "Author" resource into a course, and
                   12002: # also to create linked select boxes for Authoring Space and Directory to choose
                   12003: # save location for creation of a new "standard" problem from the Course Editor.
                   12004: #
                   12005: 
                   12006: sub recursedirs {
                   12007:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   12008:     return unless (ref($dirhashref) eq 'HASH');
                   12009:     my $currpath = $docroot.$toppath;
                   12010:     if ($relpath) {
                   12011:         $currpath .= "/$relpath";
                   12012:     }
                   12013:     my $savefile;
                   12014:     if (ref($filehashref)) {
                   12015:         $savefile = 1;
                   12016:     }
                   12017:     if ($is_home) {
                   12018:         if (opendir(my $dirh,$currpath)) {
                   12019:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   12020:                 next if ($item eq '');
                   12021:                 if (-d "$currpath/$item") {
                   12022:                     my $newpath;
                   12023:                     if ($relpath) {
                   12024:                         $newpath = "$relpath/$item";
                   12025:                     } else {
                   12026:                         $newpath = $item;
                   12027:                     }
                   12028:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   12029:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   12030:                 } elsif ($savefile) {
                   12031:                     if ($context eq 'priv') {
                   12032:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   12033:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   12034:                         }
                   12035:                     } else {
                   12036:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   12037:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   12038:                         }
                   12039:                     }
                   12040:                 }
                   12041:             }
                   12042:             closedir($dirh);
                   12043:         }
                   12044:     } else {
                   12045:         my ($dirlistref,$listerror) =
                   12046:             &dirlist($toppath.$relpath);
                   12047:         my @dir_lines;
                   12048:         my $dirptr=16384;
                   12049:         if (ref($dirlistref) eq 'ARRAY') {
                   12050:             foreach my $dir_line (sort
                   12051:                               {
                   12052:                                   my ($afile)=split('&',$a,2);
                   12053:                                   my ($bfile)=split('&',$b,2);
                   12054:                                   return (lc($afile) cmp lc($bfile));
                   12055:                               } (@{$dirlistref})) {
                   12056:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   12057:                     split(/\&/,$dir_line,16);
                   12058:                 $item =~ s/\s+$//;
                   12059:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   12060:                 if ($dirptr&$testdir) {
                   12061:                     my $newpath;
                   12062:                     if ($relpath) {
                   12063:                         $newpath = "$relpath/$item";
                   12064:                     } else {
                   12065:                         $relpath = '/';
                   12066:                         $newpath = $item;
                   12067:                     }
                   12068:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   12069:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   12070:                 } elsif ($savefile) {
                   12071:                     if ($context eq 'priv') {
                   12072:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   12073:                             $filehashref->{$relpath}{$item} = 1;
                   12074:                         }
                   12075:                     } else {
                   12076:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   12077:                             $filehashref->{$relpath}{$item} = 1;
                   12078:                         }
                   12079:                     }
                   12080:                 }
                   12081:             }
                   12082:         }
                   12083:     }
                   12084:     return;
                   12085: }
                   12086: 
1.26      www      12087: # -------------------------------------------------------- Value of a Condition
                   12088: 
1.713     albertel 12089: # gets the value of a specific preevaluated condition
                   12090: #    stored in the string  $env{user.state.<cid>}
                   12091: # or looks up a condition reference in the bighash and if if hasn't
                   12092: # already been evaluated recurses into docondval to get the value of
                   12093: # the condition, then memoizing it to 
                   12094: #   $env{user.state.<cid>.<condition>}
1.40      www      12095: sub directcondval {
                   12096:     my $number=shift;
1.620     albertel 12097:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 12098: 	&Apache::lonuserstate::evalstate();
                   12099:     }
1.713     albertel 12100:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   12101: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   12102:     } elsif ($number =~ /^_/) {
                   12103: 	my $sub_condition;
                   12104: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12105: 		&GDBM_READER(),0640)) {
                   12106: 	    $sub_condition=$bighash{'conditions'.$number};
                   12107: 	    untie(%bighash);
                   12108: 	}
                   12109: 	my $value = &docondval($sub_condition);
1.949     raeburn  12110: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 12111: 	return $value;
                   12112:     }
1.620     albertel 12113:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   12114:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      12115:     } else {
                   12116:        return 2;
                   12117:     }
                   12118: }
                   12119: 
1.713     albertel 12120: # get the collection of conditions for this resource
1.26      www      12121: sub condval {
                   12122:     my $condidx=shift;
1.54      www      12123:     my $allpathcond='';
1.713     albertel 12124:     foreach my $cond (split(/\|/,$condidx)) {
                   12125: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   12126: 	    $allpathcond.=
                   12127: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   12128: 	}
1.191     harris41 12129:     }
1.54      www      12130:     $allpathcond=~s/\|$//;
1.713     albertel 12131:     return &docondval($allpathcond);
                   12132: }
                   12133: 
                   12134: #evaluates an expression of conditions
                   12135: sub docondval {
                   12136:     my ($allpathcond) = @_;
                   12137:     my $result=0;
                   12138:     if ($env{'request.course.id'}
                   12139: 	&& defined($allpathcond)) {
                   12140: 	my $operand='|';
                   12141: 	my @stack;
                   12142: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   12143: 	    if ($chunk eq '(') {
                   12144: 		push @stack,($operand,$result);
                   12145: 	    } elsif ($chunk eq ')') {
                   12146: 		my $before=pop @stack;
                   12147: 		if (pop @stack eq '&') {
                   12148: 		    $result=$result>$before?$before:$result;
                   12149: 		} else {
                   12150: 		    $result=$result>$before?$result:$before;
                   12151: 		}
                   12152: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   12153: 		$operand=$chunk;
                   12154: 	    } else {
                   12155: 		my $new=directcondval($chunk);
                   12156: 		if ($operand eq '&') {
                   12157: 		    $result=$result>$new?$new:$result;
                   12158: 		} else {
                   12159: 		    $result=$result>$new?$result:$new;
                   12160: 		}
                   12161: 	    }
                   12162: 	}
1.26      www      12163:     }
                   12164:     return $result;
1.421     albertel 12165: }
                   12166: 
                   12167: # ---------------------------------------------------- Devalidate courseresdata
                   12168: 
                   12169: sub devalidatecourseresdata {
                   12170:     my ($coursenum,$coursedomain)=@_;
                   12171:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 12172:     &devalidate_cache_new('courseres',$hashid);
1.28      www      12173: }
                   12174: 
1.763     www      12175: 
1.200     www      12176: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     12177: #
                   12178: #  Parameters:
                   12179: #      $coursenum    - Number of the course.
                   12180: #      $coursedomain - Domain at which the course was created.
                   12181: #  Returns:
                   12182: #     A hash of the course parameters along (I think) with timestamps
                   12183: #     and version info.
1.877     foxr     12184: 
1.624     albertel 12185: sub get_courseresdata {
                   12186:     my ($coursenum,$coursedomain)=@_;
1.200     www      12187:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   12188:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 12189:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 12190:     my %dumpreply;
1.417     albertel 12191:     unless (defined($cached)) {
1.624     albertel 12192: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 12193: 	$result=\%dumpreply;
1.251     albertel 12194: 	my ($tmp) = keys(%dumpreply);
                   12195: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 12196: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 12197: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   12198: 	    return $tmp;
1.416     albertel 12199: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 12200: 	    $result=undef;
1.599     albertel 12201: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 12202: 	}
                   12203:     }
1.624     albertel 12204:     return $result;
                   12205: }
                   12206: 
1.633     albertel 12207: sub devalidateuserresdata {
                   12208:     my ($uname,$udom)=@_;
                   12209:     my $hashid="$udom:$uname";
                   12210:     &devalidate_cache_new('userres',$hashid);
                   12211: }
                   12212: 
1.624     albertel 12213: sub get_userresdata {
                   12214:     my ($uname,$udom)=@_;
                   12215:     #most student don\'t have any data set, check if there is some data
                   12216:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   12217: 
                   12218:     my $hashid="$udom:$uname";
                   12219:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   12220:     if (!defined($cached)) {
                   12221: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   12222: 	$result=\%resourcedata;
                   12223: 	&do_cache_new('userres',$hashid,$result,600);
                   12224:     }
                   12225:     my ($tmp)=keys(%$result);
                   12226:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   12227: 	return $result;
                   12228:     }
                   12229:     #error 2 occurs when the .db doesn't exist
                   12230:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  12231:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   12232: 	    &logthis("<font color=\"blue\">WARNING:".
                   12233: 		     " Trying to get resource data for ".
                   12234: 		     $uname." at ".$udom.": ".
                   12235: 		     $tmp."</font>");
                   12236:         }
1.624     albertel 12237:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 12238: 	#&EXT_cache_set($udom,$uname);
                   12239: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 12240: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 12241:     }
                   12242:     return $tmp;
                   12243: }
1.879     foxr     12244: #----------------------------------------------- resdata - return resource data
                   12245: #  Purpose:
                   12246: #    Return resource data for either users or for a course.
                   12247: #  Parameters:
                   12248: #     $name      - Course/user name.
                   12249: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  12250: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  12251: #     $mapp      - decluttered URL of enclosing map  
                   12252: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   12253: #     $recurseup - Ref to array of map URLs, starting with map containing
                   12254: #                  $mapp up through hierarchy of nested maps to top level map.  
                   12255: #     $courseid  - CourseID (first part of param identifier).
                   12256: #     $modifier  - Middle part of param identifier.
                   12257: #     $what      - Last part of param identifier.
1.879     foxr     12258: #     @which     - Array of names of resources desired.
                   12259: #  Returns:
                   12260: #     The value of the first reasource in @which that is found in the
                   12261: #     resource hash.
                   12262: #  Exceptional Conditions:
                   12263: #     If the $type passed in is not valid (not the string 'course' or 
                   12264: #     'user', an undefined  reference is returned.
                   12265: #     If none of the resources are found, an undef is returned
1.624     albertel 12266: sub resdata {
1.1301    raeburn  12267:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   12268:         $modifier,$what,@which)=@_;
1.624     albertel 12269:     my $result;
                   12270:     if ($type eq 'course') {
                   12271: 	$result=&get_courseresdata($name,$domain);
                   12272:     } elsif ($type eq 'user') {
                   12273: 	$result=&get_userresdata($name,$domain);
                   12274:     }
                   12275:     if (!ref($result)) { return $result; }    
1.251     albertel 12276:     foreach my $item (@which) {
1.1301    raeburn  12277:         if ($item->[1] eq 'course') {
                   12278:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   12279:                 unless ($$recursed) {
1.1302    raeburn  12280:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  12281:                     $$recursed = 1;
                   12282:                 }
                   12283:                 foreach my $item (@${recurseup}) {
                   12284:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   12285:                     last if (defined($result->{$norecursechk}));
                   12286:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   12287:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   12288:                 }
                   12289:             }
                   12290:         }
                   12291:         if (defined($result->{$item->[0]})) {
1.927     albertel 12292: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 12293: 	}
1.250     albertel 12294:     }
1.291     albertel 12295:     return undef;
1.200     www      12296: }
                   12297: 
1.1360    raeburn  12298: sub get_domain_lti {
                   12299:     my ($cdom,$context) = @_;
1.1483    raeburn  12300:     my ($name,$cachename,%lti);
1.1360    raeburn  12301:     if ($context eq 'consumer') {
                   12302:         $name = 'ltitools';
                   12303:     } elsif ($context eq 'provider') {
                   12304:         $name = 'lti';
1.1483    raeburn  12305:     } elsif ($context eq 'linkprot') {
                   12306:         $name = 'ltisec';
1.1360    raeburn  12307:     } else {
                   12308:         return %lti;
                   12309:     }
1.1483    raeburn  12310: 
                   12311:     if ($context eq 'linkprot') {
                   12312:         $cachename = $context;
                   12313:     } else {
                   12314:         $cachename = $name;
                   12315:     }
                   12316:     
                   12317:     my ($result,$cached)=&is_cached_new($cachename,$cdom);
1.1298    raeburn  12318:     if (defined($cached)) {
                   12319:         if (ref($result) eq 'HASH') {
1.1360    raeburn  12320:             %lti = %{$result};
1.1298    raeburn  12321:         }
                   12322:     } else {
1.1360    raeburn  12323:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   12324:         if (ref($domconfig{$name}) eq 'HASH') {
1.1483    raeburn  12325:             if ($context eq 'linkprot') {
                   12326:                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
                   12327:                     %lti = %{$domconfig{$name}{'linkprot'}};
                   12328:                 }
                   12329:             } else {
                   12330:                 %lti = %{$domconfig{$name}};
                   12331:             }
                   12332:             if (($context eq 'consumer') && (keys(%lti))) {
                   12333:                 my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
                   12334:                 if (ref($encdomconfig{$name}) eq 'HASH') {
                   12335:                     foreach my $id (keys(%lti)) {
                   12336:                         if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
                   12337:                             foreach my $item ('key','secret') {
                   12338:                                 $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
                   12339:                             }
1.1344    raeburn  12340:                         }
                   12341:                     }
                   12342:                 }
                   12343:             }
1.1298    raeburn  12344:         }
                   12345:         my $cachetime = 24*60*60;
1.1483    raeburn  12346:         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
1.1298    raeburn  12347:     }
1.1360    raeburn  12348:     return %lti;
1.1298    raeburn  12349: }
                   12350: 
1.1463    raeburn  12351: sub get_course_lti {
                   12352:     my ($cnum,$cdom) = @_;
                   12353:     my $hashid=$cdom.'_'.$cnum;
                   12354:     my %courselti;
                   12355:     my ($result,$cached)=&is_cached_new('courselti',$hashid);
                   12356:     if (defined($cached)) {
                   12357:         if (ref($result) eq 'HASH') {
                   12358:             %courselti = %{$result};
                   12359:         }
                   12360:     } else {
                   12361:         %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
                   12362:         my $cachetime = 24*60*60;
                   12363:         &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
                   12364:     }
                   12365:     return %courselti;
                   12366: }
                   12367: 
1.1479    raeburn  12368: sub courselti_itemid {
                   12369:     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
                   12370:     my ($chome,$itemid);
                   12371:     $chome = &homeserver($cnum,$cdom);
                   12372:     return if ($chome eq 'no_host');
                   12373:     if (ref($params) eq 'HASH') {
                   12374:         my $items = &freeze_escape($params);
                   12375:         my $rep;
                   12376:         if (grep { $_ eq $chome } current_machine_ids()) {
                   12377:             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
                   12378:         } else {
                   12379:             my $escurl = &escape($url);
                   12380:             my $escmethod = &escape($method);
                   12381:             my $items = &freeze_escape($params);
                   12382:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
                   12383:         }
                   12384:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   12385:                 ($rep eq 'unknown_cmd')) {
                   12386:             $itemid = $rep;
                   12387:         }
                   12388:     }
                   12389:     return $itemid;
                   12390: }
                   12391: 
                   12392: sub domainlti_itemid {
                   12393:     my ($cdom,$url,$method,$params,$context) = @_;
                   12394:     my ($primary_id,$itemid);
                   12395:     $primary_id = &domain($cdom,'primary');
                   12396:     return if ($primary_id eq '');
                   12397:     if (ref($params) eq 'HASH') {
                   12398:         my $items = &freeze_escape($params);
                   12399:         my $rep;
                   12400:         if (grep { $_ eq $primary_id } current_machine_ids()) {
                   12401:             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
                   12402:         } else {
                   12403:             my $cnum = '';
                   12404:             my $escurl = &escape($url);
                   12405:             my $escmethod = &escape($method);
                   12406:             my $items = &freeze_escape($params);
                   12407:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
                   12408:         }
                   12409:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   12410:                 ($rep eq 'unknown_cmd')) {
                   12411:             $itemid = $rep;
                   12412:         }
                   12413:     }
                   12414:     return $itemid;
                   12415: }
                   12416: 
1.1236    raeburn  12417: sub get_numsuppfiles {
                   12418:     my ($cnum,$cdom,$ignorecache)=@_;
                   12419:     my $hashid=$cnum.':'.$cdom;
                   12420:     my ($suppcount,$cached);
                   12421:     unless ($ignorecache) {
                   12422:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   12423:     }
                   12424:     unless (defined($cached)) {
                   12425:         my $chome=&homeserver($cnum,$cdom);
                   12426:         unless ($chome eq 'no_host') {
1.1366    raeburn  12427:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  12428:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  12429:             ($suppcount,$supptools,$errors) =
                   12430:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   12431:                                                          $supptools,$errors);
1.1236    raeburn  12432:         }
                   12433:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   12434:     }
                   12435:     return $suppcount;
                   12436: }
                   12437: 
1.379     matthew  12438: #
                   12439: # EXT resource caching routines
                   12440: #
                   12441: 
1.1302    raeburn  12442: {
                   12443: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   12444: #
                   12445: # The course for which we cache
                   12446: my $cachedmapkey='';
                   12447: # The cached recursive maps for this course
                   12448: my %cachedmaps=();
                   12449: # When this was last done
                   12450: my $cachedmaptime='';
                   12451: 
1.379     matthew  12452: sub clear_EXT_cache_status {
1.383     albertel 12453:     &delenv('cache.EXT.');
1.379     matthew  12454: }
                   12455: 
                   12456: sub EXT_cache_status {
                   12457:     my ($target_domain,$target_user) = @_;
1.383     albertel 12458:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 12459:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  12460:         # We know already the user has no data
                   12461:         return 1;
                   12462:     } else {
                   12463:         return 0;
                   12464:     }
                   12465: }
                   12466: 
                   12467: sub EXT_cache_set {
                   12468:     my ($target_domain,$target_user) = @_;
1.383     albertel 12469:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  12470:     #&appenv({$cachename => time});
1.379     matthew  12471: }
                   12472: 
1.28      www      12473: # --------------------------------------------------------- Value of a Variable
1.58      www      12474: sub EXT {
1.715     albertel 12475: 
1.1461    raeburn  12476:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
1.68      www      12477:     unless ($varname) { return ''; }
1.218     albertel 12478:     #get real user name/domain, courseid and symb
                   12479:     my $courseid;
1.359     albertel 12480:     my $publicuser;
1.427     www      12481:     if ($symbparm) {
                   12482: 	$symbparm=&get_symb_from_alias($symbparm);
                   12483:     }
1.218     albertel 12484:     if (!($uname && $udom)) {
1.790     albertel 12485:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 12486:       if (!$symbparm) {	$symbparm=$cursymb; }
                   12487:     } else {
1.620     albertel 12488: 	$courseid=$env{'request.course.id'};
1.218     albertel 12489:     }
1.48      www      12490:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   12491:     my $rest;
1.320     albertel 12492:     if (defined($therest[0])) {
1.48      www      12493:        $rest=join('.',@therest);
                   12494:     } else {
                   12495:        $rest='';
                   12496:     }
1.320     albertel 12497: 
1.57      www      12498:     my $qualifierrest=$qualifier;
                   12499:     if ($rest) { $qualifierrest.='.'.$rest; }
                   12500:     my $spacequalifierrest=$space;
                   12501:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      12502:     if ($realm eq 'user') {
1.48      www      12503: # --------------------------------------------------------------- user.resource
                   12504: 	if ($space eq 'resource') {
1.651     albertel 12505: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   12506: 		  || defined($Apache::lonhomework::parsing_a_task))
                   12507: 		 &&
1.1469    raeburn  12508: 		 ($symbparm eq &symbread()) ) {
1.744     albertel 12509: 		# if we are in the middle of processing the resource the
                   12510: 		# get the value we are planning on committing
                   12511:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   12512:                     return $Apache::lonhomework::results{$qualifierrest};
                   12513:                 } else {
                   12514:                     return $Apache::lonhomework::history{$qualifierrest};
                   12515:                 }
1.335     albertel 12516: 	    } else {
1.359     albertel 12517: 		my %restored;
1.620     albertel 12518: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 12519: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   12520: 		} else {
                   12521: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   12522: 		}
1.335     albertel 12523: 		return $restored{$qualifierrest};
                   12524: 	    }
1.48      www      12525: # ----------------------------------------------------------------- user.access
                   12526:         } elsif ($space eq 'access') {
1.218     albertel 12527: 	    # FIXME - not supporting calls for a specific user
1.48      www      12528:             return &allowed($qualifier,$rest);
                   12529: # ------------------------------------------ user.preferences, user.environment
                   12530:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 12531: 	    if (($uname eq $env{'user.name'}) &&
                   12532: 		($udom eq $env{'user.domain'})) {
                   12533: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 12534: 	    } else {
1.359     albertel 12535: 		my %returnhash;
                   12536: 		if (!$publicuser) {
                   12537: 		    %returnhash=&userenvironment($udom,$uname,
                   12538: 						 $qualifierrest);
                   12539: 		}
1.218     albertel 12540: 		return $returnhash{$qualifierrest};
                   12541: 	    }
1.48      www      12542: # ----------------------------------------------------------------- user.course
                   12543:         } elsif ($space eq 'course') {
1.218     albertel 12544: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12545:             return $env{join('.',('request.course',$qualifier))};
1.48      www      12546: # ------------------------------------------------------------------- user.role
                   12547:         } elsif ($space eq 'role') {
1.218     albertel 12548: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12549:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      12550:             if ($qualifier eq 'value') {
                   12551: 		return $role;
                   12552:             } elsif ($qualifier eq 'extent') {
                   12553:                 return $where;
                   12554:             }
                   12555: # ----------------------------------------------------------------- user.domain
                   12556:         } elsif ($space eq 'domain') {
1.218     albertel 12557:             return $udom;
1.48      www      12558: # ------------------------------------------------------------------- user.name
                   12559:         } elsif ($space eq 'name') {
1.218     albertel 12560:             return $uname;
1.48      www      12561: # ---------------------------------------------------- Any other user namespace
1.29      www      12562:         } else {
1.359     albertel 12563: 	    my %reply;
                   12564: 	    if (!$publicuser) {
                   12565: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   12566: 	    }
                   12567: 	    return $reply{$qualifierrest};
1.48      www      12568:         }
1.236     www      12569:     } elsif ($realm eq 'query') {
                   12570: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 12571:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   12572: 						[$spacequalifierrest]);
1.620     albertel 12573: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      12574:    } elsif ($realm eq 'request') {
1.48      www      12575: # ------------------------------------------------------------- request.browser
                   12576:         if ($space eq 'browser') {
1.1145    bisitz   12577:             return $env{'browser.'.$qualifier};
1.57      www      12578: # ------------------------------------------------------------ request.filename
                   12579:         } else {
1.620     albertel 12580:             return $env{'request.'.$spacequalifierrest};
1.29      www      12581:         }
1.28      www      12582:     } elsif ($realm eq 'course') {
1.48      www      12583: # ---------------------------------------------------------- course.description
1.620     albertel 12584:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      12585:     } elsif ($realm eq 'resource') {
1.165     www      12586: 
1.620     albertel 12587: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 12588: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   12589: 	}
1.693     albertel 12590: 
1.1232    raeburn  12591:         if ($qualifier eq '') {
                   12592: 	    if ($space eq 'title') {
                   12593: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   12594: 	        return &gettitle($symbparm);
                   12595: 	    }
1.693     albertel 12596: 	
1.1232    raeburn  12597: 	    if ($space eq 'map') {
                   12598: 	        my ($map) = &decode_symb($symbparm);
                   12599: 	        return &symbread($map);
                   12600: 	    }
                   12601:             if ($space eq 'maptitle') {
                   12602:                 my ($map) = &decode_symb($symbparm);
                   12603:                 return &gettitle($map);
                   12604:             }
                   12605: 	    if ($space eq 'filename') {
                   12606: 	        if ($symbparm) {
                   12607: 		    return &clutter((&decode_symb($symbparm))[2]);
                   12608: 	        }
                   12609: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 12610: 	    }
1.1232    raeburn  12611: 
1.1233    raeburn  12612:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   12613:                 if ($space eq 'visibleparts') {
                   12614:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   12615:                     my $item;
                   12616:                     if (ref($navmap)) {
                   12617:                         my $res = $navmap->getBySymb($symbparm);
                   12618:                         my $parts = $res->parts();
                   12619:                         if (ref($parts) eq 'ARRAY') {
                   12620:                             $item = join(',',@{$parts});
                   12621:                         }
                   12622:                         undef($navmap);
1.1232    raeburn  12623:                     }
1.1233    raeburn  12624:                     return $item;
1.1232    raeburn  12625:                 }
                   12626:             }
                   12627:         }
1.693     albertel 12628: 
1.1301    raeburn  12629: 	my ($section, $group, @groups, @recurseup, $recursed);
1.1461    raeburn  12630:         if (ref($recurseupref) eq 'ARRAY') {
                   12631:             @recurseup = @{$recurseupref};
                   12632:             $recursed = 1;
                   12633:         }
1.1301    raeburn  12634: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  12635:         if (($courseid eq '') && ($cid)) {
                   12636:             $courseid = $cid;
                   12637:         }
                   12638: 	if (($symbparm && $courseid) && 
                   12639: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      12640: 
1.218     albertel 12641: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      12642: 
1.60      www      12643: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 12644: 	    my $symbp=$symbparm;
1.1301    raeburn  12645: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 12646: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  12647:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 12648: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 12649: 	    if (($env{'user.name'} eq $uname) &&
                   12650: 		($env{'user.domain'} eq $udom)) {
                   12651: 		$section=$env{'request.course.sec'};
1.733     raeburn  12652:                 @groups = split(/:/,$env{'request.course.groups'});  
                   12653:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 12654: 	    } else {
1.539     albertel 12655: 		if (! defined($usection)) {
1.551     albertel 12656: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 12657: 		} else {
                   12658: 		    $section = $usection;
                   12659: 		}
1.733     raeburn  12660:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12661: 	    }
                   12662: 
                   12663: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12664: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  12665:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 12666: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12667: 
1.593     albertel 12668: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12669: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  12670:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 12671: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12672: 
1.60      www      12673: # ----------------------------------------------------------- first, check user
1.624     albertel 12674: 
1.1301    raeburn  12675: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   12676:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 12677: 				       ([$courselevelr,'resource'],
                   12678: 					[$courselevelm,'map'     ],
1.1301    raeburn  12679:                                         [$courseleveli,'map'     ],
1.927     albertel 12680: 					[$courselevel, 'course'  ]));
1.931     albertel 12681: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12682: 
1.594     albertel 12683: # ------------------------------------------------ second, check some of course
1.684     raeburn  12684:             my $coursereply;
1.691     raeburn  12685:             if (@groups > 0) {
                   12686:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  12687:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   12688:                                        $mapp,\$recursed,\@recurseup);
                   12689:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  12690:             }
1.96      www      12691: 
1.684     raeburn  12692: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12693: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12694: 				  'course',$mapp,\$recursed,\@recurseup,
                   12695:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 12696: 				  ([$seclevelr,   'resource'],
                   12697: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  12698:                                    [$secleveli,   'map'     ],
1.927     albertel 12699: 				   [$seclevel,    'course'  ],
                   12700: 				   [$courselevelr,'resource']));
                   12701: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12702: 
1.60      www      12703: # ------------------------------------------------------ third, check map parms
1.218     albertel 12704: 	    my %parmhash=();
                   12705: 	    my $thisparm='';
                   12706: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12707: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12708: 		    &GDBM_READER(),0640)) {
1.218     albertel 12709: 		$thisparm=$parmhash{$symbparm};
                   12710: 		untie(%parmhash);
                   12711: 	    }
1.927     albertel 12712: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12713: 	}
1.594     albertel 12714: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  12715:  
                   12716:         my $what = $spacequalifierrest;
                   12717: 	$what=~s/\./\_/;
1.282     albertel 12718: 	my $filename;
                   12719: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12720: 	if ($symbparm) {
1.409     www      12721: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12722: 	} else {
1.620     albertel 12723: 	    $filename=$env{'request.filename'};
1.282     albertel 12724: 	}
1.1362    raeburn  12725:         my $toolsymb;
                   12726:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   12727:             $toolsymb = $symbparm;
                   12728:         }
                   12729: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 12730: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  12731: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 12732: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12733: 
1.1301    raeburn  12734: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 12735: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12736: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12737: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12738: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12739: 				     'course',$mapp,\$recursed,\@recurseup,
                   12740:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 12741: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  12742:                                       [$courseleveli,'map'   ],
1.927     albertel 12743: 				      [$courselevel, 'course']));
                   12744: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12745: 	}
1.145     www      12746: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12747: 	unless ($space eq '0') {
1.336     albertel 12748: 	    my @parts=split(/_/,$space);
                   12749: 	    my $id=pop(@parts);
                   12750: 	    my $part=join('_',@parts);
                   12751: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12752: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12753: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12754: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12755: 	}
1.395     albertel 12756: 	if ($recurse) { return undef; }
1.1362    raeburn  12757: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 12758: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12759: # ---------------------------------------------------- Any other user namespace
                   12760:     } elsif ($realm eq 'environment') {
                   12761: # ----------------------------------------------------------------- environment
1.620     albertel 12762: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12763: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12764: 	} else {
1.770     albertel 12765: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12766: 		return '';
                   12767: 	    }
1.219     albertel 12768: 	    my %returnhash=&userenvironment($udom,$uname,
                   12769: 					    $spacequalifierrest);
                   12770: 	    return $returnhash{$spacequalifierrest};
                   12771: 	}
1.28      www      12772:     } elsif ($realm eq 'system') {
1.48      www      12773: # ----------------------------------------------------------------- system.time
                   12774: 	if ($space eq 'time') {
                   12775: 	    return time;
                   12776:         }
1.696     albertel 12777:     } elsif ($realm eq 'server') {
                   12778: # ----------------------------------------------------------------- system.time
                   12779: 	if ($space eq 'name') {
                   12780: 	    return $ENV{'SERVER_NAME'};
                   12781:         }
1.1415    raeburn  12782:     } elsif ($realm eq 'client') {
                   12783:         if ($space eq 'remote_addr') {
1.1441    raeburn  12784:             return &get_requestor_ip();
1.1415    raeburn  12785:         }
1.28      www      12786:     }
1.48      www      12787:     return '';
1.61      www      12788: }
                   12789: 
1.927     albertel 12790: sub get_reply {
                   12791:     my ($reply_value) = @_;
1.940     raeburn  12792:     if (ref($reply_value) eq 'ARRAY') {
                   12793:         if (wantarray) {
                   12794: 	    return @$reply_value;
                   12795:         }
                   12796:         return $reply_value->[0];
                   12797:     } else {
                   12798:         return $reply_value;
1.927     albertel 12799:     }
                   12800: }
                   12801: 
1.691     raeburn  12802: sub check_group_parms {
1.1301    raeburn  12803:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   12804:         $recursed,$recurseupref) = @_;
                   12805:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   12806:                   [$what,'course']);
                   12807:     my $coursereply;
1.691     raeburn  12808:     foreach my $group (@{$groups}) {
1.1301    raeburn  12809:         my @groupitems = ();
1.691     raeburn  12810:         foreach my $level (@levels) {
1.927     albertel 12811:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12812:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12813:         }
1.1301    raeburn  12814:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12815:                                    $env{'course.'.$courseid.'.domain'},
                   12816:                                    'course',$mapp,$recursed,$recurseupref,
                   12817:                                    $courseid,'.['.$group.'].',$what,
                   12818:                                    @groupitems);
                   12819:         last if (defined($coursereply));
1.691     raeburn  12820:     }
                   12821:     return $coursereply;
                   12822: }
                   12823: 
1.1301    raeburn  12824: sub get_map_hierarchy {
1.1302    raeburn  12825:     my ($mapname,$courseid) = @_;
                   12826:     my @recurseup = ();
1.1301    raeburn  12827:     if ($mapname) {
1.1302    raeburn  12828:         if (($cachedmapkey eq $courseid) &&
                   12829:             (abs($cachedmaptime-time)<5)) {
                   12830:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12831:                 return @{$cachedmaps{$mapname}};
                   12832:             }
                   12833:         }
1.1301    raeburn  12834:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12835:         if (ref($navmap)) {
                   12836:             @recurseup = $navmap->recurseup_maps($mapname);
                   12837:             undef($navmap);
1.1302    raeburn  12838:             $cachedmaps{$mapname} = \@recurseup;
                   12839:             $cachedmaptime=time;
                   12840:             $cachedmapkey=$courseid;
1.1301    raeburn  12841:         }
                   12842:     }
                   12843:     return @recurseup;
                   12844: }
                   12845: 
1.1302    raeburn  12846: }
                   12847: 
1.691     raeburn  12848: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12849:     my ($courseid,@groups) = @_;
                   12850:     @groups = sort(@groups);
1.691     raeburn  12851:     return @groups;
                   12852: }
                   12853: 
1.395     albertel 12854: sub packages_tab_default {
1.1362    raeburn  12855:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 12856:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12857: 
                   12858:     my (@extension,@specifics,$do_default);
1.1362    raeburn  12859:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 12860: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12861: 	if ($pack_type eq 'default') {
                   12862: 	    $do_default=1;
                   12863: 	} elsif ($pack_type eq 'extension') {
                   12864: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12865: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12866: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12867: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12868: 	}
                   12869:     }
                   12870:     # first look for a package that matches the requested part id
                   12871:     foreach my $package (@specifics) {
                   12872: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12873: 	next if ($pack_part ne $part);
                   12874: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12875: 	    return $packagetab{"$pack_type&$name&default"};
                   12876: 	}
                   12877:     }
                   12878:     # look for any possible matching non extension_ package
                   12879:     foreach my $package (@specifics) {
                   12880: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12881: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12882: 	    return $packagetab{"$pack_type&$name&default"};
                   12883: 	}
1.585     albertel 12884: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12885: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12886: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12887: 	}
                   12888:     }
1.738     albertel 12889:     # look for any posible extension_ match
                   12890:     foreach my $package (@extension) {
                   12891: 	my ($package,$pack_type)=@{$package};
                   12892: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12893: 	    return $packagetab{"$pack_type&$name&default"};
                   12894: 	}
                   12895: 	if (defined($packagetab{$package."&$name&default"})) {
                   12896: 	    return $packagetab{$package."&$name&default"};
                   12897: 	}
                   12898:     }
                   12899:     # look for a global default setting
                   12900:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12901: 	return $packagetab{"default&$name&default"};
                   12902:     }
1.395     albertel 12903:     return undef;
                   12904: }
                   12905: 
1.334     albertel 12906: sub add_prefix_and_part {
                   12907:     my ($prefix,$part)=@_;
                   12908:     my $keyroot;
                   12909:     if (defined($prefix) && $prefix !~ /^__/) {
                   12910: 	# prefix that has a part already
                   12911: 	$keyroot=$prefix;
                   12912:     } elsif (defined($prefix)) {
                   12913: 	# prefix that is missing a part
                   12914: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12915:     } else {
                   12916: 	# no prefix at all
                   12917: 	if (defined($part)) { $keyroot='_'.$part; }
                   12918:     }
                   12919:     return $keyroot;
                   12920: }
                   12921: 
1.71      www      12922: # ---------------------------------------------------------------- Get metadata
                   12923: 
1.599     albertel 12924: my %metaentry;
1.1070    www      12925: my %importedpartids;
1.1369    raeburn  12926: my %importedrespids;
1.71      www      12927: sub metadata {
1.1362    raeburn  12928:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      12929:     $uri=&declutter($uri);
1.288     albertel 12930:     # if it is a non metadata possible uri return quickly
1.529     albertel 12931:     if (($uri eq '') || 
                   12932: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  12933: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12934:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12935: 	return undef;
                   12936:     }
1.1261    raeburn  12937:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12938: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12939: 	return undef;
1.288     albertel 12940:     }
1.73      www      12941:     my $filename=$uri;
                   12942:     $uri=~s/\.meta$//;
1.172     www      12943: #
                   12944: # Is the metadata already cached?
1.177     www      12945: # Look at timestamp of caching
1.172     www      12946: # Everything is cached by the main uri, libraries are never directly cached
                   12947: #
1.428     albertel 12948:     if (!defined($liburi)) {
1.599     albertel 12949: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12950: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12951:     }
1.1362    raeburn  12952: 
                   12953: #
                   12954: # If the uri is for an external tool the file from
                   12955: # which metadata should be retrieved depends on whether
                   12956: # the tool had been configured to be gradable (set in the Course
                   12957: # Editor or Resource Editor).
                   12958: #
                   12959: # If a valid symb has been included as the third arg in the call
                   12960: # to &metadata() that can be used to retrieve the value of
                   12961: # parameter_0_gradable set for the resource, and included in the
                   12962: # uploaded map containing the tool. The value is retrieved via
                   12963: # &EXT(), if a valid symb is available.  Otherwise the value of
                   12964: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  12965: # is retrieved via &get().
                   12966: #
                   12967: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   12968: # hiddenresource and encrypturl (during course initialization)
                   12969: # the map-level parameter for resource.0.gradable included in the 
                   12970: # uploaded map containing the tool will not yet have been stored
                   12971: # in the user_course_parms.db file for the user's session, so in 
                   12972: # this case fall back to retrieving gradable status from the
                   12973: # exttool_$marker.db file.
1.1362    raeburn  12974: #
                   12975: # In order to avoid an infinite loop, &metadata() will return
                   12976: # before a call to &EXT(), if the uri is for an external tool
                   12977: # and the $what for which metadata is being requested is
                   12978: # parameter_0_gradable or 0_gradable.
                   12979: #
                   12980: 
                   12981:     if ($uri =~ /ext\.tool$/) {
                   12982:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   12983:             return;
                   12984:         } else {
                   12985:             my ($checked,$use_passback);
                   12986:             if ($toolsymb ne '') {
                   12987:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  12988:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  12989:                     $checked = 1;
                   12990:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   12991:                         $use_passback = 1;
                   12992:                     }
                   12993:                 }
                   12994:             }
                   12995:             unless ($checked) {
                   12996:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   12997:                 $marker=~s/\D//g;
1.1363    raeburn  12998:                 if ($marker) {
1.1362    raeburn  12999:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   13000:                     $use_passback = $toolsettings{'gradable'};
                   13001:                 }
                   13002:             }
                   13003:             if ($use_passback) {
                   13004:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   13005:             } else {
                   13006:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   13007:             }
                   13008:         }
                   13009:     }
                   13010: 
1.428     albertel 13011:     {
1.1069    www      13012: # Imported parts would go here
1.1369    raeburn  13013:         my @origfiletagids=();
1.1069    www      13014:         my $importedparts=0;
1.1369    raeburn  13015: 
                   13016: # Imported responseids would go here
                   13017:         my $importedresponses=0;
1.172     www      13018: #
                   13019: # Is this a recursive call for a library?
                   13020: #
1.599     albertel 13021: #	if (! exists($metacache{$uri})) {
                   13022: #	    $metacache{$uri}={};
                   13023: #	}
1.924     albertel 13024: 	my $cachetime = 60*60;
1.171     www      13025:         if ($liburi) {
                   13026: 	    $liburi=&declutter($liburi);
                   13027:             $filename=$liburi;
1.401     bowersj2 13028:         } else {
1.599     albertel 13029: 	    &devalidate_cache_new('meta',$uri);
                   13030: 	    undef(%metaentry);
1.401     bowersj2 13031: 	}
1.140     www      13032:         my %metathesekeys=();
1.73      www      13033:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 13034: 	my $metastring;
1.1140    www      13035: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 13036: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 13037: 	    $metastring = 
1.929     albertel 13038: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 13039: 					  ('grade_target' => 'meta'));
                   13040: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  13041: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   13042:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 13043: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 13044: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 13045: 	    $metastring=&getfile($file);
1.489     albertel 13046: 	}
1.208     albertel 13047:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      13048:         my $token;
1.140     www      13049:         undef %metathesekeys;
1.71      www      13050:         while ($token=$parser->get_token) {
1.339     albertel 13051: 	    if ($token->[0] eq 'S') {
                   13052: 		if (defined($token->[2]->{'package'})) {
1.172     www      13053: #
                   13054: # This is a package - get package info
                   13055: #
1.339     albertel 13056: 		    my $package=$token->[2]->{'package'};
                   13057: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13058: 		    if (defined($token->[2]->{'id'})) { 
                   13059: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   13060: 		    }
1.599     albertel 13061: 		    if ($metaentry{':packages'}) {
                   13062: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 13063: 		    } else {
1.599     albertel 13064: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 13065: 		    }
1.736     albertel 13066: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 13067: 			my $part=$keyroot;
                   13068: 			$part=~s/^\_//;
1.736     albertel 13069: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   13070: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   13071: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 13072: 			    # ignore package.tab specified default values
                   13073:                             # here &package_tab_default() will fetch those
                   13074: 			    if ($subp eq 'default') { next; }
1.736     albertel 13075: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 13076: 			    my $unikey;
                   13077: 			    if ($pack =~ /_0$/) {
                   13078: 				$unikey='parameter_0_'.$name;
                   13079: 				$part=0;
                   13080: 			    } else {
                   13081: 				$unikey='parameter'.$keyroot.'_'.$name;
                   13082: 			    }
1.339     albertel 13083: 			    if ($subp eq 'display') {
                   13084: 				$value.=' [Part: '.$part.']';
                   13085: 			    }
1.599     albertel 13086: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 13087: 			    $metathesekeys{$unikey}=1;
1.599     albertel 13088: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   13089: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 13090: 			    }
1.599     albertel 13091: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   13092: 				$metaentry{':'.$unikey}=
                   13093: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 13094: 			    }
1.339     albertel 13095: 			}
                   13096: 		    }
                   13097: 		} else {
1.172     www      13098: #
                   13099: # This is not a package - some other kind of start tag
1.339     albertel 13100: #
                   13101: 		    my $entry=$token->[1];
1.1068    www      13102: 		    my $unikey='';
1.175     www      13103: 
1.339     albertel 13104: 		    if ($entry eq 'import') {
1.175     www      13105: #
                   13106: # Importing a library here
1.339     albertel 13107: #
1.1067    www      13108:                         my $location=$parser->get_text('/import');
                   13109:                         my $dir=$filename;
                   13110:                         $dir=~s|[^/]*$||;
                   13111:                         $location=&filelocation($dir,$location);
1.1369    raeburn  13112: 
                   13113:                         my $importid=$token->[2]->{'id'};
1.1068    www      13114:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  13115: #
                   13116: # Check metadata for imported file to
                   13117: # see if it contained response items
                   13118: #
1.1372    raeburn  13119:                         my ($origfile,@libfilekeys);
1.1370    raeburn  13120:                         my %currmetaentry = %metaentry;
1.1372    raeburn  13121:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   13122:                                                            $depthcount+1));
                   13123:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   13124:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   13125:                                                              undef,$depthcount+1);
                   13126:                             if ($libresponseorder ne '') {
                   13127:                                 if ($#origfiletagids<0) {
                   13128:                                     undef(%importedrespids);
                   13129:                                     undef(%importedpartids);
                   13130:                                 }
1.1373    raeburn  13131:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   13132:                                 if (@respids) {
                   13133:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   13134:                                 }
                   13135:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  13136:                                     $importedresponses = 1;
1.1369    raeburn  13137: # We need to get the original file and the imported file to get the response order correct
                   13138: # Load and inspect original file
1.1372    raeburn  13139:                                     if ($#origfiletagids<0) {
                   13140:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   13141:                                         $origfile=&getfile($origfilelocation);
                   13142:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13143:                                     }
1.1369    raeburn  13144:                                 }
                   13145:                             }
                   13146:                         }
1.1370    raeburn  13147: # Do not overwrite contents of %metaentry hash for resource itself with 
                   13148: # hash populated for imported library file
                   13149:                         %metaentry = %currmetaentry;
                   13150:                         undef(%currmetaentry);
1.1374    raeburn  13151:                         if ($importmode eq 'part') {
1.1068    www      13152: # Import as part(s)
1.1069    www      13153:                            $importedparts=1;
                   13154: # We need to get the original file and the imported file to get the part order correct
                   13155: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  13156: # Load and inspect original file if we didn't do that already
                   13157:                            if ($#origfiletagids<0) {
                   13158:                                undef(%importedrespids);
                   13159:                                undef(%importedpartids);
                   13160:                                if ($origfile eq '') {
                   13161:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   13162:                                    $origfile=&getfile($origfilelocation);
                   13163:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13164:                                }
1.1070    www      13165:                            }
1.1372    raeburn  13166:                            my @impfilepartids;
                   13167: # If <partorder> tag is included in metadata for the imported file
                   13168: # get the parts in the imported file from that.
                   13169:                            if (grep(/^partorder$/,@libfilekeys)) {
                   13170:                                %currmetaentry = %metaentry;
                   13171:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   13172:                                                             $depthcount+1);
                   13173:                                %metaentry = %currmetaentry;
                   13174:                                undef(%currmetaentry);
                   13175:                                if ($libpartorder ne '') {
                   13176:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   13177:                                }
                   13178:                            } else {
                   13179: # If no <partorder> tag available, load and inspect imported file
                   13180:                                my $impfile=&getfile($location);
                   13181:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13182:                            }
1.1069    www      13183:                            if ($#impfilepartids>=0) {
                   13184: # This problem had parts
1.1070    www      13185:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      13186:                            } else {
                   13187: # Importing by turning a single problem into a problem part
                   13188: # It gets the import-tags ID as part-ID
                   13189:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      13190:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      13191:                            }
1.1068    www      13192:                         } else {
1.1374    raeburn  13193: # Import as problem or as normal import
                   13194:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13195:                             unless ($importmode eq 'problem') {
1.1068    www      13196: # Normal import
1.1374    raeburn  13197:                                 if (defined($token->[2]->{'id'})) {
                   13198:                                     $unikey.='_'.$token->[2]->{'id'};
                   13199:                                 }
                   13200:                             }
                   13201: # Check metadata for imported file to
                   13202: # see if it contained parts
                   13203:                             if (grep(/^partorder$/,@libfilekeys)) {
                   13204:                                 %currmetaentry = %metaentry;
                   13205:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   13206:                                                              $depthcount+1);
                   13207:                                 %metaentry = %currmetaentry;
                   13208:                                 undef(%currmetaentry);
                   13209:                                 if ($libpartorder ne '') {
                   13210:                                     $importedparts = 1;
                   13211:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   13212:                                 }
                   13213:                             }
1.1067    www      13214:                         }
1.339     albertel 13215: 			if ($depthcount<20) {
1.736     albertel 13216: 			    my $metadata = 
1.1362    raeburn  13217: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 13218: 					  $depthcount+1);
                   13219: 			    foreach my $meta (split(',',$metadata)) {
                   13220: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   13221: 				$metathesekeys{$meta}=1;
1.339     albertel 13222: 			    }
1.1068    www      13223:                         }
1.1067    www      13224: 		    } else {
                   13225: #
                   13226: # Not importing, some other kind of non-package, non-library start tag
                   13227: # 
                   13228:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13229:                         if (defined($token->[2]->{'id'})) {
                   13230:                             $unikey.='_'.$token->[2]->{'id'};
                   13231:                         }
1.339     albertel 13232: 			if (defined($token->[2]->{'name'})) { 
                   13233: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   13234: 			}
                   13235: 			$metathesekeys{$unikey}=1;
1.736     albertel 13236: 			foreach my $param (@{$token->[3]}) {
                   13237: 			    $metaentry{':'.$unikey.'.'.$param} =
                   13238: 				$token->[2]->{$param};
1.339     albertel 13239: 			}
                   13240: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 13241: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 13242: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   13243: 		 # only ws inside the tag, and not in default, so use default
                   13244: 		 # as value
1.599     albertel 13245: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 13246: 			} elsif ( $internaltext =~ /\S/ ) {
                   13247: 		  # something interesting inside the tag
                   13248: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 13249: 			} else {
1.908     albertel 13250: 		  # no interesting values, don't set a default
1.339     albertel 13251: 			}
1.172     www      13252: # end of not-a-package not-a-library import
1.339     albertel 13253: 		    }
1.172     www      13254: # end of not-a-package start tag
1.339     albertel 13255: 		}
1.172     www      13256: # the next is the end of "start tag"
1.339     albertel 13257: 	    }
                   13258: 	}
1.483     albertel 13259: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 13260: 	$extension = lc($extension);
                   13261: 	if ($extension eq 'htm') { $extension='html'; }
                   13262: 
1.737     albertel 13263: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 13264: 	    #no specific packages #how's our extension
                   13265: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 13266: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 13267: 					 \%metathesekeys);
                   13268: 	}
1.883     albertel 13269: 
                   13270: 	if (!exists($metaentry{':packages'})
                   13271: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 13272: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 13273: 		#no specific packages well let's get default then
                   13274: 		if ($key!~/^default&/) { next; }
1.488     albertel 13275: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 13276: 					     \%metathesekeys);
                   13277: 	    }
                   13278: 	}
1.338     www      13279: # are there custom rights to evaluate
1.599     albertel 13280: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 13281: 
1.338     www      13282:     #
                   13283:     # Importing a rights file here
1.339     albertel 13284:     #
                   13285: 	    unless ($depthcount) {
1.599     albertel 13286: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 13287: 		my $dir=$filename;
                   13288: 		$dir=~s|[^/]*$||;
                   13289: 		$location=&filelocation($dir,$location);
1.736     albertel 13290: 		my $rights_metadata =
1.1362    raeburn  13291: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 13292: 			      $depthcount+1);
                   13293: 		foreach my $rights (split(',',$rights_metadata)) {
                   13294: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   13295: 		    $metathesekeys{$rights}=1;
1.339     albertel 13296: 		}
                   13297: 	    }
                   13298: 	}
1.737     albertel 13299: 	# uniqifiy package listing
                   13300: 	my %seen;
                   13301: 	my @uniq_packages =
                   13302: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   13303: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   13304: 
1.1369    raeburn  13305:         if (($importedresponses) || ($importedparts)) {
                   13306:             if ($importedparts) {
1.1070    www      13307: # We had imported parts and need to rebuild partorder
1.1369    raeburn  13308:                 $metaentry{':partorder'}='';
                   13309:                 $metathesekeys{'partorder'}=1;
                   13310:             }
                   13311:             if ($importedresponses) {
                   13312: # We had imported responses and need to rebuil responseorder
                   13313:                 $metaentry{':responseorder'}='';
                   13314:                 $metathesekeys{'responseorder'}=1;
                   13315:             }
                   13316:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   13317:                 my $origid = $origfiletagids[$index+1];
                   13318:                 if ($origfiletagids[$index] eq 'part') {
                   13319: # Original part, part of the problem
                   13320:                     if ($importedparts) {
                   13321:                         $metaentry{':partorder'}.=','.$origid;
                   13322:                     }
                   13323:                 } elsif ($origfiletagids[$index] eq 'import') {
                   13324:                     if ($importedparts) {
                   13325: # We have imported parts at this position
1.1373    raeburn  13326:                         if ($importedpartids{$origid} ne '') {
                   13327:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   13328:                         }
1.1369    raeburn  13329:                     }
                   13330:                     if ($importedresponses) {
                   13331: # We have imported responses at this position
1.1373    raeburn  13332:                         if ($importedrespids{$origid} ne '') {
                   13333:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  13334:                         }
                   13335:                     }
                   13336:                 } else {
                   13337: # Original response item, part of the problem
                   13338:                     if ($importedresponses) {
                   13339:                         $metaentry{':responseorder'}.=','.$origid;
                   13340:                     }
                   13341:                 }
                   13342:             }
                   13343:             if ($importedparts) {
                   13344:                 $metaentry{':partorder'}=~s/^\,//;
                   13345:             }
                   13346:             if ($importedresponses) {
                   13347:                 $metaentry{':responseorder'}=~s/^\,//;
                   13348:             }
1.1070    www      13349:         }
1.737     albertel 13350: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 13351: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  13352: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  13353:         unless ($liburi) {
                   13354: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   13355:         }
1.177     www      13356: # this is the end of "was not already recently cached
1.71      www      13357:     }
1.599     albertel 13358:     return $metaentry{':'.$what};
1.261     albertel 13359: }
                   13360: 
1.488     albertel 13361: sub metadata_create_package_def {
1.483     albertel 13362:     my ($uri,$key,$package,$metathesekeys)=@_;
                   13363:     my ($pack,$name,$subp)=split(/\&/,$key);
                   13364:     if ($subp eq 'default') { next; }
                   13365:     
1.599     albertel 13366:     if (defined($metaentry{':packages'})) {
                   13367: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 13368:     } else {
1.599     albertel 13369: 	$metaentry{':packages'}=$package;
1.483     albertel 13370:     }
                   13371:     my $value=$packagetab{$key};
                   13372:     my $unikey;
                   13373:     $unikey='parameter_0_'.$name;
1.599     albertel 13374:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 13375:     $$metathesekeys{$unikey}=1;
1.599     albertel 13376:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   13377: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 13378:     }
1.599     albertel 13379:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   13380: 	$metaentry{':'.$unikey}=
                   13381: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 13382:     }
                   13383: }
                   13384: 
1.261     albertel 13385: sub metadata_generate_part0 {
                   13386:     my ($metadata,$metacache,$uri) = @_;
                   13387:     my %allnames;
1.737     albertel 13388:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 13389: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 13390: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   13391: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 13392: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 13393: 	    $allnames{$name}=$part;
                   13394: 	  }
                   13395: 	}
                   13396:     }
                   13397:     foreach my $name (keys(%allnames)) {
                   13398:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 13399:       my $key=":parameter_0_$name";
1.261     albertel 13400:       $$metacache{"$key.part"}='0';
                   13401:       $$metacache{"$key.name"}=$name;
1.428     albertel 13402:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 13403: 					   $allnames{$name}.'_'.$name.
                   13404: 					   '.type'};
1.428     albertel 13405:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 13406: 			     '.display'};
1.644     www      13407:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 13408:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 13409:       $$metacache{"$key.display"}=$olddis;
                   13410:     }
1.71      www      13411: }
                   13412: 
1.764     albertel 13413: # ------------------------------------------------------ Devalidate title cache
                   13414: 
                   13415: sub devalidate_title_cache {
                   13416:     my ($url)=@_;
                   13417:     if (!$env{'request.course.id'}) { return; }
                   13418:     my $symb=&symbread($url);
                   13419:     if (!$symb) { return; }
                   13420:     my $key=$env{'request.course.id'}."\0".$symb;
                   13421:     &devalidate_cache_new('title',$key);
                   13422: }
                   13423: 
1.1014    droeschl 13424: # ------------------------------------------------- Get the title of a course
                   13425: 
                   13426: sub current_course_title {
                   13427:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   13428: }
1.301     www      13429: # ------------------------------------------------- Get the title of a resource
                   13430: 
                   13431: sub gettitle {
                   13432:     my $urlsymb=shift;
                   13433:     my $symb=&symbread($urlsymb);
1.534     albertel 13434:     if ($symb) {
1.620     albertel 13435: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 13436: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 13437: 	if (defined($cached)) { 
                   13438: 	    return $result;
                   13439: 	}
1.534     albertel 13440: 	my ($map,$resid,$url)=&decode_symb($symb);
                   13441: 	my $title='';
1.907     albertel 13442: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   13443: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   13444: 	} else {
                   13445: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   13446: 		    &GDBM_READER(),0640)) {
                   13447: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   13448: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   13449: 		untie(%bighash);
                   13450: 	    }
1.534     albertel 13451: 	}
                   13452: 	$title=~s/\&colon\;/\:/gs;
                   13453: 	if ($title) {
1.1159    www      13454: # Remember both $symb and $title for dynamic metadata
                   13455:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      13456:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      13457: # Cache this title and then return it
1.599     albertel 13458: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 13459: 	}
                   13460: 	$urlsymb=$url;
                   13461:     }
                   13462:     my $title=&metadata($urlsymb,'title');
                   13463:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   13464:     return $title;
1.301     www      13465: }
1.613     albertel 13466: 
1.614     albertel 13467: sub get_slot {
                   13468:     my ($which,$cnum,$cdom)=@_;
                   13469:     if (!$cnum || !$cdom) {
1.790     albertel 13470: 	(undef,my $courseid)=&whichuser();
1.620     albertel 13471: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   13472: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 13473:     }
1.703     albertel 13474:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   13475:     my %slotinfo;
                   13476:     if (exists($remembered{$key})) {
                   13477: 	$slotinfo{$which} = $remembered{$key};
                   13478:     } else {
                   13479: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   13480: 	&Apache::lonhomework::showhash(%slotinfo);
                   13481: 	my ($tmp)=keys(%slotinfo);
                   13482: 	if ($tmp=~/^error:/) { return (); }
                   13483: 	$remembered{$key} = $slotinfo{$which};
                   13484:     }
1.616     albertel 13485:     if (ref($slotinfo{$which}) eq 'HASH') {
                   13486: 	return %{$slotinfo{$which}};
                   13487:     }
                   13488:     return $slotinfo{$which};
1.614     albertel 13489: }
1.1150    raeburn  13490: 
                   13491: sub get_reservable_slots {
                   13492:     my ($cnum,$cdom,$uname,$udom) = @_;
                   13493:     my $now = time;
                   13494:     my $reservable_info;
                   13495:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   13496:     if (exists($remembered{$key})) {
                   13497:         $reservable_info = $remembered{$key};
                   13498:     } else {
                   13499:         my %resv;
                   13500:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   13501:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   13502:         $reservable_info = \%resv;
                   13503:         $remembered{$key} = $reservable_info;
                   13504:     }
                   13505:     return $reservable_info;
                   13506: }
                   13507: 
                   13508: sub get_course_slots {
                   13509:     my ($cnum,$cdom) = @_;
                   13510:     my $hashid=$cnum.':'.$cdom;
                   13511:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   13512:     if (defined($cached)) {
                   13513:         if (ref($result) eq 'HASH') {
                   13514:             return %{$result};
                   13515:         }
                   13516:     } else {
                   13517:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   13518:         my ($tmp) = keys(%slots);
                   13519:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  13520:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  13521:             return %slots;
                   13522:         }
                   13523:     }
                   13524:     return;
                   13525: }
                   13526: 
                   13527: sub devalidate_slots_cache {
                   13528:     my ($cnum,$cdom)=@_;
                   13529:     my $hashid=$cnum.':'.$cdom;
                   13530:     &devalidate_cache_new('allslots',$hashid);
                   13531: }
                   13532: 
1.1181    raeburn  13533: sub get_coursechange {
                   13534:     my ($cdom,$cnum) = @_;
                   13535:     if ($cdom eq '' || $cnum eq '') {
                   13536:         return unless ($env{'request.course.id'});
                   13537:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   13538:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   13539:     }
                   13540:     my $hashid=$cdom.'_'.$cnum;
                   13541:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   13542:     if ((defined($cached)) && ($change ne '')) {
                   13543:         return $change;
                   13544:     } else {
                   13545:         my %crshash;
                   13546:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   13547:         if ($crshash{'internal.contentchange'} eq '') {
                   13548:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13549:             if ($change eq '') {
                   13550:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13551:                 $change = $crshash{'internal.created'};
                   13552:             }
                   13553:         } else {
                   13554:             $change = $crshash{'internal.contentchange'};
                   13555:         }
                   13556:         my $cachetime = 600;
                   13557:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   13558:     }
                   13559:     return $change;
                   13560: }
                   13561: 
                   13562: sub devalidate_coursechange_cache {
                   13563:     my ($cnum,$cdom)=@_;
                   13564:     my $hashid=$cnum.':'.$cdom;
                   13565:     &devalidate_cache_new('crschange',$hashid);
                   13566: }
                   13567: 
1.31      www      13568: # ------------------------------------------------- Update symbolic store links
                   13569: 
                   13570: sub symblist {
                   13571:     my ($mapname,%newhash)=@_;
1.438     www      13572:     $mapname=&deversion(&declutter($mapname));
1.31      www      13573:     my %hash;
1.620     albertel 13574:     if (($env{'request.course.fn'}) && (%newhash)) {
                   13575:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 13576:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  13577: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 13578: 		next if ($url eq 'last_known'
                   13579: 			 && $env{'form.no_update_last_known'});
                   13580: 		$hash{declutter($url)}=&encode_symb($mapname,
                   13581: 						    $newhash{$url}->[1],
                   13582: 						    $newhash{$url}->[0]);
1.191     harris41 13583:             }
1.31      www      13584:             if (untie(%hash)) {
                   13585: 		return 'ok';
                   13586:             }
                   13587:         }
                   13588:     }
                   13589:     return 'error';
1.212     www      13590: }
                   13591: 
                   13592: # --------------------------------------------------------------- Verify a symb
                   13593: 
                   13594: sub symbverify {
1.1190    raeburn  13595:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      13596:     my $thisfn=$thisurl;
1.439     www      13597:     $thisfn=&declutter($thisfn);
1.215     www      13598: # direct jump to resource in page or to a sequence - will construct own symbs
                   13599:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   13600: # check URL part
1.409     www      13601:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      13602: 
1.431     www      13603:     unless ($url eq $thisfn) { return 0; }
1.213     www      13604: 
1.216     www      13605:     $symb=&symbclean($symb);
1.510     www      13606:     $thisurl=&deversion($thisurl);
1.439     www      13607:     $thisfn=&deversion($thisfn);
1.213     www      13608: 
                   13609:     my %bighash;
                   13610:     my $okay=0;
1.431     www      13611: 
1.620     albertel 13612:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13613:                             &GDBM_READER(),0640)) {
1.1032    raeburn  13614:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   13615:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  13616:             if ($map =~ m{^uploaded/.+\.page$}) {
                   13617:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   13618:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   13619:             }
                   13620:         }
                   13621:         my $ids;
1.1419    raeburn  13622:         if ($map =~ m{^uploaded/.+\.page$}) {
                   13623:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1204    raeburn  13624:         } else {
                   13625:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  13626:         }
1.1102    raeburn  13627:         unless ($ids) {
                   13628:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   13629:             $ids=$bighash{$idkey};
1.216     www      13630:         }
                   13631:         if ($ids) {
                   13632: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  13633:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  13634:                 $symb =~ s/\?.+$//;
1.1202    raeburn  13635:             }
1.800     albertel 13636: 	    foreach my $id (split(/\,/,$ids)) {
                   13637: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      13638:                if (
                   13639:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  13640:    eq $symb) {
                   13641:                    if (ref($encstate)) {
                   13642:                        $$encstate = $bighash{'encrypted_'.$id};
                   13643:                    }
1.620     albertel 13644: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  13645: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   13646:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  13647: 		       $okay=1;
1.1202    raeburn  13648:                        last;
1.582     albertel 13649: 		   }
                   13650: 	       }
1.216     www      13651: 	   }
                   13652:         }
1.213     www      13653: 	untie(%bighash);
                   13654:     }
                   13655:     return $okay;
1.31      www      13656: }
                   13657: 
1.210     www      13658: # --------------------------------------------------------------- Clean-up symb
                   13659: 
                   13660: sub symbclean {
                   13661:     my $symb=shift;
1.568     albertel 13662:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      13663: # remove version from map
                   13664:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      13665: 
1.210     www      13666: # remove version from URL
                   13667:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      13668: 
1.507     www      13669: # remove wrapper
                   13670: 
1.510     www      13671:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 13672:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      13673:     return $symb;
1.409     www      13674: }
                   13675: 
                   13676: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 13677: 
                   13678: sub encode_symb {
                   13679:     my ($map,$resid,$url)=@_;
                   13680:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   13681: }
1.409     www      13682: 
                   13683: sub decode_symb {
1.568     albertel 13684:     my $symb=shift;
                   13685:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   13686:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      13687:     return (&fixversion($map),$resid,&fixversion($url));
                   13688: }
                   13689: 
                   13690: sub fixversion {
                   13691:     my $fn=shift;
1.609     banghart 13692:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      13693:     my %bighash;
                   13694:     my $uri=&clutter($fn);
1.620     albertel 13695:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      13696: # is this cached?
1.599     albertel 13697:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      13698:     if (defined($cached)) { return $result; }
                   13699: # unfortunately not cached, or expired
1.620     albertel 13700:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      13701: 	    &GDBM_READER(),0640)) {
                   13702:  	if ($bighash{'version_'.$uri}) {
                   13703:  	    my $version=$bighash{'version_'.$uri};
1.444     www      13704:  	    unless (($version eq 'mostrecent') || 
                   13705: 		    ($version==&getversion($uri))) {
1.440     www      13706:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   13707:  	    }
                   13708:  	}
                   13709:  	untie %bighash;
1.413     www      13710:     }
1.599     albertel 13711:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      13712: }
                   13713: 
                   13714: sub deversion {
                   13715:     my $url=shift;
                   13716:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   13717:     return $url;
1.210     www      13718: }
                   13719: 
1.31      www      13720: # ------------------------------------------------------ Return symb list entry
                   13721: 
                   13722: sub symbread {
1.1424    raeburn  13723:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1427    raeburn  13724:         $ignoresymbdb,$noenccheck)=@_;
1.1265    raeburn  13725:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1427    raeburn  13726:     if (defined($env{$cache_str})) {
1.1424    raeburn  13727:         unless (ref($possibles) eq 'HASH') {
                   13728:             if ($ignorecachednull) {
                   13729:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   13730:             } else {
                   13731:                 return $env{$cache_str};
                   13732:             }
1.1282    raeburn  13733:         }
                   13734:     }
1.242     www      13735: # no filename provided? try from environment
1.1265    raeburn  13736:     unless ($thisfn) {
1.620     albertel 13737:         if ($env{'request.symb'}) {
1.1427    raeburn  13738:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 13739: 	}
1.620     albertel 13740: 	$thisfn=$env{'request.filename'};
1.44      www      13741:     }
1.569     albertel 13742:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13743: # is that filename actually a symb? Verify, clean, and return
                   13744:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13745: 	if (&symbverify($thisfn,$1)) {
1.1427    raeburn  13746: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13747: 	}
1.242     www      13748:     }
1.44      www      13749:     $thisfn=declutter($thisfn);
1.31      www      13750:     my %hash;
1.37      www      13751:     my %bighash;
                   13752:     my $syval='';
1.620     albertel 13753:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.1427    raeburn  13754:         unless ($ignoresymbdb) {
1.1424    raeburn  13755:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   13756:                           &GDBM_READER(),0640)) {
1.1487    raeburn  13757: 	        $syval=$hash{$thisfn};
1.1424    raeburn  13758:                 untie(%hash);
                   13759:             }
1.1427    raeburn  13760:             if ($syval && $checkforblock) {
                   13761:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1424    raeburn  13762:                 if (@blockers) {
                   13763:                     $syval='';
                   13764:                 }
                   13765:             }
1.37      www      13766:         }
                   13767: # ---------------------------------------------------------- There was an entry
                   13768:         if ($syval) {
1.601     albertel 13769: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13770: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13771: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13772: 		    #return $env{$cache_str}='';
1.601     albertel 13773: 		#}    
                   13774: 		#$syval.=$1;
                   13775: 	    #}
1.37      www      13776:         } else {
                   13777: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13778:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13779:                             &GDBM_READER(),0640)) {
1.37      www      13780: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13781:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13782:               unless ($ids) { 
                   13783:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13784:               }
                   13785:               unless ($ids) {
                   13786: # alias?
                   13787: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13788:               }
1.37      www      13789:               if ($ids) {
                   13790: # ------------------------------------------------------------------- Has ID(s)
                   13791:                  my @possibilities=split(/\,/,$ids);
1.39      www      13792:                  if ($#possibilities==0) {
                   13793: # ----------------------------------------------- There is only one possibility
1.37      www      13794: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13795: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13796: 						    $resid,$thisfn);
1.1282    raeburn  13797:                      if (ref($possibles) eq 'HASH') {
1.1424    raeburn  13798:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   13799:                              $possibles->{$syval} = 1;
                   13800:                          }
1.1282    raeburn  13801:                      }
                   13802:                      if ($checkforblock) {
1.1424    raeburn  13803:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1426    raeburn  13804:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1424    raeburn  13805:                              if (@blockers) {
                   13806:                                  $syval = '';
1.1425    raeburn  13807:                                  untie(%bighash);
                   13808:                                  return $env{$cache_str}='';
1.1424    raeburn  13809:                              }
1.1282    raeburn  13810:                          }
                   13811:                      }
                   13812:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      13813: # ------------------------------------------ There is more than one possibility
                   13814:                      my $realpossible=0;
1.800     albertel 13815:                      foreach my $id (@possibilities) {
                   13816: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  13817:                          my $canaccess;
                   13818:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13819:                              $canaccess = 1;
                   13820:                          } else { 
                   13821:                              $canaccess = &allowed('bre',$file);
                   13822:                          }
                   13823:                          if ($canaccess) {
                   13824:          		     my ($mapid,$resid)=split(/\./,$id);
                   13825:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13826:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13827: 						             $resid,$thisfn);
1.1424    raeburn  13828:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1426    raeburn  13829:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1282    raeburn  13830:                                  if ($checkforblock) {
1.1426    raeburn  13831:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1424    raeburn  13832:                                      if (@blockers > 0) {
                   13833:                                          $syval = '';
                   13834:                                      } else {
1.1282    raeburn  13835:                                          $syval = $poss_syval;
                   13836:                                          $realpossible++;
                   13837:                                      }
                   13838:                                  } else {
                   13839:                                      $syval = $poss_syval;
                   13840:                                      $realpossible++;
                   13841:                                  }
1.1424    raeburn  13842:                                  if ($syval) {
                   13843:                                      if (ref($possibles) eq 'HASH') {
                   13844:                                          $possibles->{$syval} = 1;
                   13845:                                      }
                   13846:                                  }
1.1282    raeburn  13847:                              }
1.39      www      13848: 			 }
1.191     harris41 13849:                      }
1.39      www      13850: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13851:                  } else {
                   13852:                      $syval='';
1.37      www      13853:                  }
                   13854: 	      }
1.1282    raeburn  13855:               untie(%bighash);
1.481     raeburn  13856:            }
1.31      www      13857:         }
1.62      www      13858:         if ($syval) {
1.1427    raeburn  13859: 	    return $env{$cache_str}=$syval;
1.62      www      13860:         }
1.31      www      13861:     }
1.949     raeburn  13862:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13863:     return $env{$cache_str}='';
1.31      www      13864: }
                   13865: 
                   13866: # ---------------------------------------------------------- Return random seed
                   13867: 
1.32      www      13868: sub numval {
                   13869:     my $txt=shift;
                   13870:     $txt=~tr/A-J/0-9/;
                   13871:     $txt=~tr/a-j/0-9/;
                   13872:     $txt=~tr/K-T/0-9/;
                   13873:     $txt=~tr/k-t/0-9/;
                   13874:     $txt=~tr/U-Z/0-5/;
                   13875:     $txt=~tr/u-z/0-5/;
                   13876:     $txt=~s/\D//g;
1.564     albertel 13877:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13878:     return int($txt);
1.368     albertel 13879: }
                   13880: 
1.484     albertel 13881: sub numval2 {
                   13882:     my $txt=shift;
                   13883:     $txt=~tr/A-J/0-9/;
                   13884:     $txt=~tr/a-j/0-9/;
                   13885:     $txt=~tr/K-T/0-9/;
                   13886:     $txt=~tr/k-t/0-9/;
                   13887:     $txt=~tr/U-Z/0-5/;
                   13888:     $txt=~tr/u-z/0-5/;
                   13889:     $txt=~s/\D//g;
                   13890:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13891:     my $total;
                   13892:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13893:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13894:     return int($total);
                   13895: }
                   13896: 
1.575     albertel 13897: sub numval3 {
                   13898:     use integer;
                   13899:     my $txt=shift;
                   13900:     $txt=~tr/A-J/0-9/;
                   13901:     $txt=~tr/a-j/0-9/;
                   13902:     $txt=~tr/K-T/0-9/;
                   13903:     $txt=~tr/k-t/0-9/;
                   13904:     $txt=~tr/U-Z/0-5/;
                   13905:     $txt=~tr/u-z/0-5/;
                   13906:     $txt=~s/\D//g;
                   13907:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13908:     my $total;
                   13909:     foreach my $val (@txts) { $total+=$val; }
                   13910:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13911:     return $total;
                   13912: }
                   13913: 
1.675     albertel 13914: sub digest {
                   13915:     my ($data)=@_;
                   13916:     my $digest=&Digest::MD5::md5($data);
                   13917:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13918:     my ($e,$f);
                   13919:     {
                   13920:         use integer;
                   13921:         $e=($a+$b);
                   13922:         $f=($c+$d);
                   13923:         if ($_64bit) {
                   13924:             $e=(($e<<32)>>32);
                   13925:             $f=(($f<<32)>>32);
                   13926:         }
                   13927:     }
                   13928:     if (wantarray) {
                   13929: 	return ($e,$f);
                   13930:     } else {
                   13931: 	my $g;
                   13932: 	{
                   13933: 	    use integer;
                   13934: 	    $g=($e+$f);
                   13935: 	    if ($_64bit) {
                   13936: 		$g=(($g<<32)>>32);
                   13937: 	    }
                   13938: 	}
                   13939: 	return $g;
                   13940:     }
                   13941: }
                   13942: 
1.368     albertel 13943: sub latest_rnd_algorithm_id {
1.675     albertel 13944:     return '64bit5';
1.366     albertel 13945: }
1.32      www      13946: 
1.503     albertel 13947: sub get_rand_alg {
                   13948:     my ($courseid)=@_;
1.790     albertel 13949:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13950:     if ($courseid) {
1.620     albertel 13951: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13952:     }
                   13953:     return &latest_rnd_algorithm_id();
                   13954: }
                   13955: 
1.562     albertel 13956: sub validCODE {
                   13957:     my ($CODE)=@_;
                   13958:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13959:     return 0;
                   13960: }
                   13961: 
1.491     albertel 13962: sub getCODE {
1.620     albertel 13963:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13964:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13965: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13966: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13967: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13968:     }
                   13969:     return undef;
                   13970: }
1.1133    foxr     13971: #
                   13972: #  Determines the random seed for a specific context:
                   13973: #
                   13974: # parameters:
                   13975: #   symb      - in course context the symb for the seed.
                   13976: #   course_id - The course id of the form domain_coursenum.
                   13977: #   domain    - Domain for the user.
                   13978: #   course    - Course for the user.
                   13979: #   cenv      - environment of the course.
                   13980: #
                   13981: # NOTE:
                   13982: #   All parameters are picked out of the environment if missing
                   13983: #   or not defined.
                   13984: #   If a symb cannot be determined the current time is used instead.
                   13985: #
                   13986: #  For a given well defined symb, courside, domain, username,
                   13987: #  and course environment, the seed is reproducible.
                   13988: #
1.31      www      13989: sub rndseed {
1.1133    foxr     13990:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13991:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13992:     if (!defined($symb)) {
1.366     albertel 13993: 	unless ($symb=$wsymb) { return time; }
                   13994:     }
1.1146    foxr     13995:     if (!defined $courseid) { 
                   13996: 	$courseid=$wcourseid; 
                   13997:     }
                   13998:     if (!defined $domain) { $domain=$wdomain; }
                   13999:     if (!defined $username) { $username=$wusername }
1.1133    foxr     14000: 
                   14001:     my $which;
                   14002:     if (defined($cenv->{'rndseed'})) {
                   14003: 	$which = $cenv->{'rndseed'};
                   14004:     } else {
                   14005: 	$which =&get_rand_alg($courseid);
                   14006:     }
1.491     albertel 14007:     if (defined(&getCODE())) {
1.1133    foxr     14008: 
1.675     albertel 14009: 	if ($which eq '64bit5') {
                   14010: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   14011: 	} elsif ($which eq '64bit4') {
1.575     albertel 14012: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   14013: 	} else {
                   14014: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   14015: 	}
1.675     albertel 14016:     } elsif ($which eq '64bit5') {
                   14017: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 14018:     } elsif ($which eq '64bit4') {
                   14019: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 14020:     } elsif ($which eq '64bit3') {
                   14021: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 14022:     } elsif ($which eq '64bit2') {
                   14023: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 14024:     } elsif ($which eq '64bit') {
                   14025: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   14026:     }
                   14027:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   14028: }
                   14029: 
                   14030: sub rndseed_32bit {
                   14031:     my ($symb,$courseid,$domain,$username)=@_;
                   14032:     {
                   14033: 	use integer;
                   14034: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   14035: 	my $symbseed=numval($symb) << 22;
                   14036: 	my $namechck=unpack("%32C*",$username) << 17;
                   14037: 	my $nameseed=numval($username) << 12;
                   14038: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   14039: 	my $courseseed=unpack("%32C*",$courseid);
                   14040: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 14041: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14042: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 14043: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 14044: 	return $num;
                   14045:     }
                   14046: }
                   14047: 
                   14048: sub rndseed_64bit {
                   14049:     my ($symb,$courseid,$domain,$username)=@_;
                   14050:     {
                   14051: 	use integer;
                   14052: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   14053: 	my $symbseed=numval($symb) << 10;
                   14054: 	my $namechck=unpack("%32S*",$username);
                   14055: 	
                   14056: 	my $nameseed=numval($username) << 21;
                   14057: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   14058: 	my $courseseed=unpack("%32S*",$courseid);
                   14059: 	
                   14060: 	my $num1=$symbchck+$symbseed+$namechck;
                   14061: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 14062: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14063: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 14064: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 14065: 	return "$num1,$num2";
1.155     albertel 14066:     }
1.366     albertel 14067: }
                   14068: 
1.443     albertel 14069: sub rndseed_64bit2 {
                   14070:     my ($symb,$courseid,$domain,$username)=@_;
                   14071:     {
                   14072: 	use integer;
                   14073: 	# strings need to be an even # of cahracters long, it it is odd the
                   14074:         # last characters gets thrown away
                   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;
1.501     albertel 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.803     albertel 14087: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 14088: 	return "$num1,$num2";
                   14089:     }
                   14090: }
                   14091: 
                   14092: sub rndseed_64bit3 {
                   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=numval2($symb) << 10;
                   14100: 	my $namechck=unpack("%32S*",$username.' ');
                   14101: 	
                   14102: 	my $nameseed=numval2($username) << 21;
1.443     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 :$num1:$num2:$_64bit");
1.564     albertel 14110: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      14111: 	
1.503     albertel 14112: 	return "$num1:$num2";
1.443     albertel 14113:     }
                   14114: }
                   14115: 
1.575     albertel 14116: sub rndseed_64bit4 {
                   14117:     my ($symb,$courseid,$domain,$username)=@_;
                   14118:     {
                   14119: 	use integer;
                   14120: 	# strings need to be an even # of cahracters long, it it is odd the
                   14121:         # last characters gets thrown away
                   14122: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   14123: 	my $symbseed=numval3($symb) << 10;
                   14124: 	my $namechck=unpack("%32S*",$username.' ');
                   14125: 	
                   14126: 	my $nameseed=numval3($username) << 21;
                   14127: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   14128: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14129: 	
                   14130: 	my $num1=$symbchck+$symbseed+$namechck;
                   14131: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 14132: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14133: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 14134: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      14135: 	
1.575     albertel 14136: 	return "$num1:$num2";
                   14137:     }
                   14138: }
                   14139: 
1.675     albertel 14140: sub rndseed_64bit5 {
                   14141:     my ($symb,$courseid,$domain,$username)=@_;
                   14142:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   14143:     return "$num1:$num2";
                   14144: }
                   14145: 
1.366     albertel 14146: sub rndseed_CODE_64bit {
                   14147:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 14148:     {
1.366     albertel 14149: 	use integer;
1.443     albertel 14150: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 14151: 	my $symbseed=numval2($symb);
1.491     albertel 14152: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   14153: 	my $CODEseed=numval(&getCODE());
1.443     albertel 14154: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 14155: 	my $num1=$symbseed+$CODEchck;
                   14156: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 14157: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   14158: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 14159: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   14160: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 14161: 	return "$num1:$num2";
1.366     albertel 14162:     }
                   14163: }
                   14164: 
1.575     albertel 14165: sub rndseed_CODE_64bit4 {
                   14166:     my ($symb,$courseid,$domain,$username)=@_;
                   14167:     {
                   14168: 	use integer;
                   14169: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   14170: 	my $symbseed=numval3($symb);
                   14171: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   14172: 	my $CODEseed=numval3(&getCODE());
                   14173: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14174: 	my $num1=$symbseed+$CODEchck;
                   14175: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 14176: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   14177: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 14178: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   14179: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   14180: 	return "$num1:$num2";
                   14181:     }
                   14182: }
                   14183: 
1.675     albertel 14184: sub rndseed_CODE_64bit5 {
                   14185:     my ($symb,$courseid,$domain,$username)=@_;
                   14186:     my $code = &getCODE();
                   14187:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   14188:     return "$num1:$num2";
                   14189: }
                   14190: 
1.366     albertel 14191: sub setup_random_from_rndseed {
                   14192:     my ($rndseed)=@_;
1.503     albertel 14193:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  14194:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   14195:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   14196:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   14197:         } else {
                   14198:             &Math::Random::random_set_seed($num1,$num2);
                   14199:         }
1.366     albertel 14200:     } else {
                   14201: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 14202:     }
1.36      albertel 14203: }
                   14204: 
1.474     albertel 14205: sub latest_receipt_algorithm_id {
1.835     albertel 14206:     return 'receipt3';
1.474     albertel 14207: }
                   14208: 
1.480     www      14209: sub recunique {
                   14210:     my $fucourseid=shift;
                   14211:     my $unique;
1.835     albertel 14212:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   14213: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 14214: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      14215:     } else {
                   14216: 	$unique=$perlvar{'lonReceipt'};
                   14217:     }
                   14218:     return unpack("%32C*",$unique);
                   14219: }
                   14220: 
                   14221: sub recprefix {
                   14222:     my $fucourseid=shift;
                   14223:     my $prefix;
1.835     albertel 14224:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   14225: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 14226: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      14227:     } else {
                   14228: 	$prefix=$perlvar{'lonHostID'};
                   14229:     }
                   14230:     return unpack("%32C*",$prefix);
                   14231: }
                   14232: 
1.76      www      14233: sub ireceipt {
1.474     albertel 14234:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 14235: 
                   14236:     my $return =&recprefix($fucourseid).'-';
                   14237: 
                   14238:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   14239: 	$env{'request.state'} eq 'construct') {
                   14240: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   14241: 	return $return;
                   14242:     }
                   14243: 
1.76      www      14244:     my $cuname=unpack("%32C*",$funame);
                   14245:     my $cudom=unpack("%32C*",$fudom);
                   14246:     my $cucourseid=unpack("%32C*",$fucourseid);
                   14247:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      14248:     my $cunique=&recunique($fucourseid);
1.474     albertel 14249:     my $cpart=unpack("%32S*",$part);
1.835     albertel 14250:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   14251: 
1.790     albertel 14252: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 14253: 			       
                   14254: 	$return.= ($cunique%$cuname+
                   14255: 		   $cunique%$cudom+
                   14256: 		   $cusymb%$cuname+
                   14257: 		   $cusymb%$cudom+
                   14258: 		   $cucourseid%$cuname+
                   14259: 		   $cucourseid%$cudom+
                   14260: 		   $cpart%$cuname+
                   14261: 		   $cpart%$cudom);
                   14262:     } else {
                   14263: 	$return.= ($cunique%$cuname+
                   14264: 		   $cunique%$cudom+
                   14265: 		   $cusymb%$cuname+
                   14266: 		   $cusymb%$cudom+
                   14267: 		   $cucourseid%$cuname+
                   14268: 		   $cucourseid%$cudom);
                   14269:     }
                   14270:     return $return;
1.76      www      14271: }
                   14272: 
                   14273: sub receipt {
1.474     albertel 14274:     my ($part)=@_;
1.790     albertel 14275:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 14276:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      14277: }
1.260     ng       14278: 
1.790     albertel 14279: sub whichuser {
                   14280:     my ($passedsymb)=@_;
                   14281:     my ($symb,$courseid,$domain,$name,$publicuser);
                   14282:     if (defined($env{'form.grade_symb'})) {
                   14283: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   14284: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   14285: 	if (!$allowed &&
                   14286: 	    exists($env{'request.course.sec'}) &&
                   14287: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   14288: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   14289: 			      '/'.$env{'request.course.sec'});
                   14290: 	}
                   14291: 	if ($allowed) {
                   14292: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   14293: 	    $courseid=$tmp_courseid;
                   14294: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   14295: 	    ($name)=&get_env_multiple('form.grade_username');
                   14296: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   14297: 	}
                   14298:     }
                   14299:     if (!$passedsymb) {
                   14300: 	$symb=&symbread();
                   14301:     } else {
                   14302: 	$symb=$passedsymb;
                   14303:     }
                   14304:     $courseid=$env{'request.course.id'};
                   14305:     $domain=$env{'user.domain'};
                   14306:     $name=$env{'user.name'};
                   14307:     if ($name eq 'public' && $domain eq 'public') {
                   14308: 	if (!defined($env{'form.username'})) {
                   14309: 	    $env{'form.username'}.=time.rand(10000000);
                   14310: 	}
                   14311: 	$name.=$env{'form.username'};
                   14312:     }
                   14313:     return ($symb,$courseid,$domain,$name,$publicuser);
                   14314: 
                   14315: }
                   14316: 
1.36      albertel 14317: # ------------------------------------------------------------ Serves up a file
1.472     albertel 14318: # returns either the contents of the file or 
                   14319: # -1 if the file doesn't exist
1.481     raeburn  14320: #
                   14321: # if the target is a file that was uploaded via DOCS, 
                   14322: # a check will be made to see if a current copy exists on the local server,
                   14323: # if it does this will be served, otherwise a copy will be retrieved from
                   14324: # the home server for the course and stored in /home/httpd/html/userfiles on
                   14325: # the local server.   
1.472     albertel 14326: 
1.36      albertel 14327: sub getfile {
1.538     albertel 14328:     my ($file) = @_;
1.609     banghart 14329:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 14330:     &repcopy($file);
                   14331:     return &readfile($file);
                   14332: }
                   14333: 
                   14334: sub repcopy_userfile {
                   14335:     my ($file)=@_;
1.1142    raeburn  14336:     my $londocroot = $perlvar{'lonDocRoot'};
                   14337:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  14338:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 14339:     my ($cdom,$cnum,$filename) = 
1.811     albertel 14340: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 14341:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   14342:     if (-e "$file") {
1.828     www      14343: # we already have a local copy, check it out
1.538     albertel 14344: 	my @fileinfo = stat($file);
1.828     www      14345: 	my $rtncode;
                   14346: 	my $info;
1.538     albertel 14347: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 14348: 	if ($lwpresp ne 'ok') {
1.828     www      14349: # there is no such file anymore, even though we had a local copy
1.482     albertel 14350: 	    if ($rtncode eq '404') {
1.538     albertel 14351: 		unlink($file);
1.482     albertel 14352: 	    }
                   14353: 	    return -1;
                   14354: 	}
                   14355: 	if ($info < $fileinfo[9]) {
1.828     www      14356: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  14357: 	    return 'ok';
1.828     www      14358: 	} else {
                   14359: # the file is outdated, get rid of it
                   14360: 	    unlink($file);
1.482     albertel 14361: 	}
1.828     www      14362:     }
                   14363: # one way or the other, at this point, we don't have the file
                   14364: # construct the correct path for the file
                   14365:     my @parts = ($cdom,$cnum); 
                   14366:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   14367: 	push @parts, split(/\//,$1);
                   14368:     }
                   14369:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   14370:     foreach my $part (@parts) {
                   14371: 	$path .= '/'.$part;
                   14372: 	if (!-e $path) {
                   14373: 	    mkdir($path,0770);
1.482     albertel 14374: 	}
                   14375:     }
1.828     www      14376: # now the path exists for sure
                   14377: # get a user agent
                   14378:     my $transferfile=$file.'.in.transfer';
                   14379: # FIXME: this should flock
                   14380:     if (-e $transferfile) { return 'ok'; }
                   14381:     my $request;
                   14382:     $uri=~s/^\///;
1.980     raeburn  14383:     my $homeserver = &homeserver($cnum,$cdom);
1.1398    raeburn  14384:     my $hostname = &hostname($homeserver);
1.980     raeburn  14385:     my $protocol = $protocol{$homeserver};
                   14386:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  14387:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345    raeburn  14388:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      14389: # did it work?
                   14390:     if ($response->is_error()) {
                   14391: 	unlink($transferfile);
                   14392: 	&logthis("Userfile repcopy failed for $uri");
                   14393: 	return -1;
                   14394:     }
                   14395: # worked, rename the transfer file
                   14396:     rename($transferfile,$file);
1.607     raeburn  14397:     return 'ok';
1.481     raeburn  14398: }
                   14399: 
1.517     albertel 14400: sub tokenwrapper {
                   14401:     my $uri=shift;
1.980     raeburn  14402:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 14403:     $uri=~s|^/||;
1.620     albertel 14404:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 14405:     my $token=$1;
1.552     albertel 14406:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   14407:     if ($udom && $uname && $file) {
                   14408: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  14409:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  14410:         my $homeserver = &homeserver($uname,$udom);
1.1397    raeburn  14411:         my $hostname = &hostname($homeserver);
1.980     raeburn  14412:         my $protocol = $protocol{$homeserver};
                   14413:         $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  14414:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 14415:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   14416:                                '&tokenissued='.$perlvar{'lonHostID'};
                   14417:     } else {
                   14418:         return '/adm/notfound.html';
                   14419:     }
                   14420: }
                   14421: 
1.828     www      14422: # call with reqtype HEAD: get last modification time
                   14423: # call with reqtype GET: get the file contents
                   14424: # Do not call this with reqtype GET for large files! It loads everything into memory
                   14425: #
1.481     raeburn  14426: sub getuploaded {
                   14427:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   14428:     $uri=~s/^\///;
1.980     raeburn  14429:     my $homeserver = &homeserver($cnum,$cdom);
1.1397    raeburn  14430:     my $hostname = &hostname($homeserver);
1.980     raeburn  14431:     my $protocol = $protocol{$homeserver};
                   14432:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  14433:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  14434:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  14435:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  14436:     $$rtncode = $response->code;
1.482     albertel 14437:     if (! $response->is_success()) {
                   14438: 	return 'failed';
                   14439:     }      
                   14440:     if ($reqtype eq 'HEAD') {
1.486     www      14441: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 14442:     } elsif ($reqtype eq 'GET') {
                   14443: 	$$info = $response->content;
1.472     albertel 14444:     }
1.482     albertel 14445:     return 'ok';
1.36      albertel 14446: }
                   14447: 
1.481     raeburn  14448: sub readfile {
                   14449:     my $file = shift;
                   14450:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   14451:     my $fh;
1.1359    raeburn  14452:     open($fh,"<",$file);
1.481     raeburn  14453:     my $a='';
1.800     albertel 14454:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  14455:     return $a;
                   14456: }
                   14457: 
1.36      albertel 14458: sub filelocation {
1.590     banghart 14459:     my ($dir,$file) = @_;
                   14460:     my $location;
                   14461:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 14462: 
                   14463:     if ($file =~ m-^/adm/-) {
                   14464: 	$file=~s-^/adm/wrapper/-/-;
                   14465: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   14466:     }
1.882     albertel 14467: 
1.1139    www      14468:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  14469:         $location = $file;
1.609     banghart 14470:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 14471:         my ($udom,$uname,$filename)=
1.811     albertel 14472:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 14473:         my $home=&homeserver($uname,$udom);
                   14474:         my $is_me=0;
                   14475:         my @ids=&current_machine_ids();
                   14476:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   14477:         if ($is_me) {
1.1117    foxr     14478:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 14479:         } else {
                   14480:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   14481:   	      $udom.'/'.$uname.'/'.$filename;
                   14482:         }
1.882     albertel 14483:     } elsif ($file =~ m-^/adm/-) {
                   14484: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 14485:     } else {
                   14486:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      14487:         $file=~s:^/(res|priv)/:/:;
                   14488:         my $space=$1;
1.590     banghart 14489:         if ( !( $file =~ m:^/:) ) {
                   14490:             $location = $dir. '/'.$file;
                   14491:         } else {
1.1142    raeburn  14492:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 14493:         }
1.59      albertel 14494:     }
1.590     banghart 14495:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 14496:     while ($location=~m{/\.\./}) {
                   14497: 	if ($location =~ m{/[^/]+/\.\./}) {
                   14498: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   14499: 	} else {
                   14500: 	    $location=~ s{/\.\./}{/}g;
                   14501: 	}
                   14502:     } #remove dir/..
1.590     banghart 14503:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   14504:     return $location;
1.46      www      14505: }
1.36      albertel 14506: 
1.46      www      14507: sub hreflocation {
                   14508:     my ($dir,$file)=@_;
1.980     raeburn  14509:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 14510: 	$file=filelocation($dir,$file);
1.700     albertel 14511:     } elsif ($file=~m-^/adm/-) {
                   14512: 	$file=~s-^/adm/wrapper/-/-;
                   14513: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 14514:     }
                   14515:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   14516: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   14517:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  14518: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   14519: 	        {/uploaded/$1/$2/}x;
1.46      www      14520:     }
1.913     albertel 14521:     if ($file=~ m{^/userfiles/}) {
                   14522: 	$file =~ s{^/userfiles/}{/uploaded/};
                   14523:     }
1.462     albertel 14524:     return $file;
1.465     albertel 14525: }
                   14526: 
1.1139    www      14527: 
                   14528: 
                   14529: 
                   14530: 
1.465     albertel 14531: sub current_machine_domains {
1.853     albertel 14532:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   14533: }
                   14534: 
                   14535: sub machine_domains {
                   14536:     my ($hostname) = @_;
1.465     albertel 14537:     my @domains;
1.838     albertel 14538:     my %hostname = &all_hostnames();
1.465     albertel 14539:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  14540: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 14541: 	if ($hostname eq $name) {
1.844     albertel 14542: 	    push(@domains,&host_domain($id));
1.465     albertel 14543: 	}
                   14544:     }
                   14545:     return @domains;
                   14546: }
                   14547: 
                   14548: sub current_machine_ids {
1.853     albertel 14549:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   14550: }
                   14551: 
                   14552: sub machine_ids {
                   14553:     my ($hostname) = @_;
                   14554:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 14555:     my @ids;
1.888     albertel 14556:     my %name_to_host = &all_names();
1.889     albertel 14557:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   14558: 	return @{ $name_to_host{$hostname} };
                   14559:     }
                   14560:     return;
1.31      www      14561: }
                   14562: 
1.824     raeburn  14563: sub additional_machine_domains {
                   14564:     my @domains;
1.1466    raeburn  14565:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
                   14566:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
                   14567:             while (my $line = <$fh>) {
                   14568:                 chomp($line);           
                   14569:                 $line =~ s/\s//g;
                   14570:                 push(@domains,$line);
                   14571:             }
                   14572:             close($fh);
                   14573:         }
1.824     raeburn  14574:     }
                   14575:     return @domains;
                   14576: }
                   14577: 
                   14578: sub default_login_domain {
                   14579:     my $domain = $perlvar{'lonDefDomain'};
                   14580:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   14581:     foreach my $posdom (&current_machine_domains(),
                   14582:                         &additional_machine_domains()) {
                   14583:         if (lc($posdom) eq lc($testdomain)) {
                   14584:             $domain=$posdom;
                   14585:             last;
                   14586:         }
                   14587:     }
                   14588:     return $domain;
                   14589: }
                   14590: 
1.1414    raeburn  14591: sub shared_institution {
1.1439    raeburn  14592:     my ($dom,$lonhost) = @_;
                   14593:     if ($lonhost eq '') {
                   14594:         $lonhost = $perlvar{'lonHostID'};
                   14595:     }
1.1414    raeburn  14596:     my $same_intdom;
1.1439    raeburn  14597:     my $hostintdom = &internet_dom($lonhost);
1.1414    raeburn  14598:     if ($hostintdom ne '') {
                   14599:         my %iphost = &get_iphost();
                   14600:         my $primary_id = &domain($dom,'primary');
                   14601:         my $primary_ip = &get_host_ip($primary_id);
                   14602:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   14603:             foreach my $id (@{$iphost{$primary_ip}}) {
                   14604:                 my $intdom = &internet_dom($id);
                   14605:                 if ($intdom eq $hostintdom) {
                   14606:                     $same_intdom = 1;
                   14607:                     last;
                   14608:                 }
                   14609:             }
                   14610:         }
                   14611:     }
                   14612:     return $same_intdom;
                   14613: }
                   14614: 
1.1398    raeburn  14615: sub uses_sts {
                   14616:     my ($ignore_cache) = @_;
                   14617:     my $lonhost = $perlvar{'lonHostID'};
                   14618:     my $hostname = &hostname($lonhost);
                   14619:     my $sts_on;
                   14620:     if ($protocol{$lonhost} eq 'https') {
                   14621:         my $cachetime = 12*3600;
                   14622:         if (!$ignore_cache) {
                   14623:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   14624:             if (defined($cached)) {
                   14625:                 return $sts_on;
                   14626:             }
                   14627:         }
                   14628:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   14629:         my $request=new HTTP::Request('HEAD',$url);
                   14630:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
                   14631:         if ($response->is_success) {
                   14632:             my $has_sts = $response->header('Strict-Transport-Security');
                   14633:             if ($has_sts eq '') {
                   14634:                 $sts_on = 0;
                   14635:             } else {
                   14636:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   14637:                     my $maxage = $1;
                   14638:                     if ($maxage) {
                   14639:                         $sts_on = 1;
                   14640:                     } else {
                   14641:                         $sts_on = 0;
                   14642:                     }
                   14643:                 } else {
                   14644:                     $sts_on = 0;
                   14645:                 }
                   14646:             }
                   14647:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   14648:         }
                   14649:     }
                   14650:     return;
                   14651: }
                   14652: 
1.1449    raeburn  14653: sub waf_allssl {
                   14654:     my ($host_name) = @_;
                   14655:     my $alias = &get_proxy_alias();
                   14656:     if ($host_name eq '') {
                   14657:         $host_name = $ENV{'SERVER_NAME'};
                   14658:     }
                   14659:     if (($host_name ne '') && ($alias eq $host_name)) {
                   14660:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   14661:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   14662:         if ($defdomdefaults{'waf_sslopt'}) {
                   14663:             return $defdomdefaults{'waf_sslopt'};
                   14664:         }
                   14665:     }
                   14666:     return;
                   14667: }
                   14668: 
1.1434    raeburn  14669: sub get_requestor_ip {
                   14670:     my ($r,$nolookup,$noproxy) = @_;
                   14671:     my $from_ip;
                   14672:     if (ref($r)) {
1.1447    raeburn  14673:         if ($r->can('useragent_ip')) {
                   14674:             if ($noproxy && $r->can('client_ip')) {
                   14675:                 $from_ip = $r->client_ip();
                   14676:             } else {
                   14677:                 $from_ip = $r->useragent_ip();
                   14678:             }
                   14679:         } elsif ($r->connection->can('remote_ip')) {
                   14680:             $from_ip = $r->connection->remote_ip();
                   14681:         } else {
                   14682:             $from_ip = $r->get_remote_host($nolookup);
                   14683:         }
1.1434    raeburn  14684:     } else {
                   14685:         $from_ip = $ENV{'REMOTE_ADDR'};
                   14686:     }
                   14687:     return $from_ip if ($noproxy); 
                   14688:     # Who controls proxy settings for server
                   14689:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14690:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   14691:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
1.1437    raeburn  14692:         if ($proxyinfo->{'vpnint'}) {
                   14693:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
1.1434    raeburn  14694:                 return $from_ip;
                   14695:             }
                   14696:         }
                   14697:         if ($proxyinfo->{'trusted'}) {
                   14698:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   14699:                 my $ipheader = $proxyinfo->{'ipheader'};
                   14700:                 my ($ip,$xfor);
                   14701:                 if (ref($r)) {
                   14702:                     if ($ipheader) {
                   14703:                         $ip = $r->headers_in->{$ipheader};
                   14704:                     }
                   14705:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   14706:                 } else {
                   14707:                     if ($ipheader) {
                   14708:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   14709:                     }
                   14710:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   14711:                 }
                   14712:                 if (($ip eq '') && ($xfor ne '')) {
                   14713:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   14714:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   14715:                             $ip = $poss_ip;
1.1435    raeburn  14716:                             last;
1.1434    raeburn  14717:                         }
                   14718:                     }
                   14719:                 }
                   14720:                 if ($ip ne '') {
                   14721:                     return $ip;
                   14722:                 }
                   14723:             }
                   14724:         }
                   14725:     }
                   14726:     return $from_ip;
                   14727: }
                   14728: 
                   14729: sub get_proxy_settings {
                   14730:     my ($dom_in_use) = @_;
                   14731:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   14732:     my $proxyinfo = {
                   14733:                        ipheader => $domdefaults{'waf_ipheader'},
                   14734:                        trusted  => $domdefaults{'waf_trusted'},
1.1437    raeburn  14735:                        vpnint   => $domdefaults{'waf_vpnint'},
1.1438    raeburn  14736:                        vpnext   => $domdefaults{'waf_vpnext'},
1.1449    raeburn  14737:                        sslopt   => $domdefaults{'waf_sslopt'},
1.1434    raeburn  14738:                     };
                   14739:     return $proxyinfo;
                   14740: }
                   14741: 
                   14742: sub ip_match {
                   14743:     my ($ip,$pattern_str) = @_;
                   14744:     $ip=Net::CIDR::cidrvalidate($ip);
                   14745:     if ($ip) {
                   14746:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   14747:     }
                   14748:     return;
                   14749: }
                   14750: 
                   14751: sub get_proxy_alias {
1.1450    raeburn  14752:     my ($lonid) = @_;
                   14753:     if ($lonid eq '') {
                   14754:         $lonid = $perlvar{'lonHostID'};
                   14755:     }
                   14756:     if (!defined(&hostname($lonid))) {
                   14757:         return;
                   14758:     }
                   14759:     if ($lonid ne '') {
                   14760:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
1.1434    raeburn  14761:         if ($cached) {
                   14762:             return $alias;
                   14763:         }
1.1450    raeburn  14764:         my $dom = &Apache::lonnet::host_domain($lonid);
1.1434    raeburn  14765:         if ($dom ne '') {
                   14766:             my $cachetime = 60*60*24;
                   14767:             my %domconfig =
1.1437    raeburn  14768:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14769:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14770:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
1.1450    raeburn  14771:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   14772:                 }
                   14773:             }
                   14774:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   14775:         }
                   14776:     }
                   14777:     return;
                   14778: }
                   14779: 
                   14780: sub use_proxy_alias {
                   14781:     my ($r,$lonid) = @_;
                   14782:     my $alias = &get_proxy_alias($lonid);
                   14783:     if ($alias) {
                   14784:         my $dom = &host_domain($lonid);
                   14785:         if ($dom ne '') {
1.1467    raeburn  14786:             my $proxyinfo = &get_proxy_settings($dom);
1.1450    raeburn  14787:             my ($vpnint,$remote_ip);
                   14788:             if (ref($proxyinfo) eq 'HASH') {
                   14789:                 $vpnint = $proxyinfo->{'vpnint'};
                   14790:                 if ($vpnint) {
                   14791:                     $remote_ip = &get_requestor_ip($r,1,1);
1.1434    raeburn  14792:                 }
                   14793:             }
1.1450    raeburn  14794:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   14795:                 return $alias;
                   14796:             }
1.1434    raeburn  14797:         }
                   14798:     }
                   14799:     return;
                   14800: }
                   14801: 
1.1474    raeburn  14802: sub alias_sso {
1.1467    raeburn  14803:     my ($lonid) = @_;
                   14804:     if ($lonid eq '') {
                   14805:         $lonid = $perlvar{'lonHostID'};
                   14806:     }
                   14807:     if (!defined(&hostname($lonid))) {
                   14808:         return;
                   14809:     }
                   14810:     if ($lonid ne '') {
                   14811:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
                   14812:         if ($cached) {
                   14813:             return $use_alias;
                   14814:         }
                   14815:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14816:         if ($dom ne '') {
                   14817:             my $cachetime = 60*60*24;
                   14818:             my %domconfig =
                   14819:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14820:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14821:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
                   14822:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
                   14823:                 }
                   14824:             }
                   14825:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
                   14826:         }
                   14827:     }
                   14828:     return;
                   14829: }
                   14830: 
1.1465    raeburn  14831: sub get_saml_landing {
                   14832:     my ($lonid) = @_;
                   14833:     if ($lonid eq '') {
                   14834:         my $defdom = &default_login_domain();
                   14835:         my @hosts = &current_machine_ids();
                   14836:         if (@hosts > 1) {
                   14837:             foreach my $hostid (@hosts) {
                   14838:                 if (&host_domain($hostid) eq $defdom) {
                   14839:                     $lonid = $hostid;
                   14840:                     last;
                   14841:                 }
                   14842:             }
                   14843:         } else {
                   14844:             $lonid = $perlvar{'lonHostID'};
                   14845:         }
                   14846:         if ($lonid) {
                   14847:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
                   14848:                 return;
                   14849:             }
                   14850:         } else {
                   14851:             return;
                   14852:         }
                   14853:     } elsif (!defined(&hostname($lonid))) {
                   14854:         return;
                   14855:     }
                   14856:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   14857:     if ($cached) {
                   14858:         return $landing;
                   14859:     }
                   14860:     my $dom = &Apache::lonnet::host_domain($lonid);
                   14861:     if ($dom ne '') {
                   14862:         my $cachetime = 60*60*24;
                   14863:         my %domconfig =
                   14864:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
                   14865:         if (ref($domconfig{'login'}) eq 'HASH') {
                   14866:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   14867:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   14868:                     $landing = 1;
                   14869:                 }
                   14870:             }
                   14871:         }
                   14872:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   14873:     }
                   14874:     return;
                   14875: }
                   14876: 
1.31      www      14877: # ------------------------------------------------------------- Declutters URLs
                   14878: 
                   14879: sub declutter {
                   14880:     my $thisfn=shift;
1.569     albertel 14881:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  14882:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   14883:         $thisfn=~s{^/home/httpd/html}{};
                   14884:     }
1.31      www      14885:     $thisfn=~s/^\///;
1.697     albertel 14886:     $thisfn=~s|^adm/wrapper/||;
                   14887:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      14888:     $thisfn=~s/^res\///;
1.1172    bisitz   14889:     $thisfn=~s/^priv\///;
1.1032    raeburn  14890:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   14891:         $thisfn=~s/\?.+$//;
                   14892:     }
1.268     www      14893:     return $thisfn;
                   14894: }
                   14895: 
                   14896: # ------------------------------------------------------------- Clutter up URLs
                   14897: 
                   14898: sub clutter {
                   14899:     my $thisfn='/'.&declutter(shift);
1.887     albertel 14900:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 14901: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      14902:        $thisfn='/res'.$thisfn; 
                   14903:     }
1.1031    raeburn  14904:     if ($thisfn !~m|^/adm|) {
                   14905: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 14906: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 14907: 	} else {
                   14908: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   14909: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 14910: 	    if ($embstyle eq 'ssi'
                   14911: 		|| ($embstyle eq 'hdn')
                   14912: 		|| ($embstyle eq 'rat')
                   14913: 		|| ($embstyle eq 'prv')
                   14914: 		|| ($embstyle eq 'ign')) {
                   14915: 		#do nothing with these
                   14916: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 14917: 		|| ($embstyle eq 'emb')
                   14918: 		|| ($embstyle eq 'wrp')) {
                   14919: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 14920: 	    } elsif ($embstyle eq 'unk'
                   14921: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 14922: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 14923: 	    } else {
1.718     www      14924: #		&logthis("Got a blank emb style");
1.695     albertel 14925: 	    }
1.694     albertel 14926: 	}
1.1343    raeburn  14927:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  14928:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 14929:     }
1.31      www      14930:     return $thisfn;
1.12      www      14931: }
                   14932: 
1.787     albertel 14933: sub clutter_with_no_wrapper {
                   14934:     my $uri = &clutter(shift);
                   14935:     if ($uri =~ m-^/adm/-) {
                   14936: 	$uri =~ s-^/adm/wrapper/-/-;
                   14937: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14938:     }
                   14939:     return $uri;
                   14940: }
                   14941: 
1.557     albertel 14942: sub freeze_escape {
                   14943:     my ($value)=@_;
                   14944:     if (ref($value)) {
                   14945: 	$value=&nfreeze($value);
                   14946: 	return '__FROZEN__'.&escape($value);
                   14947:     }
                   14948:     return &escape($value);
                   14949: }
                   14950: 
1.11      www      14951: 
1.557     albertel 14952: sub thaw_unescape {
                   14953:     my ($value)=@_;
                   14954:     if ($value =~ /^__FROZEN__/) {
                   14955: 	substr($value,0,10,undef);
                   14956: 	$value=&unescape($value);
                   14957: 	return &thaw($value);
                   14958:     }
                   14959:     return &unescape($value);
                   14960: }
                   14961: 
1.436     albertel 14962: sub correct_line_ends {
                   14963:     my ($result)=@_;
                   14964:     $$result =~s/\r\n/\n/mg;
                   14965:     $$result =~s/\r/\n/mg;
1.415     albertel 14966: }
1.1       albertel 14967: # ================================================================ Main Program
                   14968: 
1.184     www      14969: sub goodbye {
1.204     albertel 14970:    &logthis("Starting Shut down");
1.443     albertel 14971: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14972:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14973: #converted
1.599     albertel 14974: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14975:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14976: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   14977: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 14978: #1.1 only
1.870     albertel 14979: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   14980: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   14981: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   14982: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   14983:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 14984:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   14985:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      14986:    &flushcourselogs();
                   14987:    &logthis("Shutting down");
                   14988: }
                   14989: 
1.852     albertel 14990: sub get_dns {
1.1210    raeburn  14991:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 14992:     if (!$ignore_cache) {
                   14993: 	my ($content,$cached)=
                   14994: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   14995: 	if ($cached) {
1.1210    raeburn  14996: 	    &$func($content,$hashref);
1.869     albertel 14997: 	    return;
                   14998: 	}
                   14999:     }
                   15000: 
                   15001:     my %alldns;
1.1379    raeburn  15002:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   15003:         foreach my $dns (<$config>) {
                   15004: 	    next if ($dns !~ /^\^(\S*)/x);
                   15005:             my $line = $1;
                   15006:             my ($host,$protocol) = split(/:/,$line);
                   15007:             if ($protocol ne 'https') {
                   15008:                 $protocol = 'http';
                   15009:             }
                   15010: 	    $alldns{$host} = $protocol;
1.979     raeburn  15011:         }
1.1379    raeburn  15012:         close($config);
1.869     albertel 15013:     }
                   15014:     while (%alldns) {
1.1263    raeburn  15015: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1456    raeburn  15016:         my ($contents,@content);
                   15017:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   15018:             my $command = (split('/',$url))[3];
                   15019:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   15020:             delete($alldns{$dns});
                   15021:             next if (($dir eq '') || ($file eq ''));
                   15022:             if (open(my $config,'<',"$dir/$file")) {
1.1457    raeburn  15023:                 @content = <$config>;
1.1456    raeburn  15024:                 close($config);
                   15025:             }
                   15026:             if ($url eq '/adm/dns/loncapaCRL') {
                   15027:                 $contents = join('',@content);
                   15028:             }
                   15029:         } else {
                   15030: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   15031:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
                   15032:             delete($alldns{$dns});
                   15033: 	    next if ($response->is_error());
                   15034:             if ($url eq '/adm/dns/loncapaCRL') {
                   15035:                 $contents = $response->content;
                   15036:             } else {
                   15037:                 @content = split("\n",$response->content);
                   15038:             }
                   15039:         }
1.1379    raeburn  15040:         if ($url eq '/adm/dns/loncapaCRL') {
1.1456    raeburn  15041:             return &$func($contents);
1.1379    raeburn  15042:         } else {
                   15043: 	    unless ($nocache) {
                   15044: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   15045: 	    }
                   15046: 	    &$func(\@content,$hashref);
                   15047:             return;
                   15048:         }
                   15049:     }
                   15050:     my $which = (split('/',$url,4))[3];
                   15051:     if ($which eq 'loncapaCRL') {
                   15052:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   15053:         if (-e $diskfile) {
                   15054:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   15055:         } else {
                   15056:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   15057:         }
                   15058:     } else {
                   15059:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   15060:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   15061:             my @content = <$config>;
                   15062:             close($config);
                   15063:             &$func(\@content,$hashref);
                   15064:         }
1.852     albertel 15065:     }
1.1210    raeburn  15066:     return;
                   15067: }
                   15068: 
                   15069: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  15070: sub parse_dns_checksums_tab {
1.1210    raeburn  15071:     my ($lines,$hashref) = @_;
1.1264    raeburn  15072:     my $lonhost = $perlvar{'lonHostID'};
                   15073:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  15074:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  15075:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   15076:     my $webconfdir = '/etc/httpd/conf';
                   15077:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   15078:         $webconfdir = '/etc/apache2';
                   15079:     } elsif ($distro =~ /^sles(\d+)$/) {
                   15080:         if ($1 >= 10) {
                   15081:             $webconfdir = '/etc/apache2';
                   15082:         }
                   15083:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   15084:         if ($1 >= 10.0) {
                   15085:             $webconfdir = '/etc/apache2';
                   15086:         }
                   15087:     }
1.1210    raeburn  15088:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   15089:     my (%chksum,%revnum);
                   15090:     if (ref($lines) eq 'ARRAY') {
                   15091:         chomp(@{$lines});
1.1238    raeburn  15092:         my $version = shift(@{$lines});
                   15093:         if ($version eq $release) {  
1.1210    raeburn  15094:             foreach my $line (@{$lines}) {
1.1238    raeburn  15095:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  15096:                 if ($file =~ m{^/etc/httpd/conf}) {
                   15097:                     if ($webconfdir eq '/etc/apache2') {
                   15098:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   15099:                     }
                   15100:                 }
1.1238    raeburn  15101:                 $chksum{$file} = $shasum;
                   15102:                 $revnum{$file} = $version;
1.1210    raeburn  15103:             }
                   15104:             if (ref($hashref) eq 'HASH') {
                   15105:                 %{$hashref} = (
                   15106:                                 sums     => \%chksum,
                   15107:                                 versions => \%revnum,
                   15108:                               );
                   15109:             }
                   15110:         }
                   15111:     }
1.869     albertel 15112:     return;
1.852     albertel 15113: }
1.1210    raeburn  15114: 
                   15115: sub fetch_dns_checksums {
1.1238    raeburn  15116:     my %checksums;
                   15117:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  15118:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  15119:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   15120:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  15121:              \%checksums);
1.1210    raeburn  15122:     return \%checksums;
                   15123: }
                   15124: 
1.1379    raeburn  15125: sub fetch_crl_pemfile {
                   15126:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   15127: }
                   15128: 
                   15129: sub save_crl_pem {
1.1456    raeburn  15130:     my ($content) = @_;
1.1380    raeburn  15131:     my ($msg,$hadchanges);
1.1456    raeburn  15132:     if ($content ne '') {
1.1379    raeburn  15133:         my $now = time;
                   15134:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   15135:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   15136:         if (open(my $fh,'>',"$tmpcrl")) {
1.1456    raeburn  15137:             print $fh $content;
1.1379    raeburn  15138:             close($fh);
                   15139:             if (-e $lonca) {
                   15140:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   15141:                     my $check = <PIPE>;
                   15142:                     close(PIPE);
                   15143:                     chomp($check);
                   15144:                     if ($check eq 'verify OK') {
                   15145:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  15146:                         my $backup;
1.1379    raeburn  15147:                         if (-e $dest) {
1.1380    raeburn  15148:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   15149:                                 $backup = 'ok';
                   15150:                             }
1.1379    raeburn  15151:                         }
                   15152:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   15153:                             $msg = 'ok';
1.1380    raeburn  15154:                             if ($backup) {
                   15155:                                 my (%oldnums,%newnums);
                   15156:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   15157:                                     while (<PIPE>) {
                   15158:                                         $oldnums{(split(/:/))[1]} = 1;
                   15159:                                     }
                   15160:                                     close(PIPE);
                   15161:                                 }
                   15162:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   15163:                                     while(<PIPE>) {
                   15164:                                         $newnums{(split(/:/))[1]} = 1;
                   15165:                                     }
                   15166:                                     close(PIPE);
                   15167:                                 }
                   15168:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   15169:                                     unless (exists($oldnums{$key})) {
                   15170:                                         $hadchanges = 1;
                   15171:                                         last;
                   15172:                                     }
                   15173:                                 }
                   15174:                                 unless ($hadchanges) {
                   15175:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   15176:                                         unless (exists($newnums{$key})) {
                   15177:                                             $hadchanges = 1;
                   15178:                                             last;
                   15179:                                         }
                   15180:                                     }
                   15181:                                 }
                   15182:                             }
1.1379    raeburn  15183:                         }
                   15184:                     } else {
                   15185:                         unlink($tmpcrl);
                   15186:                     }
                   15187:                 } else {
                   15188:                     unlink($tmpcrl);
                   15189:                 }
                   15190:             } else {
                   15191:                 unlink($tmpcrl);
                   15192:             }
                   15193:         }
                   15194:     }
1.1380    raeburn  15195:     return ($msg,$hadchanges);
1.1379    raeburn  15196: }
                   15197: 
1.1456    raeburn  15198: sub parse_getdns_url {
                   15199:     my ($command,$url) = @_;
                   15200:     my $dir = $perlvar{'lonTabDir'};
                   15201:     my $file;
                   15202:     if ($command eq 'hosts') {
                   15203:         $file = 'dns_hosts.tab';
                   15204:     } elsif ($command eq 'domain') {
                   15205:         $file = 'dns_domain.tab';
                   15206:     } elsif ($command eq 'checksums') {
                   15207:         my $version = (split('/',$url))[4];
                   15208:         $file = "dns_checksums/$version.tab",
                   15209:     } elsif ($command eq 'loncapaCRL') {
                   15210:         $dir = $perlvar{'lonCertificateDirectory'};
                   15211:         $file = $perlvar{'lonnetCertRevocationList'};
                   15212:     }
                   15213:     return ($dir,$file);
                   15214: }
                   15215: 
1.327     albertel 15216: # ------------------------------------------------------------ Read domain file
                   15217: {
1.852     albertel 15218:     my $loaded;
1.846     albertel 15219:     my %domain;
                   15220: 
1.852     albertel 15221:     sub parse_domain_tab {
                   15222: 	my ($lines) = @_;
                   15223: 	foreach my $line (@$lines) {
                   15224: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      15225: 
1.846     albertel 15226: 	    chomp($line);
1.852     albertel 15227: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 15228: 	    my %this_domain;
                   15229: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   15230: 			       'lang_def', 'city', 'longi', 'lati',
                   15231: 			       'primary') {
                   15232: 		$this_domain{$field} = shift(@elements);
                   15233: 	    }
                   15234: 	    $domain{$name} = \%this_domain;
1.852     albertel 15235: 	}
                   15236:     }
1.864     albertel 15237: 
                   15238:     sub reset_domain_info {
                   15239: 	undef($loaded);
                   15240: 	undef(%domain);
                   15241:     }
                   15242: 
1.852     albertel 15243:     sub load_domain_tab {
1.1293    raeburn  15244: 	my ($ignore_cache,$nocache) = @_;
                   15245: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 15246: 	my $fh;
1.1359    raeburn  15247: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 15248: 	    my @lines = <$fh>;
                   15249: 	    &parse_domain_tab(\@lines);
1.448     albertel 15250: 	}
1.852     albertel 15251: 	close($fh);
                   15252: 	$loaded = 1;
1.327     albertel 15253:     }
1.846     albertel 15254: 
                   15255:     sub domain {
1.852     albertel 15256: 	&load_domain_tab() if (!$loaded);
                   15257: 
1.846     albertel 15258: 	my ($name,$what) = @_;
                   15259: 	return if ( !exists($domain{$name}) );
                   15260: 
                   15261: 	if (!$what) {
                   15262: 	    return $domain{$name}{'description'};
                   15263: 	}
                   15264: 	return $domain{$name}{$what};
                   15265:     }
1.974     raeburn  15266: 
                   15267:     sub domain_info {
                   15268:         &load_domain_tab() if (!$loaded);
                   15269:         return %domain;
                   15270:     }
                   15271: 
1.327     albertel 15272: }
                   15273: 
                   15274: 
1.1       albertel 15275: # ------------------------------------------------------------- Read hosts file
                   15276: {
1.838     albertel 15277:     my %hostname;
1.844     albertel 15278:     my %hostdom;
1.845     albertel 15279:     my %libserv;
1.852     albertel 15280:     my $loaded;
1.888     albertel 15281:     my %name_to_host;
1.1074    raeburn  15282:     my %internetdom;
1.1107    raeburn  15283:     my %LC_dns_serv;
1.852     albertel 15284: 
                   15285:     sub parse_hosts_tab {
                   15286: 	my ($file) = @_;
                   15287: 	foreach my $configline (@$file) {
                   15288: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  15289:             chomp($configline);
                   15290: 	    if ($configline =~ /^\^/) {
                   15291:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   15292:                     $LC_dns_serv{$1} = 1;
                   15293:                 }
                   15294:                 next;
                   15295:             }
1.1074    raeburn  15296: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 15297: 	    $name=~s/\s//g;
                   15298: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  15299:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   15300:                     my $curr = $hostname{$id};
                   15301:                     my $skip;
                   15302:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   15303:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   15304:                             $skip = 1;
                   15305:                         } else {
                   15306:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   15307:                         }
                   15308:                     }
                   15309:                     unless ($skip) {
                   15310:                         push(@{$name_to_host{$name}},$id);
                   15311:                     }
                   15312:                 } else {
                   15313:                     push(@{$name_to_host{$name}},$id);
                   15314:                 }
1.852     albertel 15315: 		$hostname{$id}=$name;
                   15316: 		$hostdom{$id}=$domain;
                   15317: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  15318:                 if (defined($protocol)) {
                   15319:                     if ($protocol eq 'https') {
                   15320:                         $protocol{$id} = $protocol;
                   15321:                     } else {
                   15322:                         $protocol{$id} = 'http'; 
                   15323:                     }
1.968     raeburn  15324:                 } else {
1.969     raeburn  15325:                     $protocol{$id} = 'http';
1.968     raeburn  15326:                 }
1.1074    raeburn  15327:                 if (defined($intdom)) {
                   15328:                     $internetdom{$id} = $intdom;
                   15329:                 }
1.852     albertel 15330: 	    }
                   15331: 	}
                   15332:     }
1.864     albertel 15333:     
                   15334:     sub reset_hosts_info {
1.897     albertel 15335: 	&purge_remembered();
1.864     albertel 15336: 	&reset_domain_info();
                   15337: 	&reset_hosts_ip_info();
1.1339    raeburn  15338:         undef(%internetdom);
1.892     albertel 15339: 	undef(%name_to_host);
1.864     albertel 15340: 	undef(%hostname);
                   15341: 	undef(%hostdom);
                   15342: 	undef(%libserv);
                   15343: 	undef($loaded);
                   15344:     }
1.1       albertel 15345: 
1.852     albertel 15346:     sub load_hosts_tab {
1.1293    raeburn  15347: 	my ($ignore_cache,$nocache) = @_;
                   15348: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  15349: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 15350: 	my @config = <$config>;
                   15351: 	&parse_hosts_tab(\@config);
                   15352: 	close($config);
                   15353: 	$loaded=1;
1.1       albertel 15354:     }
1.852     albertel 15355: 
1.838     albertel 15356:     sub hostname {
1.852     albertel 15357: 	&load_hosts_tab() if (!$loaded);
                   15358: 
1.838     albertel 15359: 	my ($lonid) = @_;
                   15360: 	return $hostname{$lonid};
                   15361:     }
1.845     albertel 15362: 
1.838     albertel 15363:     sub all_hostnames {
1.852     albertel 15364: 	&load_hosts_tab() if (!$loaded);
                   15365: 
1.838     albertel 15366: 	return %hostname;
                   15367:     }
1.845     albertel 15368: 
1.888     albertel 15369:     sub all_names {
1.1293    raeburn  15370:         my ($ignore_cache,$nocache) = @_;
                   15371: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 15372: 
                   15373: 	return %name_to_host;
                   15374:     }
                   15375: 
1.974     raeburn  15376:     sub all_host_domain {
                   15377:         &load_hosts_tab() if (!$loaded);
                   15378:         return %hostdom;
                   15379:     }
                   15380: 
1.1339    raeburn  15381:     sub all_host_intdom {
                   15382:         &load_hosts_tab() if (!$loaded);
                   15383:         return %internetdom;
                   15384:     }
                   15385: 
1.845     albertel 15386:     sub is_library {
1.852     albertel 15387: 	&load_hosts_tab() if (!$loaded);
                   15388: 
1.845     albertel 15389: 	return exists($libserv{$_[0]});
                   15390:     }
                   15391: 
                   15392:     sub all_library {
1.852     albertel 15393: 	&load_hosts_tab() if (!$loaded);
                   15394: 
1.845     albertel 15395: 	return %libserv;
                   15396:     }
                   15397: 
1.1062    droeschl 15398:     sub unique_library {
                   15399: 	#2x reverse removes all hostnames that appear more than once
                   15400:         my %unique = reverse &all_library();
                   15401:         return reverse %unique;
                   15402:     }
                   15403: 
1.841     albertel 15404:     sub get_servers {
1.852     albertel 15405: 	&load_hosts_tab() if (!$loaded);
                   15406: 
1.841     albertel 15407: 	my ($domain,$type) = @_;
                   15408: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   15409: 	                                          : %hostname;
                   15410: 	my %result;
1.842     albertel 15411: 	if (ref($domain) eq 'ARRAY') {
                   15412: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 15413: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 15414: 		    $result{$host} = $hostname;
                   15415: 		}
                   15416: 	    }
                   15417: 	} else {
                   15418: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   15419: 		if ($hostdom{$host} eq $domain) {
                   15420: 		    $result{$host} = $hostname;
                   15421: 		}
1.841     albertel 15422: 	    }
                   15423: 	}
                   15424: 	return %result;
                   15425:     }
1.845     albertel 15426: 
1.1062    droeschl 15427:     sub get_unique_servers {
                   15428:         my %unique = reverse &get_servers(@_);
                   15429: 	return reverse %unique;
                   15430:     }
                   15431: 
1.844     albertel 15432:     sub host_domain {
1.852     albertel 15433: 	&load_hosts_tab() if (!$loaded);
                   15434: 
1.844     albertel 15435: 	my ($lonid) = @_;
                   15436: 	return $hostdom{$lonid};
                   15437:     }
                   15438: 
1.841     albertel 15439:     sub all_domains {
1.852     albertel 15440: 	&load_hosts_tab() if (!$loaded);
                   15441: 
1.841     albertel 15442: 	my %seen;
                   15443: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   15444: 	return @uniq;
                   15445:     }
1.1074    raeburn  15446: 
                   15447:     sub internet_dom {
                   15448:         &load_hosts_tab() if (!$loaded);
                   15449: 
                   15450:         my ($lonid) = @_;
                   15451:         return $internetdom{$lonid};
                   15452:     }
1.1107    raeburn  15453: 
                   15454:     sub is_LC_dns {
                   15455:         &load_hosts_tab() if (!$loaded);
                   15456: 
                   15457:         my ($hostname) = @_;
                   15458:         return exists($LC_dns_serv{$hostname});
                   15459:     }
                   15460: 
1.1       albertel 15461: }
                   15462: 
1.847     albertel 15463: { 
                   15464:     my %iphost;
1.856     albertel 15465:     my %name_to_ip;
                   15466:     my %lonid_to_ip;
1.869     albertel 15467: 
1.847     albertel 15468:     sub get_hosts_from_ip {
                   15469: 	my ($ip) = @_;
                   15470: 	my %iphosts = &get_iphost();
                   15471: 	if (ref($iphosts{$ip})) {
                   15472: 	    return @{$iphosts{$ip}};
                   15473: 	}
                   15474: 	return;
1.839     albertel 15475:     }
1.864     albertel 15476:     
                   15477:     sub reset_hosts_ip_info {
                   15478: 	undef(%iphost);
                   15479: 	undef(%name_to_ip);
                   15480: 	undef(%lonid_to_ip);
                   15481:     }
1.856     albertel 15482: 
                   15483:     sub get_host_ip {
                   15484: 	my ($lonid) = @_;
                   15485: 	if (exists($lonid_to_ip{$lonid})) {
                   15486: 	    return $lonid_to_ip{$lonid};
                   15487: 	}
                   15488: 	my $name=&hostname($lonid);
                   15489:    	my $ip = gethostbyname($name);
                   15490: 	return if (!$ip || length($ip) ne 4);
                   15491: 	$ip=inet_ntoa($ip);
                   15492: 	$name_to_ip{$name}   = $ip;
                   15493: 	$lonid_to_ip{$lonid} = $ip;
                   15494: 	return $ip;
                   15495:     }
1.847     albertel 15496:     
                   15497:     sub get_iphost {
1.1293    raeburn  15498: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 15499: 
1.869     albertel 15500: 	if (!$ignore_cache) {
                   15501: 	    if (%iphost) {
                   15502: 		return %iphost;
                   15503: 	    }
                   15504: 	    my ($ip_info,$cached)=
                   15505: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   15506: 	    if ($cached) {
                   15507: 		%iphost      = %{$ip_info->[0]};
                   15508: 		%name_to_ip  = %{$ip_info->[1]};
                   15509: 		%lonid_to_ip = %{$ip_info->[2]};
                   15510: 		return %iphost;
                   15511: 	    }
                   15512: 	}
1.894     albertel 15513: 
                   15514: 	# get yesterday's info for fallback
                   15515: 	my %old_name_to_ip;
                   15516: 	my ($ip_info,$cached)=
                   15517: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   15518: 	if ($cached) {
                   15519: 	    %old_name_to_ip = %{$ip_info->[1]};
                   15520: 	}
                   15521: 
1.1293    raeburn  15522: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 15523: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 15524: 	    my $ip;
                   15525: 	    if (!exists($name_to_ip{$name})) {
                   15526: 		$ip = gethostbyname($name);
                   15527: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 15528: 		    if (defined($old_name_to_ip{$name})) {
                   15529: 			$ip = $old_name_to_ip{$name};
                   15530: 			&logthis("Can't find $name defaulting to old $ip");
                   15531: 		    } else {
                   15532: 			&logthis("Name $name no IP found");
                   15533: 			next;
                   15534: 		    }
                   15535: 		} else {
                   15536: 		    $ip=inet_ntoa($ip);
1.847     albertel 15537: 		}
                   15538: 		$name_to_ip{$name} = $ip;
                   15539: 	    } else {
                   15540: 		$ip = $name_to_ip{$name};
1.653     albertel 15541: 	    }
1.888     albertel 15542: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   15543: 		$lonid_to_ip{$id} = $ip;
                   15544: 	    }
                   15545: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 15546: 	}
1.1293    raeburn  15547:         unless ($nocache) {
                   15548: 	    &do_cache_new('iphost','iphost',
                   15549: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   15550: 		          48*60*60);
                   15551:         }
1.869     albertel 15552: 
1.847     albertel 15553: 	return %iphost;
1.598     albertel 15554:     }
                   15555: 
1.992     raeburn  15556:     #
                   15557:     #  Given a DNS returns the loncapa host name for that DNS 
                   15558:     # 
                   15559:     sub host_from_dns {
                   15560:         my ($dns) = @_;
                   15561:         my @hosts;
                   15562:         my $ip;
                   15563: 
1.993     raeburn  15564:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  15565:             $ip = $name_to_ip{$dns};
                   15566:         }
                   15567:         if (!$ip) {
                   15568:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   15569:             if (length($ip) == 4) { 
                   15570: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   15571:             }
                   15572:         }
                   15573:         if ($ip) {
                   15574: 	    @hosts = get_hosts_from_ip($ip);
                   15575: 	    return $hosts[0];
                   15576:         }
                   15577:         return undef;
1.986     foxr     15578:     }
1.992     raeburn  15579: 
1.1074    raeburn  15580:     sub get_internet_names {
                   15581:         my ($lonid) = @_;
                   15582:         return if ($lonid eq '');
                   15583:         my ($idnref,$cached)=
                   15584:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   15585:         if ($cached) {
                   15586:             return $idnref;
                   15587:         }
                   15588:         my $ip = &get_host_ip($lonid);
                   15589:         my @hosts = &get_hosts_from_ip($ip);
                   15590:         my %iphost = &get_iphost();
                   15591:         my (@idns,%seen);
                   15592:         foreach my $id (@hosts) {
                   15593:             my $dom = &host_domain($id);
                   15594:             my $prim_id = &domain($dom,'primary');
                   15595:             my $prim_ip = &get_host_ip($prim_id);
                   15596:             next if ($seen{$prim_ip});
                   15597:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   15598:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   15599:                     my $intdom = &internet_dom($id);
                   15600:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   15601:                         push(@idns,$intdom);
                   15602:                     }
                   15603:                 }
                   15604:             }
                   15605:             $seen{$prim_ip} = 1;
                   15606:         }
1.1219    raeburn  15607:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  15608:     }
                   15609: 
1.986     foxr     15610: }
                   15611: 
1.1079    raeburn  15612: sub all_loncaparevs {
1.1249    raeburn  15613:     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  15614: }
                   15615: 
1.1227    raeburn  15616: # ---------------------------------------------------------- Read loncaparev table
                   15617: {
                   15618:     sub load_loncaparevs { 
                   15619:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  15620:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  15621:                 while (my $configline=<$config>) {
                   15622:                     chomp($configline);
                   15623:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   15624:                     $loncaparevs{$hostid}=$loncaparev;
                   15625:                 }
                   15626:                 close($config);
                   15627:             }
                   15628:         }
                   15629:     }
                   15630: }
                   15631: 
                   15632: # ---------------------------------------------------------- Read serverhostID table
                   15633: {
                   15634:     sub load_serverhomeIDs {
                   15635:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  15636:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  15637:                 while (my $configline=<$config>) {
                   15638:                     chomp($configline);
                   15639:                     my ($name,$id)=split(/:/,$configline);
                   15640:                     $serverhomeIDs{$name}=$id;
                   15641:                 }
                   15642:                 close($config);
                   15643:             }
                   15644:         }
                   15645:     }
                   15646: }
                   15647: 
                   15648: 
1.862     albertel 15649: BEGIN {
                   15650: 
                   15651: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   15652:     unless ($readit) {
                   15653: {
                   15654:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   15655:     %perlvar = (%perlvar,%{$configvars});
                   15656: }
                   15657: 
                   15658: 
1.1       albertel 15659: # ------------------------------------------------------ Read spare server file
                   15660: {
1.1359    raeburn  15661:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 15662: 
                   15663:     while (my $configline=<$config>) {
                   15664:        chomp($configline);
1.284     matthew  15665:        if ($configline) {
1.784     albertel 15666: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 15667: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 15668: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 15669:        }
                   15670:     }
1.448     albertel 15671:     close($config);
1.1       albertel 15672: }
1.11      www      15673: # ------------------------------------------------------------ Read permissions
                   15674: {
1.1359    raeburn  15675:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      15676: 
                   15677:     while (my $configline=<$config>) {
1.448     albertel 15678: 	chomp($configline);
                   15679: 	if ($configline) {
                   15680: 	    my ($role,$perm)=split(/ /,$configline);
                   15681: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   15682: 	}
1.11      www      15683:     }
1.448     albertel 15684:     close($config);
1.11      www      15685: }
                   15686: 
                   15687: # -------------------------------------------- Read plain texts for permissions
                   15688: {
1.1359    raeburn  15689:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      15690: 
                   15691:     while (my $configline=<$config>) {
1.448     albertel 15692: 	chomp($configline);
                   15693: 	if ($configline) {
1.742     raeburn  15694: 	    my ($short,@plain)=split(/:/,$configline);
                   15695:             %{$prp{$short}} = ();
                   15696: 	    if (@plain > 0) {
                   15697:                 $prp{$short}{'std'} = $plain[0];
                   15698:                 for (my $i=1; $i<@plain; $i++) {
                   15699:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   15700:                 }
                   15701:             }
1.448     albertel 15702: 	}
1.135     www      15703:     }
1.448     albertel 15704:     close($config);
1.135     www      15705: }
                   15706: 
                   15707: # ---------------------------------------------------------- Read package table
                   15708: {
1.1359    raeburn  15709:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      15710: 
                   15711:     while (my $configline=<$config>) {
1.483     albertel 15712: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 15713: 	chomp($configline);
                   15714: 	my ($short,$plain)=split(/:/,$configline);
                   15715: 	my ($pack,$name)=split(/\&/,$short);
                   15716: 	if ($plain ne '') {
                   15717: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   15718: 	    $packagetab{$short}=$plain; 
                   15719: 	}
1.11      www      15720:     }
1.448     albertel 15721:     close($config);
1.329     matthew  15722: }
                   15723: 
1.1073    raeburn  15724: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  15725: 
                   15726: &load_loncaparevs();
1.1073    raeburn  15727: 
1.1074    raeburn  15728: # ---------------------------------------------------------- Read serverhostID table
                   15729: 
1.1227    raeburn  15730: &load_serverhomeIDs();
                   15731: 
                   15732: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  15733: {
                   15734:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   15735:     if (-e $file) {
                   15736:         my $parser = HTML::LCParser->new($file);
                   15737:         while (my $token = $parser->get_token()) {
                   15738:             if ($token->[0] eq 'S') {
                   15739:                 my $item = $token->[1];
                   15740:                 my $name = $token->[2]{'name'};
                   15741:                 my $value = $token->[2]{'value'};
1.1285    raeburn  15742:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  15743:                 my $namematch = $token->[2]{'namematch'};
                   15744:                 if ($item eq 'parameter') {
                   15745:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   15746:                         my $release = $parser->get_text();
                   15747:                         $release =~ s/(^\s*|\s*$ )//gx;
                   15748:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   15749:                     }
                   15750:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  15751:                     my $release = $parser->get_text();
                   15752:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  15753:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  15754:                 }
                   15755:             }
                   15756:         }
                   15757:     }
1.1073    raeburn  15758: }
                   15759: 
1.1138    raeburn  15760: # ---------------------------------------------------------- Read managers table
                   15761: {
                   15762:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  15763:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  15764:             while (my $configline=<$config>) {
                   15765:                 chomp($configline);
                   15766:                 next if ($configline =~ /^\#/);
                   15767:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   15768:                     $managerstab{$configline} = 1;
                   15769:                 }
                   15770:             }
                   15771:             close($config);
                   15772:         }
                   15773:     }
                   15774: }
                   15775: 
1.329     matthew  15776: # ------------- set up temporary directory
                   15777: {
1.1117    foxr     15778:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  15779: 
1.11      www      15780: }
                   15781: 
1.1405    raeburn  15782: # ------------- set default texengine (domain default overrides this)
                   15783: {
                   15784:     $deftex = LONCAPA::texengine();
                   15785: }
                   15786: 
1.1416    raeburn  15787: # ------------- set default minimum length for passwords for internal auth users
                   15788: {
                   15789:     $passwdmin = LONCAPA::passwd_min();
                   15790: }
                   15791: 
1.794     albertel 15792: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   15793: 				'compress_threshold'=> 20_000,
                   15794:  			        });
1.185     www      15795: 
1.281     www      15796: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      15797: $dumpcount=0;
1.958     www      15798: $locknum=0;
1.22      www      15799: 
1.163     harris41 15800: &logtouch();
1.672     albertel 15801: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      15802: $readit=1;
1.564     albertel 15803:     {
                   15804: 	use integer;
                   15805: 	my $test=(2**32)+1;
1.568     albertel 15806: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 15807: 	&logthis(" Detected 64bit platform ($_64bit)");
                   15808:     }
1.195     www      15809: }
1.1       albertel 15810: }
1.179     www      15811: 
1.1       albertel 15812: 1;
1.191     harris41 15813: __END__
                   15814: 
1.243     albertel 15815: =pod
                   15816: 
1.191     harris41 15817: =head1 NAME
                   15818: 
1.243     albertel 15819: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 15820: 
                   15821: =head1 SYNOPSIS
                   15822: 
1.243     albertel 15823: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 15824: 
                   15825:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   15826: 
1.243     albertel 15827: Common parameters:
                   15828: 
                   15829: =over 4
                   15830: 
                   15831: =item *
                   15832: 
                   15833: $uname : an internal username (if $cname expecting a course Id specifically)
                   15834: 
                   15835: =item *
                   15836: 
                   15837: $udom : a domain (if $cdom expecting a course's domain specifically)
                   15838: 
                   15839: =item *
                   15840: 
                   15841: $symb : a resource instance identifier
                   15842: 
                   15843: =item *
                   15844: 
                   15845: $namespace : the name of a .db file that contains the data needed or
                   15846: being set.
                   15847: 
                   15848: =back
                   15849: 
1.394     bowersj2 15850: =head1 OVERVIEW
1.191     harris41 15851: 
1.394     bowersj2 15852: lonnet provides subroutines which interact with the
                   15853: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   15854: about classes, users, and resources.
1.243     albertel 15855: 
                   15856: For many of these objects you can also use this to store data about
                   15857: them or modify them in various ways.
1.191     harris41 15858: 
1.394     bowersj2 15859: =head2 Symbs
1.191     harris41 15860: 
1.394     bowersj2 15861: To identify a specific instance of a resource, LON-CAPA uses symbols
                   15862: or "symbs"X<symb>. These identifiers are built from the URL of the
                   15863: map, the resource number of the resource in the map, and the URL of
                   15864: the resource itself. The latter is somewhat redundant, but might help
                   15865: if maps change.
                   15866: 
                   15867: An example is
                   15868: 
                   15869:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   15870: 
                   15871: The respective map entry is
                   15872: 
                   15873:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   15874:   title="Problem 2">
                   15875:  </resource>
                   15876: 
                   15877: Symbs are used by the random number generator, as well as to store and
                   15878: restore data specific to a certain instance of for example a problem.
                   15879: 
                   15880: =head2 Storing And Retrieving Data
                   15881: 
                   15882: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   15883: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   15884: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   15885: is is the non-critical message twin of cstore. These functions are for
                   15886: handlers to store a perl hash to a user's permanent data space in an
                   15887: easy manner, and to retrieve it again on another call. It is expected
                   15888: that a handler would use this once at the beginning to retrieve data,
                   15889: and then again once at the end to send only the new data back.
                   15890: 
                   15891: The data is stored in the user's data directory on the user's
                   15892: homeserver under the ID of the course.
                   15893: 
                   15894: The hash that is returned by restore will have all of the previous
                   15895: value for all of the elements of the hash.
                   15896: 
                   15897: Example:
                   15898: 
                   15899:  #creating a hash
                   15900:  my %hash;
                   15901:  $hash{'foo'}='bar';
                   15902: 
                   15903:  #storing it
                   15904:  &Apache::lonnet::cstore(\%hash);
                   15905: 
                   15906:  #changing a value
                   15907:  $hash{'foo'}='notbar';
                   15908: 
                   15909:  #adding a new value
                   15910:  $hash{'bar'}='foo';
                   15911:  &Apache::lonnet::cstore(\%hash);
                   15912: 
                   15913:  #retrieving the hash
                   15914:  my %history=&Apache::lonnet::restore();
                   15915: 
                   15916:  #print the hash
                   15917:  foreach my $key (sort(keys(%history))) {
                   15918:    print("\%history{$key} = $history{$key}");
                   15919:  }
                   15920: 
                   15921: Will print out:
1.191     harris41 15922: 
1.394     bowersj2 15923:  %history{1:foo} = bar
                   15924:  %history{1:keys} = foo:timestamp
                   15925:  %history{1:timestamp} = 990455579
                   15926:  %history{2:bar} = foo
                   15927:  %history{2:foo} = notbar
                   15928:  %history{2:keys} = foo:bar:timestamp
                   15929:  %history{2:timestamp} = 990455580
                   15930:  %history{bar} = foo
                   15931:  %history{foo} = notbar
                   15932:  %history{timestamp} = 990455580
                   15933:  %history{version} = 2
                   15934: 
                   15935: Note that the special hash entries C<keys>, C<version> and
                   15936: C<timestamp> were added to the hash. C<version> will be equal to the
                   15937: total number of versions of the data that have been stored. The
                   15938: C<timestamp> attribute will be the UNIX time the hash was
                   15939: stored. C<keys> is available in every historical section to list which
                   15940: keys were added or changed at a specific historical revision of a
                   15941: hash.
                   15942: 
                   15943: B<Warning>: do not store the hash that restore returns directly. This
                   15944: will cause a mess since it will restore the historical keys as if the
                   15945: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 15946: 
1.394     bowersj2 15947: Calling convention:
1.191     harris41 15948: 
1.1225    raeburn  15949:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  15950:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 15951: 
1.394     bowersj2 15952: For more detailed information, see lonnet specific documentation.
1.191     harris41 15953: 
1.394     bowersj2 15954: =head1 RETURN MESSAGES
1.191     harris41 15955: 
1.394     bowersj2 15956: =over 4
1.191     harris41 15957: 
1.394     bowersj2 15958: =item * B<con_lost>: unable to contact remote host
1.191     harris41 15959: 
1.394     bowersj2 15960: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   15961: when the connection is brought back up
1.191     harris41 15962: 
1.394     bowersj2 15963: =item * B<con_failed>: unable to contact remote host and unable to save message
                   15964: for later delivery
1.191     harris41 15965: 
1.967     bisitz   15966: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 15967: 
1.394     bowersj2 15968: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 15969: that was requested
1.191     harris41 15970: 
1.243     albertel 15971: =back
1.191     harris41 15972: 
1.243     albertel 15973: =head1 PUBLIC SUBROUTINES
1.191     harris41 15974: 
1.243     albertel 15975: =head2 Session Environment Functions
1.191     harris41 15976: 
1.243     albertel 15977: =over 4
1.191     harris41 15978: 
1.394     bowersj2 15979: =item * 
                   15980: X<appenv()>
1.949     raeburn  15981: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 15982: the user envirnoment file, and will be restored for each access this
1.620     albertel 15983: user makes during this session, also modifies the %env for the current
1.949     raeburn  15984: process. Optional rolesarrayref - if defined contains a reference to an array
                   15985: of roles which are exempt from the restriction on modifying user.role entries 
                   15986: in the user's environment.db and in %env.    
1.191     harris41 15987: 
                   15988: =item *
1.394     bowersj2 15989: X<delenv()>
1.987     raeburn  15990: B<delenv($delthis,$regexp)>: removes all items from the session
                   15991: environment file that begin with $delthis. If the 
                   15992: optional second arg - $regexp - is true, $delthis is treated as a 
                   15993: regular expression, otherwise \Q$delthis\E is used. 
                   15994: The values are also deleted from the current processes %env.
1.191     harris41 15995: 
1.795     albertel 15996: =item * get_env_multiple($name) 
                   15997: 
                   15998: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   15999: values may be defined and end up as an array ref.
                   16000: 
                   16001: returns an array of values
                   16002: 
1.243     albertel 16003: =back
                   16004: 
                   16005: =head2 User Information
1.191     harris41 16006: 
1.243     albertel 16007: =over 4
1.191     harris41 16008: 
                   16009: =item *
1.394     bowersj2 16010: X<queryauthenticate()>
                   16011: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 16012: authentication scheme
                   16013: 
                   16014: =item *
1.394     bowersj2 16015: X<authenticate()>
1.1073    raeburn  16016: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 16017: authenticate user from domain's lib servers (first use the current
                   16018: one). C<$upass> should be the users password.
1.1073    raeburn  16019: $checkdefauth is optional (value is 1 if a check should be made to
                   16020:    authenticate user using default authentication method, and allow
                   16021:    account creation if username does not have account in the domain).
                   16022: $clientcancheckhost is optional (value is 1 if checking whether the
                   16023:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 16024: 
                   16025: =item *
1.394     bowersj2 16026: X<homeserver()>
                   16027: B<homeserver($uname,$udom)>: find the server which has
                   16028: the user's directory and files (there must be only one), this caches
                   16029: the answer, and also caches if there is a borken connection.
1.191     harris41 16030: 
                   16031: =item *
1.394     bowersj2 16032: X<idget()>
1.1300    raeburn  16033: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   16034: a list of student/employee IDs or clicker IDs
                   16035: (student/employee IDs are a unique resource in a domain, there must be 
                   16036: only 1 ID per username, and only 1 username per ID in a specific domain).
                   16037: clickerIDs are not necessarily unique, as students might share clickers.
                   16038: (returns hash: id=>name,id=>name)
1.191     harris41 16039: 
                   16040: =item *
1.394     bowersj2 16041: X<idrget()>
                   16042: B<idrget($udom,@unames)>: find the IDs behind a list of
                   16043: usernames (returns hash: name=>id,name=>id)
1.191     harris41 16044: 
                   16045: =item *
1.394     bowersj2 16046: X<idput()>
1.1300    raeburn  16047: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   16048: names and associated student/employee IDs or clicker IDs.
                   16049: 
                   16050: =item *
                   16051: X<iddel()>
                   16052: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   16053: student/employee ID or clicker ID username look-ups from domain.
                   16054: The homeserver ($uhome) and namespace ($namespace) are optional.
                   16055: If no $uhome is provided, it will be determined usig &homeserver()
                   16056: for each user.  If no $namespace is provided, the default is ids.
                   16057: 
                   16058: =item *
                   16059: X<updateclickers()>
                   16060: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   16061: clicker ID-to-username look-ups in clickers.db on library server.
                   16062: Permitted actions are add or del (i.e., add or delete). The 
                   16063: clickers.db contains clickerID as keys (escaped), and each corresponding
                   16064: value is an escaped comma-separated list of usernames (for whom the
                   16065: library server is the homeserver), who registered that particular ID.
                   16066: If $critical is true, the update will be sent via &critical, otherwise
                   16067: &reply() will be used.
1.191     harris41 16068: 
                   16069: =item *
1.394     bowersj2 16070: X<rolesinit()>
1.1169    droeschl 16071: B<rolesinit($udom,$username)>: get user privileges.
                   16072: returns user role, first access and timer interval hashes
1.243     albertel 16073: 
                   16074: =item *
1.1171    droeschl 16075: X<privileged()>
                   16076: B<privileged($username,$domain)>: returns a true if user has a
                   16077: privileged and active role (i.e. su or dc), false otherwise.
                   16078: 
                   16079: =item *
1.551     albertel 16080: X<getsection()>
                   16081: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 16082: course $cname, return section name/number or '' for "not in course"
                   16083: and '-1' for "no section"
                   16084: 
                   16085: =item *
1.394     bowersj2 16086: X<userenvironment()>
                   16087: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 16088: passed in @what from the requested user's environment, returns a hash
                   16089: 
1.858     raeburn  16090: =item * 
                   16091: X<userlog_query()>
1.859     albertel 16092: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   16093: activity.log file. %filters defines filters applied when parsing the
                   16094: log file. These can be start or end timestamps, or the type of action
                   16095: - log to look for Login or Logout events, check for Checkin or
                   16096: Checkout, role for role selection. The response is in the form
                   16097: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   16098: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  16099: 
1.243     albertel 16100: =back
                   16101: 
                   16102: =head2 User Roles
                   16103: 
                   16104: =over 4
                   16105: 
                   16106: =item *
                   16107: 
1.1284    raeburn  16108: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   16109: returns codes for allowed actions.
                   16110: 
                   16111: The first argument is required, all others are optional.
                   16112: 
                   16113: $priv is the privilege being checked.
                   16114: $uri contains additional information about what is being checked for access (e.g.,
                   16115: URL, course ID etc.). 
                   16116: $symb is the unique resource instance identifier in a course; if needed,
                   16117: but not provided, it will be retrieved via a call to &symbread(). 
                   16118: $role is the role for which a priv is being checked (only used if priv is evb). 
                   16119: $clientip is the user's IP address (only used when checking for access to portfolio 
                   16120: files).
                   16121: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   16122: prevents recursive calls to &allowed.
                   16123: 
1.243     albertel 16124:  F: full access
                   16125:  U,I,K: authentication modes (cxx only)
                   16126:  '': forbidden
                   16127:  1: user needs to choose course
                   16128:  2: browse allowed
1.766     albertel 16129:  A: passphrase authentication needed
1.1284    raeburn  16130:  B: access temporarily blocked because of a blocking event in a course.
1.1402    raeburn  16131:  D: access blocked because access is required via session initiated via deep-link 
1.243     albertel 16132: 
                   16133: =item *
                   16134: 
1.1192    raeburn  16135: constructaccess($url,$setpriv) : check for access to construction space URL
                   16136: 
                   16137: See if the owner domain and name in the URL match those in the
                   16138: expected environment.  If so, return three element list
                   16139: ($ownername,$ownerdomain,$ownerhome).
                   16140: 
                   16141: Otherwise return the null string.
                   16142: 
                   16143: If second argument 'setpriv' is true, it assigns the privileges,
                   16144: and returns the same three element list, unless the owner has
                   16145: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   16146: in which case the null string is returned.
                   16147: 
                   16148: =item *
                   16149: 
1.1326    raeburn  16150: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   16151: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   16152: for system, domain, and course level. $uname and $udom are optional (current
                   16153: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 16154: 
                   16155: =item *
                   16156: 
1.988     raeburn  16157: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   16158: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  16159: $type is Course (default) or Community.
1.988     raeburn  16160: If $forcedefault evaluates to true, text returned will be default 
                   16161: text for $type. Otherwise, if this is a course, the text returned 
                   16162: will be a custom name for the role (if defined in the course's 
                   16163: environment).  If no custom name is defined the default is returned.
                   16164:    
1.832     raeburn  16165: =item *
                   16166: 
1.1219    raeburn  16167: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  16168: All arguments are optional. Returns a hash of a roles, either for
                   16169: co-author/assistant author roles for a user's Construction Space
1.906     albertel 16170: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  16171: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   16172: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   16173: For each key, value is set to colon-separated start and end times for
                   16174: the role.  If no username and domain are specified, will default to
1.934     raeburn  16175: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  16176: of role statuses (active, future or previous), roles 
                   16177: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   16178: to restrict the list of roles reported. If no array ref is 
                   16179: provided for types, will default to return only active roles.
1.834     albertel 16180: 
1.1195    raeburn  16181: =item *
                   16182: 
                   16183: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  16184: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   16185: 
                   16186: Additional optional arguments are: $type (if role checking is to be restricted 
                   16187: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  16188: available roles) or future (roles available in the future), and
                   16189: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  16190: have active Domain Coordinator role in course's domain or in additional
                   16191: domains (specified in 'Domains to check for privileged users' in course
                   16192: environment -- set via:  Course Settings -> Classlists and staff listing).
                   16193: 
                   16194: =item *
                   16195: 
                   16196: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   16197: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   16198: $possdomains and $possroles are optional array refs -- to domains to check and
                   16199: roles to check.  If $possdomains is not specified, a dump will be done of the
                   16200: users' roles.db to check for a dc or su role in any domain. This can be
                   16201: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   16202: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   16203: this then allows &privileged_by_domain() to be used, which caches the identity
                   16204: of privileged users, eliminating the need for repeated calls to &dump().
                   16205: 
                   16206: =item *
                   16207: 
                   16208: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   16209: where the outer hash keys are domains specified in the $possdomains array ref,
                   16210: next inner hash keys are privileged roles specified in the $roles array ref,
                   16211: and the innermost hash contains key = value pairs for username:domain = end:start
                   16212: for active or future "privileged" users with that role in that domain. To avoid
                   16213: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   16214: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  16215: 
1.243     albertel 16216: =back
                   16217: 
                   16218: =head2 User Modification
                   16219: 
                   16220: =over 4
                   16221: 
                   16222: =item *
                   16223: 
1.957     raeburn  16224: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 16225: user for the level given by URL.  Optional start and end dates (leave empty
                   16226: string or zero for "no date")
1.191     harris41 16227: 
                   16228: =item *
                   16229: 
1.243     albertel 16230: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   16231: change a users, password, possible return values are: ok,
                   16232: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   16233: refused
1.191     harris41 16234: 
                   16235: =item *
                   16236: 
1.243     albertel 16237: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 16238: 
                   16239: =item *
                   16240: 
1.1058    raeburn  16241: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   16242:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   16243: 
                   16244: will update user information (firstname,middlename,lastname,generation,
                   16245: permanentemail), and if forceid is true, student/employee ID also.
                   16246: A user's institutional affiliation(s) can also be updated.
                   16247: User information fields will not be overwritten with empty entries 
                   16248: unless the field is included in the $candelete array reference.
                   16249: This array is included when a single user is modified via "Manage Users",
                   16250: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 16251: 
                   16252: =item *
                   16253: 
1.286     matthew  16254: modifystudent
                   16255: 
1.957     raeburn  16256: modify a student's enrollment and identification information.
1.1235    raeburn  16257: The course id is resolved based on the current user's environment.  
                   16258: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  16259: associated with a course.
                   16260: 
1.297     matthew  16261: This call is essentially a wrapper for lonnet::modifyuser and
                   16262: lonnet::modify_student_enrollment
1.286     matthew  16263: 
                   16264: Inputs: 
                   16265: 
                   16266: =over 4
                   16267: 
1.957     raeburn  16268: =item B<$udom> Student's loncapa domain
1.286     matthew  16269: 
1.957     raeburn  16270: =item B<$uname> Student's loncapa login name
1.286     matthew  16271: 
1.964     bisitz   16272: =item B<$uid> Student/Employee ID
1.286     matthew  16273: 
1.957     raeburn  16274: =item B<$umode> Student's authentication mode
1.286     matthew  16275: 
1.957     raeburn  16276: =item B<$upass> Student's password
1.286     matthew  16277: 
1.957     raeburn  16278: =item B<$first> Student's first name
1.286     matthew  16279: 
1.957     raeburn  16280: =item B<$middle> Student's middle name
1.286     matthew  16281: 
1.957     raeburn  16282: =item B<$last> Student's last name
1.286     matthew  16283: 
1.957     raeburn  16284: =item B<$gene> Student's generation
1.286     matthew  16285: 
1.957     raeburn  16286: =item B<$usec> Student's section in course
1.286     matthew  16287: 
                   16288: =item B<$end> Unix time of the roles expiration
                   16289: 
                   16290: =item B<$start> Unix time of the roles start date
                   16291: 
                   16292: =item B<$forceid> If defined, allow $uid to be changed
                   16293: 
                   16294: =item B<$desiredhome> server to use as home server for student
                   16295: 
1.957     raeburn  16296: =item B<$email> Student's permanent e-mail address
                   16297: 
                   16298: =item B<$type> Type of enrollment (auto or manual)
                   16299: 
1.963     raeburn  16300: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   16301: 
                   16302: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  16303: 
1.963     raeburn  16304: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  16305: 
1.963     raeburn  16306: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  16307: 
1.1216    raeburn  16308: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   16309: 
                   16310: =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  16311: 
1.286     matthew  16312: =back
1.297     matthew  16313: 
                   16314: =item *
                   16315: 
                   16316: modify_student_enrollment
                   16317: 
1.1235    raeburn  16318: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  16319: 'role.request.course' must be defined for this function to proceed.
                   16320: 
                   16321: Inputs:
                   16322: 
                   16323: =over 4
                   16324: 
1.1235    raeburn  16325: =item $udom, student's domain
1.297     matthew  16326: 
1.1235    raeburn  16327: =item $uname, student's name
1.297     matthew  16328: 
1.1235    raeburn  16329: =item $uid, student's user id
1.297     matthew  16330: 
1.1235    raeburn  16331: =item $first, student's first name
1.297     matthew  16332: 
                   16333: =item $middle
                   16334: 
                   16335: =item $last
                   16336: 
                   16337: =item $gene
                   16338: 
                   16339: =item $usec
                   16340: 
                   16341: =item $end
                   16342: 
                   16343: =item $start
                   16344: 
1.957     raeburn  16345: =item $type
                   16346: 
                   16347: =item $locktype
                   16348: 
                   16349: =item $cid
                   16350: 
                   16351: =item $selfenroll
                   16352: 
                   16353: =item $context
                   16354: 
1.1216    raeburn  16355: =item $credits, number of credits student will earn from this class
                   16356: 
1.1314    raeburn  16357: =item $instsec, institutional course section code for student
                   16358: 
1.297     matthew  16359: =back
                   16360: 
1.191     harris41 16361: 
                   16362: =item *
                   16363: 
1.243     albertel 16364: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   16365: custom role; give a custom role to a user for the level given by URL.  Specify
                   16366: name and domain of role author, and role name
1.191     harris41 16367: 
                   16368: =item *
                   16369: 
1.243     albertel 16370: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 16371: 
                   16372: =item *
                   16373: 
1.243     albertel 16374: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   16375: 
                   16376: =back
                   16377: 
                   16378: =head2 Course Infomation
                   16379: 
                   16380: =over 4
1.191     harris41 16381: 
                   16382: =item *
                   16383: 
1.1118    foxr     16384: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 16385: specified course id, including all environment settings for the
                   16386: course, the description of the course will be in the hash under the
                   16387: key 'description'
1.191     harris41 16388: 
1.1118    foxr     16389: $options is an optional parameter that if supplied is a hash reference that controls
                   16390: what how this function works.  It has the following key/values:
                   16391: 
                   16392: =over 4
                   16393: 
                   16394: =item freshen_cache
                   16395: 
                   16396: If defined, and the environment cache for the course is valid, it is 
                   16397: returned in the returned hash.
                   16398: 
                   16399: =item one_time
                   16400: 
                   16401: If defined, the last cache time is set to _now_
                   16402: 
                   16403: =item user
                   16404: 
                   16405: If defined, the supplied username is used instead of the current user.
                   16406: 
                   16407: 
                   16408: =back
                   16409: 
1.191     harris41 16410: =item *
                   16411: 
1.624     albertel 16412: resdata($name,$domain,$type,@which) : request for current parameter
                   16413: setting for a specific $type, where $type is either 'course' or 'user',
                   16414: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  16415: answers for 10 minutes.
1.243     albertel 16416: 
1.877     foxr     16417: =item *
                   16418: 
                   16419: get_courseresdata($courseid, $domain) : dump the entire course resource
                   16420: data base, returning a hash that is keyed by the resource name and has
                   16421: values that are the resource value.  I believe that the timestamps and
                   16422: versions are also returned.
                   16423: 
1.1236    raeburn  16424: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   16425: supplemental content area. This routine caches the number of files for 
                   16426: 10 minutes.
                   16427: 
1.243     albertel 16428: =back
                   16429: 
                   16430: =head2 Course Modification
                   16431: 
                   16432: =over 4
1.191     harris41 16433: 
                   16434: =item *
                   16435: 
1.243     albertel 16436: writecoursepref($courseid,%prefs) : write preferences (environment
                   16437: database) for a course
1.191     harris41 16438: 
                   16439: =item *
                   16440: 
1.1011    raeburn  16441: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   16442: 
                   16443: =item *
                   16444: 
1.1038    raeburn  16445: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 16446: 
1.1167    droeschl 16447: =item *
                   16448: 
                   16449: is_course($courseid), is_course($cdom, $cnum)
                   16450: 
                   16451: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   16452: two component version $cdom, $cnum. It checks if the specified course exists.
                   16453: 
                   16454: Returns:
                   16455:     undef if the course doesn't exist, otherwise
                   16456:     in scalar context the combined courseid.
                   16457:     in list context the two components of the course identifier, domain and 
                   16458:     courseid.    
                   16459: 
1.243     albertel 16460: =back
                   16461: 
1.1401    raeburn  16462: =head2 Bubblesheet Configuration
                   16463: 
                   16464: =over 4
                   16465: 
                   16466: =item *
                   16467: 
                   16468: get_scantron_config($which)
                   16469: 
                   16470: $which - the name of the configuration to parse from the file.
                   16471: 
                   16472: Parses and returns the bubblesheet configuration line selected as a
                   16473: hash of configuration file fields.
                   16474: 
                   16475: 
                   16476: Returns:
                   16477:     If the named configuration is not in the file, an empty
                   16478:     hash is returned.
                   16479: 
                   16480:     a hash with the fields
                   16481:       name         - internal name for the this configuration setup
                   16482:       description  - text to display to operator that describes this config
                   16483:       CODElocation - if 0 or the string 'none'
                   16484:                           - no CODE exists for this config
                   16485:                      if -1 || the string 'letter'
                   16486:                           - a CODE exists for this config and is
                   16487:                             a string of letters
                   16488:                      Unsupported value (but planned for future support)
                   16489:                           if a positive integer
                   16490:                                - The CODE exists as the first n items from
                   16491:                                  the question section of the form
                   16492:                           if the string 'number'
                   16493:                                - The CODE exists for this config and is
                   16494:                                  a string of numbers
                   16495:       CODEstart   - (only matter if a CODE exists) column in the line where
                   16496:                      the CODE starts
                   16497:       CODElength  - length of the CODE
                   16498:       IDstart     - column where the student/employee ID starts
                   16499:       IDlength    - length of the student/employee ID info
                   16500:       Qstart      - column where the information from the bubbled
                   16501:                     'questions' start
                   16502:       Qlength     - number of columns comprising a single bubble line from
                   16503:                     the sheet. (usually either 1 or 10)
                   16504:       Qon         - either a single character representing the character used
                   16505:                     to signal a bubble was chosen in the positional setup, or
                   16506:                     the string 'letter' if the letter of the chosen bubble is
                   16507:                     in the final, or 'number' if a number representing the
                   16508:                     chosen bubble is in the file (1->A 0->J)
                   16509:       Qoff        - the character used to represent that a bubble was
                   16510:                     left blank
                   16511:       PaperID     - if the scanning process generates a unique number for each
                   16512:                     sheet scanned the column that this ID number starts in
                   16513:       PaperIDlength - number of columns that comprise the unique ID number
                   16514:                       for the sheet of paper
                   16515:       FirstName   - column that the first name starts in
                   16516:       FirstNameLength - number of columns that the first name spans
                   16517:       LastName    - column that the last name starts in
                   16518:       LastNameLength - number of columns that the last name spans
                   16519:       BubblesPerRow - number of bubbles available in each row used to
                   16520:                       bubble an answer. (If not specified, 10 assumed).
                   16521: 
                   16522: 
                   16523: =item *
                   16524: 
                   16525: get_scantronformat_file($cdom)
                   16526: 
                   16527: $cdom - the course's domain (optional); if not supplied, uses
                   16528: domain for current $env{'request.course.id'}.
                   16529: 
                   16530: Returns an array containing lines from the scantron format file for
                   16531: the domain of the course.
                   16532: 
                   16533: If a url for a custom.tab file is listed in domain's configuration.db,
                   16534: lines are from this file.
                   16535: 
                   16536: Otherwise, if a default.tab has been published in RES space by the
                   16537: domainconfig user, lines are from this file.
                   16538: 
                   16539: Otherwise, fall back to getting lines from the legacy file on the
                   16540: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   16541: 
                   16542: =back
                   16543: 
1.243     albertel 16544: =head2 Resource Subroutines
                   16545: 
                   16546: =over 4
1.191     harris41 16547: 
                   16548: =item *
                   16549: 
1.243     albertel 16550: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 16551: 
                   16552: =item *
                   16553: 
1.243     albertel 16554: repcopy($filename) : subscribes to the requested file, and attempts to
                   16555: replicate from the owning library server, Might return
1.607     raeburn  16556: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   16557: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 16558: resource. Expects the local filesystem pathname
                   16559: (/home/httpd/html/res/....)
                   16560: 
                   16561: =back
                   16562: 
                   16563: =head2 Resource Information
                   16564: 
                   16565: =over 4
1.191     harris41 16566: 
                   16567: =item *
                   16568: 
1.1228    raeburn  16569: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   16570: and returns the value of a variety of different possible values,
                   16571: $varname should be a request string, and the other parameters can be
                   16572: used to specify who and what one is asking about. Ordinarily, $cid 
                   16573: does not need to be specified, as it is retrived from 
                   16574: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   16575: within lonuserstate::loadmap() when initializing a course, before
                   16576: $env{'request.course.id'} has been set, so it needs to be provided
                   16577: in that one case.
1.243     albertel 16578: 
                   16579: Possible values for $varname are environment.lastname (or other item
                   16580: from the envirnment hash), user.name (or someother aspect about the
                   16581: user), resource.0.maxtries (or some other part and parameter of a
                   16582: resource)
1.204     albertel 16583: 
                   16584: =item *
                   16585: 
1.243     albertel 16586: directcondval($number) : get current value of a condition; reads from a state
                   16587: string
1.204     albertel 16588: 
                   16589: =item *
                   16590: 
1.243     albertel 16591: condval($condidx) : value of condition index based on state
1.204     albertel 16592: 
                   16593: =item *
                   16594: 
1.1362    raeburn  16595: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 16596: resource's metadata, $what should be either a specific key, or either
                   16597: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  16598: packages that this resource currently uses, the last 3 arguments are 
                   16599: only used internally for recursive metadata.
                   16600: 
                   16601: the toolsymb is only used where the uri is for an external tool (for which
                   16602: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 16603: 
1.1371    raeburn  16604: this function automatically caches all requests except any made recursively
                   16605: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   16606: defined).
1.191     harris41 16607: 
                   16608: =item *
                   16609: 
1.243     albertel 16610: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   16611: network of library servers; returns file handle of where SQL and regex results
                   16612: will be stored for query
1.191     harris41 16613: 
                   16614: =item *
                   16615: 
1.1282    raeburn  16616: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   16617: return symbolic list entry (all arguments optional). 
                   16618: 
                   16619: Args: filename is the filename (including path) for the file for which a symb 
                   16620: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   16621: to check access status if more than one resource was found in the bighash 
                   16622: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   16623: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   16624: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   16625: cause possible symbs to be checked to determine if they are subject to content
                   16626: blocking, if so they will not be included as possible symbs; possibles is a
                   16627: ref to a hash, which, as a side effect, will be populated with all possible 
                   16628: symbs (content blocking not tested).
                   16629:  
1.243     albertel 16630: returns the data handle
1.191     harris41 16631: 
                   16632: =item *
                   16633: 
1.1190    raeburn  16634: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   16635: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 16636: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  16637: on failure, user must be in a course, as it assumes the existence of
                   16638: the course initial hash, and uses $env('request.course.id'}.  The third
                   16639: arg is an optional reference to a scalar.  If this arg is passed in the 
                   16640: call to symbverify, it will be set to 1 if the symb has been set to be 
                   16641: encrypted; otherwise it will be null.  
1.191     harris41 16642: 
                   16643: =item *
                   16644: 
1.243     albertel 16645: symbclean($symb) : removes versions numbers from a symb, returns the
                   16646: cleaned symb
1.191     harris41 16647: 
                   16648: =item *
                   16649: 
1.243     albertel 16650: is_on_map($uri) : checks if the $uri is somewhere on the current
                   16651: course map, user must be in a course for it to work.
1.191     harris41 16652: 
                   16653: =item *
                   16654: 
1.243     albertel 16655: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 16656: 
                   16657: =item *
                   16658: 
1.243     albertel 16659: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   16660: a random seed, all arguments are optional, if they aren't sent it uses the
                   16661: environment to derive them. Note: if symb isn't sent and it can't get one
                   16662: from &symbread it will use the current time as its return value
1.191     harris41 16663: 
                   16664: =item *
                   16665: 
1.243     albertel 16666: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   16667: unfakeable, receipt
1.191     harris41 16668: 
                   16669: =item *
                   16670: 
1.620     albertel 16671: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 16672: 
                   16673: =item *
                   16674: 
1.243     albertel 16675: countacc($url) : count the number of accesses to a given URL
1.191     harris41 16676: 
                   16677: =item *
                   16678: 
1.243     albertel 16679: 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 16680: 
                   16681: =item *
                   16682: 
1.243     albertel 16683: 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 16684: 
                   16685: =item *
                   16686: 
1.243     albertel 16687: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 16688: 
                   16689: =item *
                   16690: 
1.243     albertel 16691: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   16692: forcing spreadsheet to reevaluate the resource scores next time.
                   16693: 
1.1195    raeburn  16694: =item * 
                   16695: 
1.1196    raeburn  16696: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   16697: when viewing in course context.
1.1195    raeburn  16698: 
1.1196    raeburn  16699:  input: six args -- filename (decluttered), course number, course domain,
                   16700:                     url, symb (if registered) and group (if this is a 
                   16701:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  16702: 
1.1196    raeburn  16703:  output: array of five scalars --
1.1195    raeburn  16704:          $cfile -- url for file editing if editable on current server
                   16705:          $home -- homeserver of resource (i.e., for author if published,
                   16706:                                           or course if uploaded.).
                   16707:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  16708:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   16709:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  16710: 
                   16711: =item *
                   16712: 
                   16713: is_course_upload($file,$cnum,$cdom)
                   16714: 
                   16715: Used in course context to determine if current file was uploaded to 
                   16716: the course (i.e., would be found in /userfiles/docs on the course's 
                   16717: homeserver.
                   16718: 
                   16719:   input: 3 args -- filename (decluttered), course number and course domain.
                   16720:   output: boolean -- 1 if file was uploaded.
                   16721: 
1.243     albertel 16722: =back
                   16723: 
                   16724: =head2 Storing/Retreiving Data
                   16725: 
                   16726: =over 4
1.191     harris41 16727: 
                   16728: =item *
                   16729: 
1.1269    raeburn  16730: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   16731: permanently for this url; hashref needs to be given and should be a \%hashname;
                   16732: the remaining args aren't required and if they aren't passed or are '' they will
                   16733: be derived from the env (with the exception of $laststore, which is an 
                   16734: optional arg used when a user's submission is stored in grading).
                   16735: $laststore is $version=$timestamp, where $version is the most recent version
                   16736: number retrieved for the corresponding $symb in the $namespace db file, and
                   16737: $timestamp is the timestamp for that transaction (UNIX time).
                   16738: $laststore is currently only passed when cstore() is called by 
                   16739: structuretags::finalize_storage().
1.191     harris41 16740: 
                   16741: =item *
                   16742: 
1.1269    raeburn  16743: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   16744: but uses critical subroutine
1.191     harris41 16745: 
                   16746: =item *
                   16747: 
1.243     albertel 16748: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   16749: all args are optional
1.191     harris41 16750: 
                   16751: =item *
                   16752: 
1.717     albertel 16753: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   16754: dumps the complete (or key matching regexp) namespace into a hash
                   16755: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   16756: normally &store()ed into
                   16757: 
                   16758: $range should be either an integer '100' (give me the first 100
                   16759:                                            matching records)
                   16760:               or be  two integers sperated by a - with no spaces
                   16761:                  '30-50' (give me the 30th through the 50th matching
                   16762:                           records)
                   16763: 
                   16764: 
                   16765: =item *
                   16766: 
1.1269    raeburn  16767: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 16768: replaces a &store() version of data with a replacement set of data
                   16769: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  16770: reference. If $tolog is true, the transaction is logged in the courselog
                   16771: with an action=PUTSTORE.
1.717     albertel 16772: 
                   16773: =item *
                   16774: 
1.243     albertel 16775: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   16776: works very similar to store/cstore, but all data is stored in a
                   16777: temporary location and can be reset using tmpreset, $storehash should
                   16778: be a hash reference, returns nothing on success
1.191     harris41 16779: 
                   16780: =item *
                   16781: 
1.243     albertel 16782: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   16783: similar to restore, but all data is stored in a temporary location and
                   16784: can be reset using tmpreset. Returns a hash of values on success,
                   16785: error string otherwise.
1.191     harris41 16786: 
                   16787: =item *
                   16788: 
1.243     albertel 16789: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   16790: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 16791: 
                   16792: =item *
                   16793: 
1.243     albertel 16794: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16795: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 16796: 
                   16797: =item *
                   16798: 
1.243     albertel 16799: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   16800: namesp ($udom and $uname are optional)
1.191     harris41 16801: 
                   16802: =item *
                   16803: 
1.702     albertel 16804: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 16805: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 16806: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  16807: 
1.702     albertel 16808: $range should be either an integer '100' (give me the first 100
                   16809:                                            matching records)
                   16810:               or be  two integers sperated by a - with no spaces
                   16811:                  '30-50' (give me the 30th through the 50th matching
                   16812:                           records)
1.449     matthew  16813: =item *
                   16814: 
                   16815: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   16816: $store can be a scalar, an array reference, or if the amount to be 
                   16817: incremented is > 1, a hash reference.
                   16818: 
                   16819: ($udom and $uname are optional)
1.191     harris41 16820: 
                   16821: =item *
                   16822: 
1.243     albertel 16823: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   16824: ($udom and $uname are optional)
1.191     harris41 16825: 
                   16826: =item *
                   16827: 
1.243     albertel 16828: cput($namespace,$storehash,$udom,$uname) : critical put
                   16829: ($udom and $uname are optional)
1.191     harris41 16830: 
                   16831: =item *
                   16832: 
1.748     albertel 16833: newput($namespace,$storehash,$udom,$uname) :
                   16834: 
                   16835: Attempts to store the items in the $storehash, but only if they don't
                   16836: currently exist, if this succeeds you can be certain that you have 
                   16837: successfully created a new key value pair in the $namespace db.
                   16838: 
                   16839: 
                   16840: Args:
                   16841:  $namespace: name of database to store values to
                   16842:  $storehash: hashref to store to the db
                   16843:  $udom: (optional) domain of user containing the db
                   16844:  $uname: (optional) name of user caontaining the db
                   16845: 
                   16846: Returns:
                   16847:  'ok' -> succeeded in storing all keys of $storehash
                   16848:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   16849:                         least <key> already existed in the db (other
                   16850:                         requested keys may also already exist)
1.967     bisitz   16851:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 16852:  'con_lost' -> unable to contact request server
                   16853:  'refused' -> action was not allowed by remote machine
                   16854: 
                   16855: 
                   16856: =item *
                   16857: 
1.243     albertel 16858: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16859: reference filled in from namesp (encrypts the return communication)
                   16860: ($udom and $uname are optional)
1.191     harris41 16861: 
                   16862: =item *
                   16863: 
1.243     albertel 16864: log($udom,$name,$home,$message) : write to permanent log for user; use
                   16865: critical subroutine
                   16866: 
1.806     raeburn  16867: =item *
                   16868: 
1.860     raeburn  16869: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   16870: array reference filled in from namespace found in domain level on either
                   16871: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  16872: 
                   16873: =item *
                   16874: 
1.860     raeburn  16875: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   16876: domain level either on specified domain server ($uhome) or primary domain 
                   16877: server ($udom and $uhome are optional)
1.806     raeburn  16878: 
1.943     raeburn  16879: =item * 
                   16880: 
1.1240    raeburn  16881: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   16882: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   16883: the target domain.
                   16884: 
                   16885: May also include additional key => value pairs for the following groups:
                   16886: 
                   16887: =over
                   16888: 
                   16889: =item
                   16890: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   16891: 
                   16892: =over
                   16893: 
                   16894: =item defaultquota, authorquota
                   16895: 
                   16896: =back
                   16897: 
                   16898: =item
                   16899: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   16900: portfolio for users).
                   16901: 
                   16902: =over
                   16903: 
                   16904: =item
                   16905: aboutme, blog, webdav, portfolio
                   16906: 
                   16907: =back
                   16908: 
                   16909: =item
                   16910: requestcourses: ability to request courses, and how requests are processed.
                   16911: 
                   16912: =over
                   16913: 
                   16914: =item
1.1305    raeburn  16915: official, unofficial, community, textbook, placement
1.1240    raeburn  16916: 
                   16917: =back
                   16918: 
                   16919: =item
                   16920: inststatus: types of institutional affiliation, and order in which they are displayed.
                   16921: 
                   16922: =over
                   16923: 
                   16924: =item
1.1256    raeburn  16925: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  16926: 
                   16927: =back
                   16928: 
                   16929: =item
                   16930: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   16931: for course's uploaded content.
                   16932: 
                   16933: =over
                   16934: 
                   16935: =item
1.1246    raeburn  16936: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  16937: communityquota, textbookquota, placementquota
1.1240    raeburn  16938: 
                   16939: =back
                   16940: 
                   16941: =item
                   16942: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   16943: on your servers.
                   16944: 
                   16945: =over
                   16946: 
                   16947: =item 
                   16948: remotesessions, hostedsessions
                   16949: 
                   16950: =back
                   16951: 
                   16952: =back
                   16953: 
                   16954: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   16955: utility to create a configuration.db file on a domain's primary library server 
                   16956: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   16957: -- corresponding values are authentication type (internal, krb4, krb5,
                   16958: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   16959: will be available. Values are retrieved from cache (if current), unless the
                   16960: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   16961: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   16962: 
                   16963: Typical usage:
1.943     raeburn  16964: 
1.1240    raeburn  16965: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  16966: 
1.243     albertel 16967: =back
                   16968: 
                   16969: =head2 Network Status Functions
                   16970: 
                   16971: =over 4
1.191     harris41 16972: 
                   16973: =item *
                   16974: 
1.1137    raeburn  16975: dirlist() : return directory list based on URI (first arg).
                   16976: 
                   16977: Inputs: 1 required, 5 optional.
                   16978: 
                   16979: =over
                   16980: 
                   16981: =item 
                   16982: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   16983: 
                   16984: =item
                   16985: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   16986: 
                   16987: =item
                   16988: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   16989: 
                   16990: =item
                   16991: $getpropath - boolean: 1 if prepend path using &propath(). 
                   16992: 
                   16993: =item
                   16994: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   16995: 
                   16996: =item 
                   16997: $alternateRoot - path to prepend in place of path from $uri.
                   16998: 
                   16999: =back
                   17000: 
                   17001: Returns: Array of up to two items.
                   17002: 
                   17003: =over
                   17004: 
                   17005: a reference to an array of files/subdirectories
                   17006: 
                   17007: =over
                   17008: 
                   17009: Each element in the array of files/subdirectories is a & separated list of
                   17010: item name and the result of running stat on the item.  If dirlist was requested
                   17011: for a file instead of a directory, the item name will be ''. For a directory 
                   17012: listing, if the item is a metadata file, the element will end &N&M 
                   17013: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   17014: default copyright set (1).  
                   17015: 
                   17016: =back
                   17017: 
                   17018: a scalar containing error condition (if encountered).
                   17019: 
                   17020: =over
                   17021: 
                   17022: =item 
                   17023: no_host (no homeserver identified for $username:$domain).
                   17024: 
                   17025: =item 
                   17026: no_such_host (server contacted for listing not identified as valid host).
                   17027: 
                   17028: =item 
                   17029: con_lost (connection to remote server failed).
                   17030: 
                   17031: =item 
                   17032: refused (invalid $username:$domain received on lond side).
                   17033: 
                   17034: =item 
                   17035: no_such_dir (directory at specified path on lond side does not exist). 
                   17036: 
                   17037: =item 
                   17038: empty (directory at specified path on lond side is empty).
                   17039: 
                   17040: =over
                   17041: 
                   17042: This is currently not encountered because the &ls3, &ls2, 
                   17043: &ls (_handler) routines on the lond side do not filter out
                   17044: . and .. from a directory listing. 
                   17045: 
                   17046: =back
                   17047: 
                   17048: =back
                   17049: 
                   17050: =back
1.191     harris41 17051: 
                   17052: =item *
                   17053: 
1.243     albertel 17054: spareserver() : find server with least workload from spare.tab
                   17055: 
1.986     foxr     17056: 
                   17057: =item *
                   17058: 
                   17059: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   17060: if there is no corresponding loncapa host.
                   17061: 
1.243     albertel 17062: =back
                   17063: 
1.986     foxr     17064: 
1.243     albertel 17065: =head2 Apache Request
                   17066: 
                   17067: =over 4
1.191     harris41 17068: 
                   17069: =item *
                   17070: 
1.243     albertel 17071: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   17072: localhost, posts hash
                   17073: 
                   17074: =back
                   17075: 
                   17076: =head2 Data to String to Data
                   17077: 
                   17078: =over 4
1.191     harris41 17079: 
                   17080: =item *
                   17081: 
1.243     albertel 17082: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   17083: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 17084: 
                   17085: =item *
                   17086: 
1.243     albertel 17087: hashref2str($hashref) : convert a hashref into a string complete with
                   17088: escaping and '=' and '&' separators, supports elements that are
                   17089: arrayrefs and hashrefs
1.191     harris41 17090: 
                   17091: =item *
                   17092: 
1.243     albertel 17093: arrayref2str($arrayref) : convert an arrayref into a string complete
                   17094: with escaping and '&' separators, supports elements that are arrayrefs
                   17095: and hashrefs
1.191     harris41 17096: 
                   17097: =item *
                   17098: 
1.243     albertel 17099: str2hash($string) : convert string to hash using unescaping and
                   17100: splitting on '=' and '&', supports elements that are arrayrefs and
                   17101: hashrefs
1.191     harris41 17102: 
                   17103: =item *
                   17104: 
1.243     albertel 17105: str2array($string) : convert string to hash using unescaping and
                   17106: splitting on '&', supports elements that are arrayrefs and hashrefs
                   17107: 
                   17108: =back
                   17109: 
                   17110: =head2 Logging Routines
                   17111: 
                   17112: 
                   17113: These routines allow one to make log messages in the lonnet.log and
                   17114: lonnet.perm logfiles.
1.191     harris41 17115: 
1.1119    foxr     17116: =over 4
                   17117: 
1.191     harris41 17118: =item *
                   17119: 
1.243     albertel 17120: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 17121: 
                   17122: =item *
                   17123: 
1.243     albertel 17124: logthis() : append message to the normal lonnet.log file, it gets
                   17125: preiodically rolled over and deleted.
1.191     harris41 17126: 
                   17127: =item *
                   17128: 
1.243     albertel 17129: logperm() : append a permanent message to lonnet.perm.log, this log
                   17130: file never gets deleted by any automated portion of the system, only
                   17131: messages of critical importance should go in here.
                   17132: 
1.1119    foxr     17133: 
1.243     albertel 17134: =back
                   17135: 
                   17136: =head2 General File Helper Routines
                   17137: 
                   17138: =over 4
1.191     harris41 17139: 
                   17140: =item *
                   17141: 
1.481     raeburn  17142: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   17143: (a) files in /uploaded
                   17144:   (i) If a local copy of the file exists - 
                   17145:       compares modification date of local copy with last-modified date for 
                   17146:       definitive version stored on home server for course. If local copy is 
                   17147:       stale, requests a new version from the home server and stores it. 
                   17148:       If the original has been removed from the home server, then local copy 
                   17149:       is unlinked.
                   17150:   (ii) If local copy does not exist -
                   17151:       requests the file from the home server and stores it. 
                   17152:   
                   17153:   If $caller is 'uploadrep':  
                   17154:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   17155:     for request for files originally uploaded via DOCS. 
                   17156:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   17157:   
                   17158:   Otherwise:
                   17159:      This indicates a call from the content generation phase of the request.
                   17160:      -  returns the entire contents of the file or -1.
                   17161:      
                   17162: (b) files in /res
                   17163:    - returns the entire contents of a file or -1; 
                   17164:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 17165: 
1.712     albertel 17166: 
                   17167: =item *
                   17168: 
                   17169: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   17170:                   reference
                   17171: 
                   17172: returns either a stat() list of data about the file or an empty list
                   17173: if the file doesn't exist or couldn't find out about it (connection
                   17174: problems or user unknown)
                   17175: 
1.191     harris41 17176: =item *
                   17177: 
1.243     albertel 17178: filelocation($dir,$file) : returns file system location of a file
                   17179: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   17180: directory that relative $file lookups are to looked in ($dir of /a/dir
                   17181: and a file of ../bob will become /a/bob)
1.191     harris41 17182: 
                   17183: =item *
                   17184: 
                   17185: hreflocation($dir,$file) : returns file system location or a URL; same as
                   17186: filelocation except for hrefs
                   17187: 
                   17188: =item *
                   17189: 
1.1261    raeburn  17190: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   17191: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 17192: 
1.243     albertel 17193: =back
                   17194: 
1.608     albertel 17195: =head2 Usererfile file routines (/uploaded*)
                   17196: 
                   17197: =over 4
                   17198: 
                   17199: =item *
                   17200: 
                   17201: userfileupload(): main rotine for putting a file in a user or course's
                   17202:                   filespace, arguments are,
                   17203: 
1.620     albertel 17204:  formname - required - this is the name of the element in $env where the
1.608     albertel 17205:            filename, and the contents of the file to create/modifed exist
1.620     albertel 17206:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   17207:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  17208:  context - if coursedoc, store the file in the course of the active role
                   17209:              of the current user; 
                   17210:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   17211:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 17212:  subdir - required - subdirectory to put the file in under ../userfiles/
                   17213:          if undefined, it will be placed in "unknown"
                   17214: 
                   17215:  (This routine calls clean_filename() to remove any dangerous
                   17216:  characters from the filename, and then calls finuserfileupload() to
                   17217:  complete the transaction)
                   17218: 
                   17219:  returns either the url of the uploaded file (/uploaded/....) if successful
                   17220:  and /adm/notfound.html if unsuccessful
                   17221: 
                   17222: =item *
                   17223: 
                   17224: clean_filename(): routine for cleaing a filename up for storage in
                   17225:                  userfile space, argument is:
                   17226: 
                   17227:  filename - proposed filename
                   17228: 
                   17229: returns: the new clean filename
                   17230: 
                   17231: =item *
                   17232: 
1.1090    raeburn  17233: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 17234: userspace, probably shouldn't be called directly
                   17235: 
                   17236:   docuname: username or courseid of destination for the file
                   17237:   docudom: domain of user/course of destination for the file
                   17238:   formname: same as for userfileupload()
1.1090    raeburn  17239:   fname: filename (including subdirectories) for the file
                   17240:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401    raeburn  17241:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  17242:   allfiles: reference to hash used to store objects found by parser
                   17243:   codebase: reference to hash used for codebases of java objects found by parser
                   17244:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   17245:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   17246:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   17247:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   17248:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   17249:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  17250:   mimetype: reference to scalar to accommodate mime type determined
                   17251:             from File::MMagic if $parser = parse.
1.608     albertel 17252: 
                   17253:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  17254:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   17255:  was 'overwrite').
                   17256:  
1.608     albertel 17257: 
                   17258: =item *
                   17259: 
                   17260: renameuserfile(): renames an existing userfile to a new name
                   17261: 
                   17262:   Args:
                   17263:    docuname: username or courseid of destination for the file
                   17264:    docudom: domain of user/course of destination for the file
                   17265:    old: current file name (including any subdirs under userfiles)
                   17266:    new: desired file name (including any subdirs under userfiles)
                   17267: 
                   17268: =item *
                   17269: 
                   17270: mkdiruserfile(): creates a directory is a userfiles dir
                   17271: 
                   17272:   Args:
                   17273:    docuname: username or courseid of destination for the file
                   17274:    docudom: domain of user/course of destination for the file
                   17275:    dir: dir to create (including any subdirs under userfiles)
                   17276: 
                   17277: =item *
                   17278: 
                   17279: removeuserfile(): removes a file that exists in userfiles
                   17280: 
                   17281:   Args:
                   17282:    docuname: username or courseid of destination for the file
                   17283:    docudom: domain of user/course of destination for the file
                   17284:    fname: filname to delete (including any subdirs under userfiles)
                   17285: 
                   17286: =item *
                   17287: 
                   17288: removeuploadedurl(): convience function for removeuserfile()
                   17289: 
                   17290:   Args:
                   17291:    url:  a full /uploaded/... url to delete
                   17292: 
1.747     albertel 17293: =item * 
                   17294: 
                   17295: get_portfile_permissions():
                   17296:   Args:
                   17297:     domain: domain of user or course contain the portfolio files
                   17298:     user: name of user or num of course contain the portfolio files
                   17299:   Returns:
                   17300:     hashref of a dump of the proper file_permissions.db
                   17301:    
                   17302: 
                   17303: =item * 
                   17304: 
                   17305: get_access_controls():
                   17306: 
                   17307: Args:
                   17308:   current_permissions: the hash ref returned from get_portfile_permissions()
                   17309:   group: (optional) the group you want the files associated with
                   17310:   file: (optional) the file you want access info on
                   17311: 
                   17312: Returns:
1.749     raeburn  17313:     a hash (keys are file names) of hashes containing
                   17314:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   17315:         values are XML containing access control settings (see below) 
1.747     albertel 17316: 
                   17317: Internal notes:
                   17318: 
1.749     raeburn  17319:  access controls are stored in file_permissions.db as key=value pairs.
                   17320:     key -> path to file/file_name\0uniqueID:scope_end_start
                   17321:         where scope -> public,guest,course,group,domains or users.
                   17322:               end -> UNIX time for end of access (0 -> no end date)
                   17323:               start -> UNIX time for start of access
                   17324: 
                   17325:     value -> XML description of access control
                   17326:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   17327:             <start></start>
                   17328:             <end></end>
                   17329: 
                   17330:             <password></password>  for scope type = guest
                   17331: 
                   17332:             <domain></domain>     for scope type = course or group
                   17333:             <number></number>
                   17334:             <roles id="">
                   17335:              <role></role>
                   17336:              <access></access>
                   17337:              <section></section>
                   17338:              <group></group>
                   17339:             </roles>
                   17340: 
                   17341:             <dom></dom>         for scope type = domains
                   17342: 
                   17343:             <users>             for scope type = users
                   17344:              <user>
                   17345:               <uname></uname>
                   17346:               <udom></udom>
                   17347:              </user>
                   17348:             </users>
                   17349:            </scope> 
                   17350:               
                   17351:  Access data is also aggregated for each file in an additional key=value pair:
                   17352:  key -> path to file/file_name\0accesscontrol 
                   17353:  value -> reference to hash
                   17354:           hash contains key = value pairs
                   17355:           where key = uniqueID:scope_end_start
                   17356:                 value = UNIX time record was last updated
                   17357: 
                   17358:           Used to improve speed of look-ups of access controls for each file.  
                   17359:  
                   17360:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   17361: 
1.1198    raeburn  17362: =item *
                   17363: 
1.749     raeburn  17364: modify_access_controls():
                   17365: 
                   17366: Modifies access controls for a portfolio file
                   17367: Args
                   17368: 1. file name
                   17369: 2. reference to hash of required changes,
                   17370: 3. domain
                   17371: 4. username
                   17372:   where domain,username are the domain of the portfolio owner 
                   17373:   (either a user or a course) 
                   17374: 
                   17375: Returns:
                   17376: 1. result of additions or updates ('ok' or 'error', with error message). 
                   17377: 2. result of deletions ('ok' or 'error', with error message).
                   17378: 3. reference to hash of any new or updated access controls.
                   17379: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   17380:    key = integer (inbound ID)
1.1198    raeburn  17381:    value = uniqueID
                   17382: 
                   17383: =item *
                   17384: 
                   17385: get_timebased_id():
                   17386: 
                   17387: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   17388: course via the Course Editor (e.g., folders, composite pages, 
                   17389: group bulletin boards).
                   17390: 
                   17391: Args: (first three required; six others optional)
                   17392: 
                   17393: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   17394:    docssequence, or name of group
                   17395: 
                   17396: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   17397:    e.g., num, boardids
                   17398: 
                   17399: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   17400:    file will be named nohist_namespace.db
                   17401: 
                   17402: 4. cdom: domain of course; default is current course domain from %env
                   17403: 
                   17404: 5. cnum: course number; default is current course number from %env
                   17405: 
                   17406: 6. idtype: set to concat if an additional digit is to be appended to the 
                   17407:    unix timestamp to form the suffix, if the plain timestamp is already
                   17408:    in use.  Default is to not do this, but simply increment the unix 
                   17409:    timestamp by 1 until a unique key is obtained.
                   17410: 
                   17411: 7. who: holder of locking key; defaults to user:domain for user.
                   17412: 
                   17413: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   17414:    retrying); default is 3.
                   17415: 
                   17416: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   17417: 
                   17418: Returns:
                   17419: 
                   17420: 1. suffix obtained (numeric)
                   17421: 
                   17422: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   17423: 
                   17424: 3. error: contains (localized) error message if an error occurred.
                   17425: 
1.747     albertel 17426: 
1.608     albertel 17427: =back
                   17428: 
1.243     albertel 17429: =head2 HTTP Helper Routines
                   17430: 
                   17431: =over 4
                   17432: 
1.191     harris41 17433: =item *
                   17434: 
                   17435: escape() : unpack non-word characters into CGI-compatible hex codes
                   17436: 
                   17437: =item *
                   17438: 
                   17439: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   17440: 
1.243     albertel 17441: =back
                   17442: 
                   17443: =head1 PRIVATE SUBROUTINES
                   17444: 
                   17445: =head2 Underlying communication routines (Shouldn't call)
                   17446: 
                   17447: =over 4
                   17448: 
                   17449: =item *
                   17450: 
                   17451: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   17452: 
                   17453: =item *
                   17454: 
                   17455: reply() : uses subreply to send a message to remote machine, logs all failures
                   17456: 
                   17457: =item *
                   17458: 
                   17459: critical() : passes a critical message to another server; if cannot
                   17460: get through then place message in connection buffer directory and
                   17461: returns con_delayed, if incapable of saving message, returns
                   17462: con_failed
                   17463: 
                   17464: =item *
                   17465: 
                   17466: reconlonc() : tries to reconnect lonc client processes.
                   17467: 
                   17468: =back
                   17469: 
                   17470: =head2 Resource Access Logging
                   17471: 
                   17472: =over 4
                   17473: 
                   17474: =item *
                   17475: 
                   17476: flushcourselogs() : flush (save) buffer logs and access logs
                   17477: 
                   17478: =item *
                   17479: 
                   17480: courselog($what) : save message for course in hash
                   17481: 
                   17482: =item *
                   17483: 
                   17484: courseacclog($what) : save message for course using &courselog().  Perform
                   17485: special processing for specific resource types (problems, exams, quizzes, etc).
                   17486: 
1.191     harris41 17487: =item *
                   17488: 
                   17489: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   17490: as a PerlChildExitHandler
1.243     albertel 17491: 
                   17492: =back
                   17493: 
                   17494: =head2 Other
                   17495: 
                   17496: =over 4
                   17497: 
                   17498: =item *
                   17499: 
                   17500: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 17501: 
                   17502: =back
                   17503: 
                   17504: =cut
1.877     foxr     17505: 

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