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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1472  ! raeburn     4: # $Id: lonnet.pm,v 1.1471 2021/11/09 20:14:04 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);
                   1326:     if (!$uhome) {
                   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");
                   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.1023    raeburn  2265: # ----------------------------------construct domainconfig user for a domain 
                   2266: sub get_domainconfiguser {
                   2267:     my ($udom) = @_;
                   2268:     return $udom.'-domainconfig';
                   2269: }
                   2270: 
1.837     raeburn  2271: sub retrieve_inst_usertypes {
                   2272:     my ($udom) = @_;
                   2273:     my (%returnhash,@order);
1.989     raeburn  2274:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2275:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2276:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2277:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2278:     } else {
                   2279:         if (defined(&domain($udom,'primary'))) {
                   2280:             my $uhome=&domain($udom,'primary');
                   2281:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2282:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2283:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2284:                 return (\%returnhash,\@order);
                   2285:             }
                   2286:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2287:             my @pairs=split(/\&/,$hashitems);
                   2288:             foreach my $item (@pairs) {
                   2289:                 my ($key,$value)=split(/=/,$item,2);
                   2290:                 $key = &unescape($key);
                   2291:                 next if ($key =~ /^error: 2 /);
                   2292:                 $returnhash{$key}=&thaw_unescape($value);
                   2293:             }
                   2294:             my @esc_order = split(/\&/,$orderitems);
                   2295:             foreach my $item (@esc_order) {
                   2296:                 push(@order,&unescape($item));
                   2297:             }
                   2298:         } else {
1.1256    raeburn  2299:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2300:         }
1.1256    raeburn  2301:         return (\%returnhash,\@order);
1.837     raeburn  2302:     }
                   2303: }
                   2304: 
1.868     raeburn  2305: sub is_domainimage {
                   2306:     my ($url) = @_;
1.1468    raeburn  2307:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868     raeburn  2308:         if (&domain($1) ne '') {
                   2309:             return '1';
                   2310:         }
                   2311:     }
                   2312:     return;
                   2313: }
                   2314: 
1.899     raeburn  2315: sub inst_directory_query {
                   2316:     my ($srch) = @_;
                   2317:     my $udom = $srch->{'srchdomain'};
                   2318:     my %results;
                   2319:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2320:     my $outcome;
1.899     raeburn  2321:     if ($homeserver ne '') {
1.1357    raeburn  2322:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2323:             if ($srch->{'srchby'} eq 'email') {
1.1417    raeburn  2324:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1357    raeburn  2325:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2326:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2327:                     (($major == 2) && ($minor < 12))) {
                   2328:                     return;
                   2329:                 }
                   2330:             }
                   2331:         }
1.904     albertel 2332: 	my $queryid=&reply("querysend:instdirsearch:".
                   2333: 			   &escape($srch->{'srchby'}).':'.
                   2334: 			   &escape($srch->{'srchterm'}).':'.
                   2335: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2336: 	my $host=&hostname($homeserver);
                   2337: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2338: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2339: 	    return;
                   2340: 	}
                   2341: 	my $response = &get_query_reply($queryid);
                   2342: 	my $maxtries = 5;
                   2343: 	my $tries = 1;
                   2344: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2345: 	    $response = &get_query_reply($queryid);
                   2346: 	    $tries ++;
                   2347: 	}
                   2348: 
                   2349:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2350:             if ($response eq 'unavailable') {
                   2351:                 $outcome = $response;
                   2352:             } else {
                   2353:                 $outcome = 'ok';
                   2354:                 my @matches = split(/\n/,$response);
                   2355:                 foreach my $match (@matches) {
                   2356:                     my ($key,$value) = split(/=/,$match);
                   2357:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2358:                 }
1.899     raeburn  2359:             }
                   2360:         }
                   2361:     }
1.909     raeburn  2362:     return ($outcome,%results);
1.899     raeburn  2363: }
                   2364: 
                   2365: sub usersearch {
                   2366:     my ($srch) = @_;
                   2367:     my $dom = $srch->{'srchdomain'};
                   2368:     my %results;
                   2369:     my %libserv = &all_library();
                   2370:     my $query = 'usersearch';
                   2371:     foreach my $tryserver (keys(%libserv)) {
                   2372:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2373:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2374:                 if ($srch->{'srchby'} eq 'email') {
1.1417    raeburn  2375:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1357    raeburn  2376:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2377:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2378:                              (($major == 2) && ($minor < 12)));
                   2379:                 }
                   2380:             }
1.899     raeburn  2381:             my $host=&hostname($tryserver);
                   2382:             my $queryid=
1.911     raeburn  2383:                 &reply("querysend:".&escape($query).':'.
                   2384:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2385:                        &escape($srch->{'srchtype'}).':'.
                   2386:                        &escape($srch->{'srchterm'}),$tryserver);
                   2387:             if ($queryid !~/^\Q$host\E\_/) {
                   2388:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2389:                 next;
1.899     raeburn  2390:             }
                   2391:             my $reply = &get_query_reply($queryid);
                   2392:             my $maxtries = 1;
                   2393:             my $tries = 1;
                   2394:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2395:                 $reply = &get_query_reply($queryid);
                   2396:                 $tries ++;
                   2397:             }
                   2398:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2399:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2400:             } else {
1.911     raeburn  2401:                 my @matches;
                   2402:                 if ($reply =~ /\n/) {
                   2403:                     @matches = split(/\n/,$reply);
                   2404:                 } else {
                   2405:                     @matches = split(/\&/,$reply);
                   2406:                 }
1.899     raeburn  2407:                 foreach my $match (@matches) {
                   2408:                     my ($uname,$udom,%userhash);
1.911     raeburn  2409:                     foreach my $entry (split(/:/,$match)) {
                   2410:                         my ($key,$value) =
                   2411:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2412:                         $userhash{$key} = $value;
                   2413:                         if ($key eq 'username') {
                   2414:                             $uname = $value;
                   2415:                         } elsif ($key eq 'domain') {
                   2416:                             $udom = $value;
1.911     raeburn  2417:                         }
1.899     raeburn  2418:                     }
                   2419:                     $results{$uname.':'.$udom} = \%userhash;
                   2420:                 }
                   2421:             }
                   2422:         }
                   2423:     }
                   2424:     return %results;
                   2425: }
                   2426: 
1.912     raeburn  2427: sub get_instuser {
                   2428:     my ($udom,$uname,$id) = @_;
                   2429:     my $homeserver = &domain($udom,'primary');
                   2430:     my ($outcome,%results);
                   2431:     if ($homeserver ne '') {
                   2432:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2433:                            &escape($id).':'.&escape($udom),$homeserver);
                   2434:         my $host=&hostname($homeserver);
                   2435:         if ($queryid !~/^\Q$host\E\_/) {
                   2436:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2437:             return;
                   2438:         }
                   2439:         my $response = &get_query_reply($queryid);
                   2440:         my $maxtries = 5;
                   2441:         my $tries = 1;
                   2442:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2443:             $response = &get_query_reply($queryid);
                   2444:             $tries ++;
                   2445:         }
                   2446:         if (!&error($response) && $response ne 'refused') {
                   2447:             if ($response eq 'unavailable') {
                   2448:                 $outcome = $response;
                   2449:             } else {
                   2450:                 $outcome = 'ok';
                   2451:                 my @matches = split(/\n/,$response);
                   2452:                 foreach my $match (@matches) {
                   2453:                     my ($key,$value) = split(/=/,$match);
                   2454:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2455:                 }
                   2456:             }
                   2457:         }
                   2458:     }
                   2459:     my %userinfo;
                   2460:     if (ref($results{$uname}) eq 'HASH') {
                   2461:         %userinfo = %{$results{$uname}};
                   2462:     } 
                   2463:     return ($outcome,%userinfo);
                   2464: }
                   2465: 
1.1290    raeburn  2466: sub get_multiple_instusers {
                   2467:     my ($udom,$users,$caller) = @_;
                   2468:     my ($outcome,$results);
                   2469:     if (ref($users) eq 'HASH') {
                   2470:         my $count = keys(%{$users}); 
                   2471:         my $requested = &freeze_escape($users);
                   2472:         my $homeserver = &domain($udom,'primary');
                   2473:         if ($homeserver ne '') {
                   2474:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2475:             my $host=&hostname($homeserver);
                   2476:             if ($queryid !~/^\Q$host\E\_/) {
                   2477:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2478:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2479:                 return ($outcome,$results);
                   2480:             }
                   2481:             my $response = &get_query_reply($queryid);
                   2482:             my $maxtries = 5;
                   2483:             if ($count > 100) {
                   2484:                 $maxtries = 1+int($count/20);
                   2485:             }
                   2486:             my $tries = 1;
                   2487:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2488:                 $response = &get_query_reply($queryid);
                   2489:                 $tries ++;
                   2490:             }
                   2491:             if ($response eq '') {
                   2492:                 $results = {};
                   2493:                 foreach my $key (keys(%{$users})) {
                   2494:                     my ($uname,$id);
                   2495:                     if ($caller eq 'id') {
                   2496:                         $id = $key;
                   2497:                     } else {
                   2498:                         $uname = $key;
                   2499:                     }
                   2500:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2501:                     $outcome = $resp;
1.1290    raeburn  2502:                     if ($resp eq 'ok') {
                   2503:                         %{$results} = (%{$results}, %info);
                   2504:                     } else {
                   2505:                         last;
                   2506:                     }
                   2507:                 }
                   2508:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2509:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2510:                     $outcome = $response;
                   2511:                 } else {
1.1291    raeburn  2512:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2513:                     if ($outcome eq 'ok') {
                   2514:                         $results = &thaw_unescape($userdata); 
                   2515:                     }
                   2516:                 }
                   2517:             }
                   2518:         }
                   2519:     }
                   2520:     return ($outcome,$results);
                   2521: }
                   2522: 
1.912     raeburn  2523: sub inst_rulecheck {
1.923     raeburn  2524:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2525:     my %returnhash;
                   2526:     if ($udom ne '') {
                   2527:         if (ref($rules) eq 'ARRAY') {
                   2528:             @{$rules} = map {&escape($_);} (@{$rules});
                   2529:             my $rulestr = join(':',@{$rules});
                   2530:             my $homeserver=&domain($udom,'primary');
                   2531:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2532:                 my $response;
                   2533:                 if ($item eq 'username') {                
                   2534:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2535:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2536:                                               $homeserver));
1.923     raeburn  2537:                 } elsif ($item eq 'id') {
                   2538:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2539:                                               ':'.&escape($id).':'.$rulestr,
                   2540:                                               $homeserver));
1.945     raeburn  2541:                 } elsif ($item eq 'selfcreate') {
                   2542:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2543:                                                &escape($udom).':'.&escape($uname).
                   2544:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2545:                 }
1.912     raeburn  2546:                 if ($response ne 'refused') {
                   2547:                     my @pairs=split(/\&/,$response);
                   2548:                     foreach my $item (@pairs) {
                   2549:                         my ($key,$value)=split(/=/,$item,2);
                   2550:                         $key = &unescape($key);
                   2551:                         next if ($key =~ /^error: 2 /);
                   2552:                         $returnhash{$key}=&thaw_unescape($value);
                   2553:                     }
                   2554:                 }
                   2555:             }
                   2556:         }
                   2557:     }
                   2558:     return %returnhash;
                   2559: }
                   2560: 
                   2561: sub inst_userrules {
1.923     raeburn  2562:     my ($udom,$check) = @_;
1.912     raeburn  2563:     my (%ruleshash,@ruleorder);
                   2564:     if ($udom ne '') {
                   2565:         my $homeserver=&domain($udom,'primary');
                   2566:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2567:             my $response;
                   2568:             if ($check eq 'id') {
                   2569:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2570:                                  $homeserver);
1.943     raeburn  2571:             } elsif ($check eq 'email') {
                   2572:                 $response=&reply('instemailrules:'.&escape($udom),
                   2573:                                  $homeserver);
1.923     raeburn  2574:             } else {
                   2575:                 $response=&reply('instuserrules:'.&escape($udom),
                   2576:                                  $homeserver);
                   2577:             }
1.912     raeburn  2578:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2579:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2580:                 ($response ne 'no_such_host')) {
                   2581:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2582:                 my @pairs=split(/\&/,$hashitems);
                   2583:                 foreach my $item (@pairs) {
                   2584:                     my ($key,$value)=split(/=/,$item,2);
                   2585:                     $key = &unescape($key);
                   2586:                     next if ($key =~ /^error: 2 /);
                   2587:                     $ruleshash{$key}=&thaw_unescape($value);
                   2588:                 }
                   2589:                 my @esc_order = split(/\&/,$orderitems);
                   2590:                 foreach my $item (@esc_order) {
                   2591:                     push(@ruleorder,&unescape($item));
                   2592:                 }
                   2593:             }
                   2594:         }
                   2595:     }
                   2596:     return (\%ruleshash,\@ruleorder);
                   2597: }
                   2598: 
1.976     raeburn  2599: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2600: 
                   2601: sub get_domain_defaults {
1.1240    raeburn  2602:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2603:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2604:     my $cachetime = 60*60*24;
1.1240    raeburn  2605:     unless ($ignore_cache) {
                   2606:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2607:         if (defined($cached)) {
                   2608:             if (ref($result) eq 'HASH') {
                   2609:                 return %{$result};
                   2610:             }
1.943     raeburn  2611:         }
                   2612:     }
                   2613:     my %domdefaults;
                   2614:     my %domconfig =
1.989     raeburn  2615:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2616:                                   'requestcourses','inststatus',
1.1183    raeburn  2617:                                   'coursedefaults','usersessions',
1.1258    raeburn  2618:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2619:                                   'coursecategories','ssl','autoenroll',
1.1434    raeburn  2620:                                   'trust','helpsettings','wafproxy'],$domain);
1.1305    raeburn  2621:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2622:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2623:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2624:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2625:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2626:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2627:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2628:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2629:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2630:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2631:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2632:     } else {
                   2633:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2634:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2635:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2636:     }
1.976     raeburn  2637:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2638:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2639:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2640:         } else {
                   2641:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2642:         }
1.1177    raeburn  2643:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2644:         foreach my $item (@usertools) {
                   2645:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2646:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2647:             }
                   2648:         }
1.1229    raeburn  2649:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2650:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2651:         }
1.976     raeburn  2652:     }
1.985     raeburn  2653:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2654:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2655:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2656:         }
                   2657:     }
1.1183    raeburn  2658:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2659:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2660:     }
1.989     raeburn  2661:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2662:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2663:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2664:         }
                   2665:     }
1.1047    raeburn  2666:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2667:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2668:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2669:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2670:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2671:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2672:         }
1.1254    raeburn  2673:         foreach my $type (@coursetypes) {
                   2674:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2675:                 unless ($type eq 'community') {
                   2676:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2677:                 }
                   2678:             }
                   2679:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2680:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2681:             }
1.1277    raeburn  2682:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2683:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2684:                     $domdefaults{$type.'postsubtimeout'} = 
                   2685:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2686:                 }
                   2687:             }
1.1230    raeburn  2688:         }
1.1286    raeburn  2689:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2690:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2691:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2692:                 if (@clonecodes) {
                   2693:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2694:                 }
                   2695:             }
                   2696:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2697:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2698:         }
1.1356    raeburn  2699:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2700:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2701:         } 
1.1047    raeburn  2702:     }
1.1073    raeburn  2703:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2704:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2705:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2706:         }
                   2707:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2708:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2709:         }
1.1279    raeburn  2710:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2711:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2712:         }
1.1440    raeburn  2713:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1439    raeburn  2714:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2715:         }
1.1073    raeburn  2716:     }
1.1254    raeburn  2717:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2718:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2719:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2720:                             'approval','limit');
                   2721:             foreach my $type (@coursetypes) {
                   2722:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2723:                     my @mgrdc = ();
                   2724:                     foreach my $item (@settings) {
                   2725:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2726:                             push(@mgrdc,$item);
                   2727:                         }
                   2728:                     }
                   2729:                     if (@mgrdc) {
                   2730:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2731:                     }
                   2732:                 }
                   2733:             }
                   2734:         }
                   2735:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2736:             foreach my $type (@coursetypes) {
                   2737:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2738:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2739:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2740:                     }
                   2741:                 }
                   2742:             }
                   2743:         }
                   2744:     }
1.1258    raeburn  2745:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2746:         $domdefaults{'catauth'} = 'std';
                   2747:         $domdefaults{'catunauth'} = 'std';
1.1413    raeburn  2748:         if ($domconfig{'coursecategories'}{'auth'}) {
1.1258    raeburn  2749:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2750:         }
                   2751:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2752:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2753:         }
                   2754:     }
1.1315    raeburn  2755:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2756:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2757:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2758:         }
1.1338    raeburn  2759:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2760:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2761:         }
                   2762:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2763:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2764:         }
                   2765:     }
1.1320    raeburn  2766:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2767:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2768:         foreach my $prefix (@prefixes) {
                   2769:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2770:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2771:             }
                   2772:         }
                   2773:     }
1.1314    raeburn  2774:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2775:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2776:     }
1.1332    raeburn  2777:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2778:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2779:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2780:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2781:         }
                   2782:     }
1.1434    raeburn  2783:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
1.1449    raeburn  2784:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
1.1434    raeburn  2785:             if ($domconfig{'wafproxy'}{$item}) {
                   2786:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
                   2787:             }
                   2788:         }
                   2789:     } 
1.1219    raeburn  2790:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2791:     return %domdefaults;
                   2792: }
                   2793: 
1.1412    raeburn  2794: sub get_dom_cats {
                   2795:     my ($dom) = @_;
                   2796:     return unless (&domain($dom));
                   2797:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2798:     unless (defined($cached)) {
                   2799:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2800:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2801:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2802:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2803:             } else {
                   2804:                 $cats = {};
                   2805:             }
                   2806:         } else {
                   2807:             $cats = {};
                   2808:         }
                   2809:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2810:     }
1.1413    raeburn  2811:     return $cats;
                   2812: }
                   2813: 
                   2814: sub get_dom_instcats {
                   2815:     my ($dom) = @_;
                   2816:     return unless (&domain($dom));
                   2817:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2818:     unless (defined($cached)) {
                   2819:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2820:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2821:         if ($totcodes > 0) {
                   2822:             my $caller = 'global';
                   2823:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2824:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2825:                 $instcats = {
                   2826:                                 codes => \%codes,
                   2827:                                 codetitles => \@codetitles,
                   2828:                                 cat_titles => \%cat_titles,
                   2829:                                 cat_order => \%cat_order,
                   2830:                             };
                   2831:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2832:             }
                   2833:         }
                   2834:     }
                   2835:     return $instcats;
                   2836: }
                   2837: 
                   2838: sub retrieve_instcodes {
                   2839:     my ($coursecodes,$dom) = @_;
                   2840:     my $totcodes;
                   2841:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2842:     foreach my $course (keys(%courses)) {
                   2843:         if (ref($courses{$course}) eq 'HASH') {
                   2844:             if ($courses{$course}{'inst_code'} ne '') {
                   2845:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2846:                 $totcodes ++;
                   2847:             }
                   2848:         }
                   2849:     }
                   2850:     return $totcodes;
1.1412    raeburn  2851: }
                   2852: 
1.1311    raeburn  2853: sub course_portal_url {
1.1451    raeburn  2854:     my ($cnum,$cdom,$r) = @_;
1.1311    raeburn  2855:     my $chome = &homeserver($cnum,$cdom);
                   2856:     my $hostname = &hostname($chome);
                   2857:     my $protocol = $protocol{$chome};
                   2858:     $protocol = 'http' if ($protocol ne 'https');
                   2859:     my %domdefaults = &get_domain_defaults($cdom);
                   2860:     my $firsturl;
                   2861:     if ($domdefaults{'portal_def'}) {
                   2862:         $firsturl = $domdefaults{'portal_def'};
                   2863:     } else {
1.1451    raeburn  2864:         my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
                   2865:         $hostname = $alias if ($alias ne '');
1.1311    raeburn  2866:         $firsturl = $protocol.'://'.$hostname;
                   2867:     }
                   2868:     return $firsturl;
                   2869: }
                   2870: 
1.1407    raeburn  2871: # --------------------------------------------- Get domain config for passwords
                   2872: 
                   2873: sub get_passwdconf {
                   2874:     my ($dom) = @_;
                   2875:     my (%passwdconf,$gotconf,$lookup);
                   2876:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2877:     if (defined($cached)) {
                   2878:         if (ref($result) eq 'HASH') {
                   2879:             %passwdconf = %{$result};
                   2880:             $gotconf = 1;
                   2881:         }
                   2882:     }
                   2883:     unless ($gotconf) {
                   2884:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2885:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2886:             %passwdconf = %{$domconfig{'passwords'}};
                   2887:         }
                   2888:         my $cachetime = 24*60*60;
                   2889:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2890:     }
                   2891:     return %passwdconf;
                   2892: }
                   2893: 
1.344     www      2894: # --------------------------------------------------- Assign a key to a student
                   2895: 
                   2896: sub assign_access_key {
1.364     www      2897: #
                   2898: # a valid key looks like uname:udom#comments
                   2899: # comments are being appended
                   2900: #
1.498     www      2901:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2902:     $kdom=
1.620     albertel 2903:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2904:     $knum=
1.620     albertel 2905:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2906:     $cdom=
1.620     albertel 2907:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2908:     $cnum=
1.620     albertel 2909:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2910:     $udom=$env{'user.name'} unless (defined($udom));
                   2911:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2912:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2913:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2914:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2915:                                                   # assigned to this person
                   2916:                                                   # - this should not happen,
1.345     www      2917:                                                   # unless something went wrong
                   2918:                                                   # the first time around
                   2919: # ready to assign
1.364     www      2920:         $logentry=$1.'; '.$logentry;
1.496     www      2921:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2922:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2923: # key now belongs to user
1.346     www      2924: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2925:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2926:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2927:                 return 'ok';
                   2928:             } else {
                   2929:                 return 
                   2930:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2931: 	    }
                   2932:         } else {
                   2933:             return 'error: Could not assign key, try again later.';
                   2934:         }
1.364     www      2935:     } elsif (!$existing{$ckey}) {
1.345     www      2936: # the key does not exist
                   2937: 	return 'error: The key does not exist';
                   2938:     } else {
                   2939: # the key is somebody else's
                   2940: 	return 'error: The key is already in use';
                   2941:     }
1.344     www      2942: }
                   2943: 
1.364     www      2944: # ------------------------------------------ put an additional comment on a key
                   2945: 
                   2946: sub comment_access_key {
                   2947: #
                   2948: # a valid key looks like uname:udom#comments
                   2949: # comments are being appended
                   2950: #
                   2951:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2952:     $cdom=
1.620     albertel 2953:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2954:     $cnum=
1.620     albertel 2955:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2956:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2957:     if ($existing{$ckey}) {
                   2958:         $existing{$ckey}.='; '.$logentry;
                   2959: # ready to assign
1.367     www      2960:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2961:                                                  $cdom,$cnum) eq 'ok') {
                   2962: 	    return 'ok';
                   2963:         } else {
                   2964: 	    return 'error: Count not store comment.';
                   2965:         }
                   2966:     } else {
                   2967: # the key does not exist
                   2968: 	return 'error: The key does not exist';
                   2969:     }
                   2970: }
                   2971: 
1.344     www      2972: # ------------------------------------------------------ Generate a set of keys
                   2973: 
                   2974: sub generate_access_keys {
1.364     www      2975:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2976:     $cdom=
1.620     albertel 2977:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2978:     $cnum=
1.620     albertel 2979:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2980:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2981:     unless (($cdom) && ($cnum)) { return 0; }
                   2982:     if ($number>10000) { return 0; }
                   2983:     sleep(2); # make sure don't get same seed twice
                   2984:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2985:     my $total=0;
                   2986:     for (my $i=1;$i<=$number;$i++) {
                   2987:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2988:                   sprintf("%lx",int(100000*rand)).'-'.
                   2989:                   sprintf("%lx",int(100000*rand));
                   2990:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2991:        $newkey=~s/0/h/g; # and also 0 and O
                   2992:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2993:        if ($existing{$newkey}) {
                   2994:            $i--;
                   2995:        } else {
1.364     www      2996: 	  if (&put('accesskeys',
                   2997:               { $newkey => '# generated '.localtime().
1.620     albertel 2998:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2999:                            '; '.$logentry },
                   3000: 		   $cdom,$cnum) eq 'ok') {
1.344     www      3001:               $total++;
                   3002: 	  }
                   3003:        }
                   3004:     }
1.620     albertel 3005:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      3006:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   3007:     return $total;
                   3008: }
                   3009: 
                   3010: # ------------------------------------------------------- Validate an accesskey
                   3011: 
                   3012: sub validate_access_key {
                   3013:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   3014:     $cdom=
1.620     albertel 3015:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      3016:     $cnum=
1.620     albertel 3017:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   3018:     $udom=$env{'user.domain'} unless (defined($udom));
                   3019:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      3020:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 3021:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      3022: }
                   3023: 
                   3024: # ------------------------------------- Find the section of student in a course
1.652     albertel 3025: sub devalidate_getsection_cache {
                   3026:     my ($udom,$unam,$courseid)=@_;
                   3027:     my $hashid="$udom:$unam:$courseid";
                   3028:     &devalidate_cache_new('getsection',$hashid);
                   3029: }
1.298     matthew  3030: 
1.815     albertel 3031: sub courseid_to_courseurl {
                   3032:     my ($courseid) = @_;
                   3033:     #already url style courseid
                   3034:     return $courseid if ($courseid =~ m{^/});
                   3035: 
                   3036:     if (exists($env{'course.'.$courseid.'.num'})) {
                   3037: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   3038: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   3039: 	return "/$cdom/$cnum";
                   3040:     }
                   3041: 
                   3042:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   3043:     if (exists($courseinfo{'num'})) {
                   3044: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   3045:     }
                   3046: 
                   3047:     return undef;
                   3048: }
                   3049: 
1.298     matthew  3050: sub getsection {
                   3051:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 3052:     my $cachetime=1800;
1.551     albertel 3053: 
                   3054:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 3055:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 3056:     if (defined($cached)) { return $result; }
                   3057: 
1.298     matthew  3058:     my %Pending; 
                   3059:     my %Expired;
                   3060:     #
                   3061:     # Each role can either have not started yet (pending), be active, 
                   3062:     #    or have expired.
                   3063:     #
                   3064:     # If there is an active role, we are done.
                   3065:     #
                   3066:     # If there is more than one role which has not started yet, 
                   3067:     #     choose the one which will start sooner
                   3068:     # If there is one role which has not started yet, return it.
                   3069:     #
                   3070:     # If there is more than one expired role, choose the one which ended last.
                   3071:     # If there is a role which has expired, return it.
                   3072:     #
1.815     albertel 3073:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  3074:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  3075:     foreach my $key (keys(%roleshash)) {
1.479     albertel 3076:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  3077:         my $section=$1;
                   3078:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  3079:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  3080:         my $now=time;
1.548     albertel 3081:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  3082:             $Expired{$end}=$section;
                   3083:             next;
                   3084:         }
1.548     albertel 3085:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  3086:             $Pending{$start}=$section;
                   3087:             next;
                   3088:         }
1.599     albertel 3089:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  3090:     }
                   3091:     #
                   3092:     # Presumedly there will be few matching roles from the above
                   3093:     # loop and the sorting time will be negligible.
                   3094:     if (scalar(keys(%Pending))) {
                   3095:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 3096:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  3097:     } 
                   3098:     if (scalar(keys(%Expired))) {
                   3099:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   3100:         my $time = pop(@sorted);
1.599     albertel 3101:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  3102:     }
1.599     albertel 3103:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  3104: }
1.70      www      3105: 
1.599     albertel 3106: sub save_cache {
                   3107:     &purge_remembered();
1.722     albertel 3108:     #&Apache::loncommon::validate_page();
1.620     albertel 3109:     undef(%env);
1.780     albertel 3110:     undef($env_loaded);
1.599     albertel 3111: }
1.452     albertel 3112: 
1.599     albertel 3113: my $to_remember=-1;
                   3114: my %remembered;
                   3115: my %accessed;
                   3116: my $kicks=0;
                   3117: my $hits=0;
1.849     albertel 3118: sub make_key {
                   3119:     my ($name,$id) = @_;
1.872     albertel 3120:     if (length($id) > 65 
                   3121: 	&& length(&escape($id)) > 200) {
                   3122: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   3123:     }
1.849     albertel 3124:     return &escape($name.':'.$id);
                   3125: }
                   3126: 
1.599     albertel 3127: sub devalidate_cache_new {
                   3128:     my ($name,$id,$debug) = @_;
                   3129:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  3130:     my $remembered_id=$name.':'.$id;
1.849     albertel 3131:     $id=&make_key($name,$id);
1.599     albertel 3132:     $memcache->delete($id);
1.1319    damieng  3133:     delete($remembered{$remembered_id});
                   3134:     delete($accessed{$remembered_id});
1.599     albertel 3135: }
                   3136: 
                   3137: sub is_cached_new {
                   3138:     my ($name,$id,$debug) = @_;
1.1319    damieng  3139:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   3140:     if (exists($remembered{$remembered_id})) {
                   3141: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   3142: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3143: 	$hits++;
1.1319    damieng  3144: 	return ($remembered{$remembered_id},1);
1.599     albertel 3145:     }
1.1319    damieng  3146:     $id=&make_key($name,$id);
1.599     albertel 3147:     my $value = $memcache->get($id);
                   3148:     if (!(defined($value))) {
                   3149: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 3150: 	return (undef,undef);
1.416     albertel 3151:     }
1.599     albertel 3152:     if ($value eq '__undef__') {
                   3153: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   3154: 	$value=undef;
                   3155:     }
1.1319    damieng  3156:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3157:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   3158:     return ($value,1);
                   3159: }
                   3160: 
                   3161: sub do_cache_new {
                   3162:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  3163:     my $remembered_id=$name.':'.$id;
1.849     albertel 3164:     $id=&make_key($name,$id);
1.599     albertel 3165:     my $setvalue=$value;
                   3166:     if (!defined($setvalue)) {
                   3167: 	$setvalue='__undef__';
                   3168:     }
1.623     albertel 3169:     if (!defined($time) ) {
                   3170: 	$time=600;
                   3171:     }
1.599     albertel 3172:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 3173:     my $result = $memcache->set($id,$setvalue,$time);
                   3174:     if (! $result) {
1.872     albertel 3175: 	&logthis("caching of id -> $id  failed");
1.910     albertel 3176: 	$memcache->disconnect_all();
1.872     albertel 3177:     }
1.600     albertel 3178:     # need to make a copy of $value
1.1319    damieng  3179:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3180:     return $value;
                   3181: }
                   3182: 
                   3183: sub make_room {
1.1319    damieng  3184:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3185: 
1.1319    damieng  3186:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3187:                                     : $value;
1.599     albertel 3188:     if ($to_remember<0) { return; }
1.1319    damieng  3189:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3190:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3191:     my $to_kick;
                   3192:     my $max_time=0;
                   3193:     foreach my $other (keys(%accessed)) {
                   3194: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3195: 	    $to_kick=$other;
                   3196: 	    $max_time=&tv_interval($accessed{$other});
                   3197: 	}
                   3198:     }
                   3199:     delete($remembered{$to_kick});
                   3200:     delete($accessed{$to_kick});
                   3201:     $kicks++;
                   3202:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3203:     return;
                   3204: }
                   3205: 
1.599     albertel 3206: sub purge_remembered {
1.604     albertel 3207:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3208:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3209:     undef(%remembered);
                   3210:     undef(%accessed);
1.428     albertel 3211: }
1.70      www      3212: # ------------------------------------- Read an entry from a user's environment
                   3213: 
                   3214: sub userenvironment {
                   3215:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3216:     my $items;
                   3217:     foreach my $item (@what) {
                   3218:         $items.=&escape($item).'&';
                   3219:     }
                   3220:     $items=~s/\&$//;
1.70      www      3221:     my %returnhash=();
1.1009    raeburn  3222:     my $uhome = &homeserver($unam,$udom);
                   3223:     unless ($uhome eq 'no_host') {
                   3224:         my @answer=split(/\&/, 
                   3225:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3226:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3227:             return %returnhash;
                   3228:         }
1.1009    raeburn  3229:         my $i;
                   3230:         for ($i=0;$i<=$#what;$i++) {
                   3231: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3232:         }
1.70      www      3233:     }
                   3234:     return %returnhash;
1.1       albertel 3235: }
                   3236: 
1.617     albertel 3237: # ---------------------------------------------------------- Get a studentphoto
                   3238: sub studentphoto {
                   3239:     my ($udom,$unam,$ext) = @_;
                   3240:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3241:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3242:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3243:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3244:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3245:             } else {
                   3246:                 my ($result,$perm_reqd)=
1.707     albertel 3247: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3248:                 if ($result eq 'ok') {
                   3249:                     if (!($perm_reqd eq 'yes')) {
                   3250:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3251:                     }
                   3252:                 }
                   3253:             }
                   3254:         }
                   3255:     } else {
                   3256:         my ($result,$perm_reqd) = 
1.707     albertel 3257: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3258:         if ($result eq 'ok') {
                   3259:             if (!($perm_reqd eq 'yes')) {
                   3260:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3261:             }
                   3262:         }
                   3263:     }
                   3264:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3265: }
                   3266: 
                   3267: sub retrievestudentphoto {
                   3268:     my ($udom,$unam,$ext,$type) = @_;
                   3269:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3270:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3271:     if ($ret eq 'ok') {
                   3272:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3273:         if ($type eq 'thumbnail') {
                   3274:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3275:         }
                   3276:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3277:         return $tokenurl;
                   3278:     } else {
                   3279:         if ($type eq 'thumbnail') {
                   3280:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3281:         } else { 
                   3282:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3283:         }
1.617     albertel 3284:     }
                   3285: }
                   3286: 
1.263     www      3287: # -------------------------------------------------------------------- New chat
                   3288: 
                   3289: sub chatsend {
1.724     raeburn  3290:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3291:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3292:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3293:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3294:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3295: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3296: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3297: }
                   3298: 
                   3299: # ------------------------------------------ Find current version of a resource
                   3300: 
                   3301: sub getversion {
                   3302:     my $fname=&clutter(shift);
1.1189    raeburn  3303:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3304:     return &currentversion(&filelocation('',$fname));
                   3305: }
                   3306: 
                   3307: sub currentversion {
                   3308:     my $fname=shift;
                   3309:     my $author=$fname;
                   3310:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3311:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3312:     my $home=&homeserver($uname,$udom);
1.292     www      3313:     if ($home eq 'no_host') { 
                   3314:         return -1; 
                   3315:     }
1.1112    www      3316:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3317:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3318: 	return -1;
                   3319:     }
1.1112    www      3320:     return $answer;
1.263     www      3321: }
                   3322: 
1.1111    www      3323: #
                   3324: # Return special version number of resource if set by override, empty otherwise
                   3325: #
                   3326: sub usedversion {
                   3327:     my $fname=shift;
                   3328:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3329:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3330:     if ($urlversion) { return $urlversion; }
                   3331:     return '';
                   3332: }
                   3333: 
1.1       albertel 3334: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3335: 
1.1       albertel 3336: sub subscribe {
                   3337:     my $fname=shift;
1.761     raeburn  3338:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3339:     $fname=~s/[\n\r]//g;
1.1       albertel 3340:     my $author=$fname;
                   3341:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3342:     my ($udom,$uname)=split(/\//,$author);
                   3343:     my $home=homeserver($uname,$udom);
1.335     albertel 3344:     if ($home eq 'no_host') {
                   3345:         return 'not_found';
1.1       albertel 3346:     }
                   3347:     my $answer=reply("sub:$fname",$home);
1.64      www      3348:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3349: 	$answer.=' by '.$home;
                   3350:     }
1.1       albertel 3351:     return $answer;
                   3352: }
                   3353:     
1.8       www      3354: # -------------------------------------------------------------- Replicate file
                   3355: 
                   3356: sub repcopy {
                   3357:     my $filename=shift;
1.23      www      3358:     $filename=~s/\/+/\//g;
1.1142    raeburn  3359:     my $londocroot = $perlvar{'lonDocRoot'};
                   3360:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3361:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3362:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3363: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3364: 	return &repcopy_userfile($filename);
                   3365:     }
1.532     albertel 3366:     $filename=~s/[\n\r]//g;
1.8       www      3367:     my $transname="$filename.in.transfer";
1.828     www      3368: # FIXME: this should flock
1.607     raeburn  3369:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3370:     my $remoteurl=subscribe($filename);
1.64      www      3371:     if ($remoteurl =~ /^con_lost by/) {
                   3372: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3373:            return 'unavailable';
1.8       www      3374:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3375: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3376: 	   return 'not_found';
1.64      www      3377:     } elsif ($remoteurl =~ /^rejected by/) {
                   3378: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3379:            return 'forbidden';
1.20      www      3380:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3381:            return 'ok';
1.8       www      3382:     } else {
1.290     www      3383:         my $author=$filename;
                   3384:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3385:         my ($udom,$uname)=split(/\//,$author);
                   3386:         my $home=homeserver($uname,$udom);
                   3387:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3388:            my @parts=split(/\//,$filename);
                   3389:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3390:            if ($path ne "$londocroot/res") {
1.8       www      3391:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3392: 	       return 'bad_request';
1.8       www      3393:            }
                   3394:            my $count;
                   3395:            for ($count=5;$count<$#parts;$count++) {
                   3396:                $path.="/$parts[$count]";
                   3397:                if ((-e $path)!=1) {
                   3398: 		   mkdir($path,0777);
                   3399:                }
                   3400:            }
                   3401:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3402:            my $response;
                   3403:            if ($remoteurl =~ m{/raw/}) {
                   3404:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3405:            } else {
                   3406:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3407:            }
1.8       www      3408:            if ($response->is_error()) {
                   3409: 	       unlink($transname);
                   3410:                my $message=$response->status_line;
1.672     albertel 3411:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3412:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3413:                return 'unavailable';
1.8       www      3414:            } else {
1.16      www      3415: 	       if ($remoteurl!~/\.meta$/) {
                   3416:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3417:                   my $mresponse;
                   3418:                   if ($remoteurl =~ m{/raw/}) {
                   3419:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3420:                   } else {
                   3421:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3422:                   }
1.16      www      3423:                   if ($mresponse->is_error()) {
                   3424: 		      unlink($filename.'.meta');
                   3425:                       &logthis(
1.672     albertel 3426:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3427:                   }
                   3428: 	       }
1.8       www      3429:                rename($transname,$filename);
1.607     raeburn  3430:                return 'ok';
1.8       www      3431:            }
1.290     www      3432:        }
1.8       www      3433:     }
1.330     www      3434: }
                   3435: 
1.1422    raeburn  3436: # ------------------------------------------------- Unsubscribe from a resource
                   3437: 
                   3438: sub unsubscribe {
                   3439:     my ($fname) = @_;
                   3440:     my $answer;
                   3441:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3442:     $fname=~s/[\n\r]//g;
                   3443:     my $author=$fname;
                   3444:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3445:     my ($udom,$uname)=split(/\//,$author);
                   3446:     my $home=homeserver($uname,$udom);
                   3447:     if ($home eq 'no_host') {
                   3448:         $answer = 'no_host';
                   3449:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3450:         $answer = 'home';
                   3451:     } else {
                   3452:         my $defdom = $perlvar{'lonDefDomain'};
                   3453:         if (&will_trust('content',$defdom,$udom)) {
                   3454:             $answer = reply("unsub:$fname",$home);
                   3455:         } else {
                   3456:             $answer = 'untrusted';
                   3457:         }
                   3458:     }
                   3459:     return $answer;
                   3460: }
                   3461: 
1.330     www      3462: # ------------------------------------------------ Get server side include body
                   3463: sub ssi_body {
1.381     albertel 3464:     my ($filelink,%form)=@_;
1.606     matthew  3465:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3466:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3467:     }
1.953     www      3468:     my $output='';
                   3469:     my $response;
1.980     raeburn  3470:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3471:        ($output,$response)=&externalssi($filelink);
1.953     www      3472:     } else {
1.1004    droeschl 3473:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3474:        $filelink .= 'inhibitmenu=yes';
1.953     www      3475:        ($output,$response)=&ssi($filelink,%form);
                   3476:     }
1.778     albertel 3477:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3478:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3479:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3480:     if (wantarray) {
                   3481:         return ($output, $response);
                   3482:     } else {
                   3483:         return $output;
                   3484:     }
1.8       www      3485: }
                   3486: 
1.15      www      3487: # --------------------------------------------------------- Server Side Include
                   3488: 
1.782     albertel 3489: sub absolute_url {
1.1447    raeburn  3490:     my ($host_name,$unalias,$keep_proto) = @_;
1.782     albertel 3491:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3492:     if ($host_name eq '') {
                   3493: 	$host_name = $ENV{'SERVER_NAME'};
                   3494:     }
1.1447    raeburn  3495:     if ($unalias) {
                   3496:         my $alias = &get_proxy_alias();
                   3497:         if ($alias eq $host_name) {
                   3498:             my $lonhost = $perlvar{'lonHostID'};
                   3499:             my $hostname = &hostname($lonhost);
                   3500:             my $lcproto; 
                   3501:             if (($keep_proto) || ($hostname eq '')) {
                   3502:                 $lcproto = $protocol;
                   3503:             } else {
                   3504:                 $lcproto = $protocol{$lonhost};
                   3505:                 $lcproto = 'http' if ($lcproto ne 'https');
                   3506:                 $lcproto .= '://';
                   3507:             }
                   3508:             unless ($hostname eq '') {
                   3509:                 return $lcproto.$hostname;
                   3510:             }
                   3511:         }
                   3512:     }
1.782     albertel 3513:     return $protocol.$host_name;
                   3514: }
                   3515: 
1.942     foxr     3516: #
                   3517: #   Server side include.
                   3518: # Parameters:
                   3519: #  fn     Possibly encrypted resource name/id.
                   3520: #  form   Hash that describes how the rendering should be done
                   3521: #         and other things.
1.944     foxr     3522: # Returns:
1.950     raeburn  3523: #   Scalar context: The content of the response.
                   3524: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3525: #     
1.15      www      3526: sub ssi {
                   3527: 
1.944     foxr     3528:     my ($fn,%form)=@_;
1.1447    raeburn  3529:     my ($host,$request,$response);
                   3530:     $host = &absolute_url('',1);
1.711     albertel 3531: 
                   3532:     $form{'no_update_last_known'}=1;
1.895     albertel 3533:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3534:     if (%form) {
1.1447    raeburn  3535:       $request=new HTTP::Request('POST',$host.$fn);
1.1272    droeschl 3536:       $request->content(join('&',map { 
                   3537:             my $name = escape($_);
                   3538:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3539:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3540:             : &escape($form{$_}) );    
                   3541:         } keys(%form)));
1.23      www      3542:     } else {
1.1447    raeburn  3543:       $request=new HTTP::Request('GET',$host.$fn);
1.23      www      3544:     }
                   3545: 
1.15      www      3546:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3547:     my $lonhost = $perlvar{'lonHostID'};
1.1385    raeburn  3548:     my $islocal;
                   3549:     if (($env{'request.course.id'}) &&
                   3550:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3551:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3552:         ($form{'grade_symb'} ne '') &&
                   3553:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3554:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
                   3555:         $islocal = 1;
                   3556:     }
1.1447    raeburn  3557:     $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
                   3558:                                              '','','',$islocal);
1.1182    foxr     3559: 
1.944     foxr     3560:     if (wantarray) {
1.1345    raeburn  3561: 	return ($response->content, $response);
1.944     foxr     3562:     } else {
1.1345    raeburn  3563: 	return $response->content;
1.942     foxr     3564:     }
1.324     www      3565: }
                   3566: 
                   3567: sub externalssi {
                   3568:     my ($url)=@_;
                   3569:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3570:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3571:     if (wantarray) {
                   3572:         return ($response->content, $response);
                   3573:     } else {
                   3574:         return $response->content;
                   3575:     }
1.15      www      3576: }
1.254     www      3577: 
1.1354    raeburn  3578: 
                   3579: # If the local copy of a replicated resource is outdated, trigger a  
                   3580: # connection from the homeserver to flush the delayed queue. If no update 
                   3581: # happens, remove local copies of outdated resource (and corresponding
                   3582: # metadata file).
                   3583: 
1.1352    raeburn  3584: sub remove_stale_resfile {
                   3585:     my ($url) = @_;
1.1354    raeburn  3586:     my $removed;
1.1352    raeburn  3587:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3588:         my $audom = $1;
                   3589:         my $auname = $2;
1.1353    raeburn  3590:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3591:             my $homeserver = &homeserver($auname,$audom);
                   3592:             unless (($homeserver eq 'no_host') ||
                   3593:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3594:                 my $fname = &filelocation('',$url);
                   3595:                 if (-e $fname) {
                   3596:                     my $hostname = &hostname($homeserver);
                   3597:                     if ($hostname) {
1.1397    raeburn  3598:                         my $protocol = $protocol{$homeserver};
                   3599:                         $protocol = 'http' if ($protocol ne 'https');
1.1352    raeburn  3600:                         my $uri = &declutter($url);
                   3601:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3602:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3603:                         if ($response->is_success()) {
                   3604:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3605:                             my $locmodtime = (stat($fname))[9];
                   3606:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3607:                                 my $stale;
                   3608:                                 my $answer = &reply('pong',$homeserver);
                   3609:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3610:                                     sleep(0.2);
                   3611:                                     $locmodtime = (stat($fname))[9];
                   3612:                                     if ($locmodtime < $remmodtime) {
                   3613:                                         my $posstransfer = $fname.'.in.transfer';
                   3614:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3615:                                             $removed = 1;
                   3616:                                         } else {
                   3617:                                             $stale = 1;
                   3618:                                         }
                   3619:                                     } else {
                   3620:                                         $removed = 1;
                   3621:                                     }
                   3622:                                 } else {
                   3623:                                     $stale = 1;
                   3624:                                 }
                   3625:                                 if ($stale) {
1.1421    raeburn  3626:                                     if (unlink($fname)) {
                   3627:                                         if ($uri!~/\.meta$/) {
                   3628:                                             if (-e $fname.'.meta') {
                   3629:                                                 unlink($fname.'.meta');
                   3630:                                             }
                   3631:                                         }
1.1422    raeburn  3632:                                         my $unsubresult = &unsubscribe($fname);
                   3633:                                         unless ($unsubresult eq 'ok') {
                   3634:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3635:                                         }
1.1421    raeburn  3636:                                         $removed = 1;
1.1354    raeburn  3637:                                     }
1.1352    raeburn  3638:                                 }
                   3639:                             }
                   3640:                         }
                   3641:                     }
                   3642:                 }
                   3643:             }
                   3644:         }
                   3645:     }
1.1354    raeburn  3646:     return $removed;
1.1352    raeburn  3647: }
                   3648: 
1.492     albertel 3649: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3650: 
                   3651: sub allowuploaded {
                   3652:     my ($srcurl,$url)=@_;
                   3653:     $url=&clutter(&declutter($url));
                   3654:     my $dir=$url;
                   3655:     $dir=~s/\/[^\/]+$//;
                   3656:     my %httpref=();
                   3657:     my $httpurl=&hreflocation('',$url);
                   3658:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3659:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3660: }
1.477     raeburn  3661: 
1.1193    raeburn  3662: #
                   3663: # Determine if the current user should be able to edit a particular resource,
                   3664: # when viewing in course context.
                   3665: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3666: #     Functions.
                   3667: # (b) When displaying folder contents in course editor, used to determine if
                   3668: #     "Edit" link will be displayed alongside resource.
                   3669: #
1.1196    raeburn  3670: #  input: six args -- filename (decluttered), course number, course domain,
                   3671: #                   url, symb (if registered) and group (if this is a group
                   3672: #                   item -- e.g., bulletin board, group page etc.).
                   3673: #  output: array of five scalars -- 
1.1193    raeburn  3674: #          $cfile -- url for file editing if editable on current server
                   3675: #          $home -- homeserver of resource (i.e., for author if published,
                   3676: #                                           or course if uploaded.).
                   3677: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3678: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3679: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3680: #
                   3681: 
                   3682: sub can_edit_resource {
1.1194    raeburn  3683:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3684:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3685: #
                   3686: # For aboutme pages user can only edit his/her own.
                   3687: #
1.1199    raeburn  3688:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3689:         my ($sdom,$sname) = ($1,$2);
                   3690:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3691:             $home = $env{'user.home'};
                   3692:             $cfile = $resurl;
                   3693:             if ($env{'form.forceedit'}) {
                   3694:                 $forceview = 1;
                   3695:             } else {
                   3696:                 $forceedit = 1;
                   3697:             }
                   3698:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3699:         } else {
                   3700:             return;
                   3701:         }
                   3702:     }
                   3703: 
                   3704:     if ($env{'request.course.id'}) {
                   3705:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3706:         if ($group ne '') {
                   3707: # if this is a group homepage or group bulletin board, check group privs
                   3708:             my $allowed = 0;
1.1197    raeburn  3709:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3710:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3711:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3712:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3713:                     $allowed = 1;
                   3714:                 }
1.1197    raeburn  3715:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3716:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3717:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3718:                     $allowed = 1;
                   3719:                 }
                   3720:             }
                   3721:             if ($allowed) {
                   3722:                 $home=&homeserver($cnum,$cdom);
                   3723:                 if ($env{'form.forceedit'}) {
                   3724:                     $forceview = 1;
                   3725:                 } else {
                   3726:                     $forceedit = 1;
                   3727:                 }
                   3728:                 $cfile = $resurl;
                   3729:             } else {
                   3730:                 return;
                   3731:             }
                   3732:         } else {
1.1208    raeburn  3733:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3734:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3735:                     return;
                   3736:                 }
                   3737:             } elsif (!$crsedit) {
1.1194    raeburn  3738: #
                   3739: # No edit allowed where CC has switched to student role.
                   3740: #
                   3741:                 return;
                   3742:             }
                   3743:         }
                   3744:     }
                   3745: 
1.1193    raeburn  3746:     if ($file ne '') {
                   3747:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3748:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3749:                 $uploaded = 1;
                   3750:                 $incourse = 1;
1.1193    raeburn  3751:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3752:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3753:                     if ($env{'form.forceedit'}) {
                   3754:                         $forceview = 1;
                   3755:                     } else {
                   3756:                         $forceedit = 1;
                   3757:                     }
1.1194    raeburn  3758:                 }
                   3759:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3760:                 $incourse = 1;
                   3761:                 if ($env{'form.forceedit'}) {
                   3762:                     $forceview = 1;
                   3763:                 } else {
                   3764:                     $forceedit = 1;
                   3765:                 }
                   3766:                 $cfile = $resurl;
                   3767:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3768:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3769:                     $incourse = 1;
                   3770:                     if ($env{'form.forceedit'}) {
                   3771:                         $forceview = 1;
                   3772:                     } else {
                   3773:                         $forceedit = 1;
                   3774:                     }
                   3775:                     $cfile = $resurl;
1.1199    raeburn  3776:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3777:                     $incourse = 1;
                   3778:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3779:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3780:                     $incourse = 1;
1.1199    raeburn  3781:                     if ($env{'form.forceedit'}) {
                   3782:                         $forceview = 1;
                   3783:                     } else {
                   3784:                         $forceedit = 1;
                   3785:                     }
                   3786:                     $cfile = $resurl;
1.1419    raeburn  3787:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3788:                     my ($map,$id,$res) = &decode_symb($symb);
                   3789:                     if ($map =~ /\.page$/) {
                   3790:                         $incourse = 1;
                   3791:                         if ($env{'form.forceedit'}) {
                   3792:                             $forceview = 1;
                   3793:                             $cfile = $map;
                   3794:                         } else {
                   3795:                             $forceedit = 1;
                   3796:                             $cfile =  '/adm/wrapper'.$resurl;
                   3797:                         }
                   3798:                     }
1.1343    raeburn  3799:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3800:                     $incourse = 1;
                   3801:                     if ($env{'form.forceedit'}) {
                   3802:                         $forceview = 1;
                   3803:                     } else {
                   3804:                         $forceedit = 1;
                   3805:                     }
                   3806:                     $cfile = $resurl;
1.1208    raeburn  3807:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3808:                     $incourse = 1;
                   3809:                     if ($env{'form.forceedit'}) {
                   3810:                         $forceview = 1;
                   3811:                     } else {
                   3812:                         $forceedit = 1;
                   3813:                     }
                   3814:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3815:                 }
                   3816:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3817:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3818:                 if (&is_on_map($template)) { 
                   3819:                     $incourse = 1;
                   3820:                     $forceview = 1;
                   3821:                     $cfile = $template;
1.1193    raeburn  3822:                 }
1.1199    raeburn  3823:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1418    raeburn  3824:                 $incourse = 1;
                   3825:                 if ($env{'form.forceedit'}) {
                   3826:                     $forceview = 1;
                   3827:                 } else {
                   3828:                     $forceedit = 1;
                   3829:                 }
                   3830:                 $cfile = $resurl;
1.1343    raeburn  3831:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3832:                 $incourse = 1;
                   3833:                 if ($env{'form.forceedit'}) {
                   3834:                     $forceview = 1;
                   3835:                 } else {
                   3836:                     $forceedit = 1;
                   3837:                 }
                   3838:                 $cfile = $resurl;
1.1199    raeburn  3839:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3840:                 $incourse = 1;
                   3841:                 $forceview = 1;
                   3842:                 if ($symb) {
                   3843:                     my ($map,$id,$res)=&decode_symb($symb);
                   3844:                     $env{'request.symb'} = $symb;
                   3845:                     $cfile = &clutter($res);
                   3846:                 } else {
                   3847:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3848:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3849:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3850:                         $cfile = '/adm/wrapper'.$escfile;
                   3851:                     } else {
                   3852:                         $escfile =~ s{^http://}{};
                   3853:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3854:                     }
1.1199    raeburn  3855:                 }
1.1234    raeburn  3856:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3857:                 if ($env{'form.forceedit'}) {
                   3858:                     $forceview = 1;
                   3859:                 } else {
                   3860:                     $forceedit = 1;
                   3861:                 }
                   3862:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3863:             }
                   3864:         }
1.1194    raeburn  3865:         if ($uploaded || $incourse) {
                   3866:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3867:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3868:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3869:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3870:             # Check that the user has permission to edit this resource
                   3871:             my $setpriv = 1;
                   3872:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3873:             if (defined($cfudom)) {
                   3874:                 $home=&homeserver($cfuname,$cfudom);
                   3875:                 $cfile=$file;
                   3876:             }
                   3877:         }
1.1194    raeburn  3878:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3879:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3880:             my @ids=&current_machine_ids();
                   3881:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3882:                 $switchserver=1;
                   3883:             }
                   3884:         }
                   3885:     }
1.1194    raeburn  3886:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3887: }
                   3888: 
                   3889: sub is_course_upload {
                   3890:     my ($file,$cnum,$cdom) = @_;
                   3891:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3892:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3893:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3894:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3895:         return 1;
                   3896:     }
                   3897:     return;
                   3898: }
                   3899: 
1.1194    raeburn  3900: sub in_course {
1.1195    raeburn  3901:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3902:     if ($hideprivileged) {
                   3903:         my $skipuser;
1.1219    raeburn  3904:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3905:         my @possdoms = ($cdom);  
                   3906:         if ($coursehash{'checkforpriv'}) { 
                   3907:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3908:         }
                   3909:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3910:             $skipuser = 1;
                   3911:             if ($coursehash{'nothideprivileged'}) {
                   3912:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3913:                     my $user;
                   3914:                     if ($item =~ /:/) {
                   3915:                         $user = $item;
                   3916:                     } else {
                   3917:                         $user = join(':',split(/[\@]/,$item));
                   3918:                     }
                   3919:                     if ($user eq $uname.':'.$udom) {
                   3920:                         undef($skipuser);
                   3921:                         last;
                   3922:                     }
                   3923:                 }
                   3924:             }
                   3925:             if ($skipuser) {
                   3926:                 return 0;
                   3927:             }
                   3928:         }
                   3929:     }
1.1194    raeburn  3930:     $type ||= 'any';
                   3931:     if (!defined($cdom) || !defined($cnum)) {
                   3932:         my $cid  = $env{'request.course.id'};
                   3933:         $cdom = $env{'course.'.$cid.'.domain'};
                   3934:         $cnum = $env{'course.'.$cid.'.num'};
                   3935:     }
                   3936:     my $typesref;
1.1195    raeburn  3937:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3938:         $typesref = ['active','previous','future'];
                   3939:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3940:         $typesref = [$type];
                   3941:     }
                   3942:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3943:                               $typesref,undef,[$cdom]);
                   3944:     my ($tmp) = keys(%roles);
                   3945:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3946:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3947:     if (@course_roles > 0) {
                   3948:         return 1;
                   3949:     }
                   3950:     return 0;
                   3951: }
                   3952: 
1.478     albertel 3953: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3954: # input: action, courseID, current domain, intended
1.637     raeburn  3955: #        path to file, source of file, instruction to parse file for objects,
                   3956: #        ref to hash for embedded objects,
                   3957: #        ref to hash for codebase of java objects.
1.1095    raeburn  3958: #        reference to scalar to accommodate mime type determined
                   3959: #          from File::MMagic if $parser = parse.
1.637     raeburn  3960: #
1.485     raeburn  3961: # output: url to file (if action was uploaddoc), 
                   3962: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3963: #
1.478     albertel 3964: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3965: # course.
1.477     raeburn  3966: #
1.478     albertel 3967: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3968: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3969: #          course's home server.
1.477     raeburn  3970: #
1.478     albertel 3971: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3972: #          be copied from $source (current location) to 
                   3973: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3974: #         and will then be copied to
                   3975: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3976: #         course's home server.
1.485     raeburn  3977: #
1.481     raeburn  3978: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3979: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3980: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3981: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3982: #         in course's home server.
1.637     raeburn  3983: #
1.477     raeburn  3984: 
                   3985: sub process_coursefile {
1.1095    raeburn  3986:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3987:         $mimetype)=@_;
1.477     raeburn  3988:     my $fetchresult;
1.638     albertel 3989:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3990:     if ($action eq 'propagate') {
1.638     albertel 3991:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3992: 			     $home);
1.481     raeburn  3993:     } else {
1.477     raeburn  3994:         my $fpath = '';
                   3995:         my $fname = $file;
1.478     albertel 3996:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3997:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3998:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3999:         if ($action eq 'copy') {
                   4000:             if ($source eq '') {
                   4001:                 $fetchresult = 'no source file';
                   4002:                 return $fetchresult;
                   4003:             } else {
                   4004:                 my $destination = $filepath.'/'.$fname;
                   4005:                 rename($source,$destination);
                   4006:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4007:                                  $home);
1.481     raeburn  4008:             }
                   4009:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  4010:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 4011:             print $fh $env{'form.'.$source};
1.481     raeburn  4012:             close($fh);
1.637     raeburn  4013:             if ($parser eq 'parse') {
1.1024    raeburn  4014:                 my $mm = new File::MMagic;
1.1095    raeburn  4015:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   4016:                 if ($type eq 'text/html') {
1.1024    raeburn  4017:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   4018:                     unless ($parse_result eq 'ok') {
                   4019:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   4020:                     }
1.637     raeburn  4021:                 }
1.1095    raeburn  4022:                 if (ref($mimetype)) {
                   4023:                     $$mimetype = $type;
                   4024:                 } 
1.637     raeburn  4025:             }
1.477     raeburn  4026:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4027:                                  $home);
1.481     raeburn  4028:             if ($fetchresult eq 'ok') {
                   4029:                 return '/uploaded/'.$fpath.'/'.$fname;
                   4030:             } else {
                   4031:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 4032:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  4033:                 return '/adm/notfound.html';
                   4034:             }
1.477     raeburn  4035:         }
                   4036:     }
1.485     raeburn  4037:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  4038:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 4039:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  4040:     }
                   4041:     return $fetchresult;
                   4042: }
                   4043: 
1.637     raeburn  4044: sub build_filepath {
                   4045:     my ($fpath) = @_;
                   4046:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   4047:     unless ($fpath eq '') {
                   4048:         my @parts=split('/',$fpath);
                   4049:         foreach my $part (@parts) {
                   4050:             $filepath.= '/'.$part;
                   4051:             if ((-e $filepath)!=1) {
                   4052:                 mkdir($filepath,0777);
                   4053:             }
                   4054:         }
                   4055:     }
                   4056:     return $filepath;
                   4057: }
                   4058: 
                   4059: sub store_edited_file {
1.638     albertel 4060:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  4061:     my $file = $primary_url;
                   4062:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   4063:     my $fpath = '';
                   4064:     my $fname = $file;
                   4065:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   4066:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   4067:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  4068:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  4069:     print $fh $content;
                   4070:     close($fh);
1.638     albertel 4071:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  4072:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4073: 			  $home);
1.637     raeburn  4074:     if ($$fetchresult eq 'ok') {
                   4075:         return '/uploaded/'.$fpath.'/'.$fname;
                   4076:     } else {
1.638     albertel 4077:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   4078: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  4079:         return '/adm/notfound.html';
                   4080:     }
                   4081: }
                   4082: 
1.531     albertel 4083: sub clean_filename {
1.831     albertel 4084:     my ($fname,$args)=@_;
1.315     www      4085: # Replace Windows backslashes by forward slashes
1.257     www      4086:     $fname=~s/\\/\//g;
1.831     albertel 4087:     if (!$args->{'keep_path'}) {
                   4088:         # Get rid of everything but the actual filename
                   4089: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   4090:     }
1.315     www      4091: # Replace spaces by underscores
                   4092:     $fname=~s/\s+/\_/g;
1.1406    raeburn  4093: # Transliterate non-ascii text to ascii
                   4094:     my $lang = &Apache::lonlocal::current_language();
                   4095:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      4096: # Replace all other weird characters by nothing
1.831     albertel 4097:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 4098: # Replace all .\d. sequences with _\d. so they no longer look like version
                   4099: # numbers
                   4100:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1443    raeburn  4101: # Replace three or more adjacent underscores with one for consistency 
                   4102: # with loncfile::filename_check() so complete url can be extracted by
                   4103: # lonnet::decode_symb()
                   4104:     $fname=~s/_{3,}/_/g;
1.531     albertel 4105:     return $fname;
                   4106: }
1.1406    raeburn  4107: 
1.1051    raeburn  4108: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   4109: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   4110: # image with the same aspect ratio as the original, but with dimensions which do 
                   4111: # not exceed $resizewidth and $resizeheight.
                   4112:  
1.984     neumanie 4113: sub resizeImage {
1.1051    raeburn  4114:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   4115:     my $ima = Image::Magick->new;
                   4116:     my $resized;
                   4117:     if (-e $img_path) {
                   4118:         $ima->Read($img_path);
                   4119:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   4120:             my $width = $ima->Get('width');
                   4121:             my $height = $ima->Get('height');
                   4122:             if ($width > $resizewidth) {
                   4123: 	        my $factor = $width/$resizewidth;
                   4124:                 my $newheight = $height/$factor;
                   4125:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   4126:                 $resized = 1;
                   4127:             }
                   4128:         }
                   4129:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   4130:             my $width = $ima->Get('width');
                   4131:             my $height = $ima->Get('height');
                   4132:             if ($height > $resizeheight) {
                   4133:                 my $factor = $height/$resizeheight;
                   4134:                 my $newwidth = $width/$factor;
                   4135:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   4136:                 $resized = 1;
                   4137:             }
                   4138:         }
                   4139:         if ($resized) {
                   4140:             $ima->Write($img_path);
                   4141:         }
                   4142:     }
                   4143:     return;
1.977     amueller 4144: }
                   4145: 
1.608     albertel 4146: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 4147: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  4148: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  4149: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1401    raeburn  4150: #                                    canceloverwrite, scantron or ''.
1.1090    raeburn  4151: #                   if 'coursedoc': upload to the current course
                   4152: #                   if 'existingfile': write file to tmp/overwrites directory 
                   4153: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   4154: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 4155: #        $subdir - directory in userfile to store the file into
1.1401    raeburn  4156: #        $parser - instruction to parse file for objects ($parser = parse) or
                   4157: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   4158: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
                   4159: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  4160: #        $allfiles - reference to hash for embedded objects
                   4161: #        $codebase - reference to hash for codebase of java objects
                   4162: #        $desuname - username for permanent storage of uploaded file
                   4163: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  4164: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   4165: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  4166: #        $resizewidth - width (pixels) to which to resize uploaded image
                   4167: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  4168: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  4169: #                    from File::MMagic.
1.858     raeburn  4170: # 
1.686     albertel 4171: # output: url of file in userspace, or error: <message> 
                   4172: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 4173: 
1.531     albertel 4174: sub userfileupload {
1.1090    raeburn  4175:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  4176:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 4177:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 4178:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 4179:     $fname=&clean_filename($fname);
1.1090    raeburn  4180:     # See if there is anything left
1.257     www      4181:     unless ($fname) { return 'error: no uploaded file'; }
1.1406    raeburn  4182:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   4183:     if ($fname =~ /^\./) {
                   4184:         my ($s,$usec) = &gettimeofday();
                   4185:         while (length($usec) < 6) {
                   4186:             $usec = '0'.$usec;
                   4187:         }
                   4188:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   4189:     }
1.1090    raeburn  4190:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   4191:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   4192:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   4193:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  4194:         my $now = time;
1.1090    raeburn  4195:         my $filepath;
1.1095    raeburn  4196:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  4197:              $filepath = 'tmp/helprequests/'.$now;
                   4198:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   4199:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   4200:                          '_'.$env{'user.domain'}.'/pending';
                   4201:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   4202:             my ($docuname,$docudom);
1.1350    raeburn  4203:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  4204:                 $docudom = $destudom;
                   4205:             } else {
                   4206:                 $docudom = $env{'user.domain'};
                   4207:             }
1.1350    raeburn  4208:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  4209:                 $docuname = $destuname;
                   4210:             } else {
                   4211:                 $docuname = $env{'user.name'};
                   4212:             }
                   4213:             if (exists($env{'form.group'})) {
                   4214:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4215:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4216:             }
                   4217:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   4218:             if ($context eq 'canceloverwrite') {
                   4219:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   4220:                 if (-e  $tempfile) {
                   4221:                     my @info = stat($tempfile);
                   4222:                     if ($info[9] eq $env{'form.timestamp'}) {
                   4223:                         unlink($tempfile);
                   4224:                     }
                   4225:                 }
                   4226:                 return;
1.523     raeburn  4227:             }
                   4228:         }
1.1090    raeburn  4229:         # Create the directory if not present
1.741     raeburn  4230:         my @parts=split(/\//,$filepath);
                   4231:         my $fullpath = $perlvar{'lonDaemons'};
                   4232:         for (my $i=0;$i<@parts;$i++) {
                   4233:             $fullpath .= '/'.$parts[$i];
                   4234:             if ((-e $fullpath)!=1) {
                   4235:                 mkdir($fullpath,0777);
                   4236:             }
                   4237:         }
1.1359    raeburn  4238:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  4239:         print $fh $env{'form.'.$formname};
                   4240:         close($fh);
1.1090    raeburn  4241:         if ($context eq 'existingfile') {
                   4242:             my @info = stat($fullpath.'/'.$fname);
                   4243:             return ($fullpath.'/'.$fname,$info[9]);
                   4244:         } else {
                   4245:             return $fullpath.'/'.$fname;
                   4246:         }
1.523     raeburn  4247:     }
1.995     raeburn  4248:     if ($subdir eq 'scantron') {
                   4249:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4250:     } else {
1.995     raeburn  4251:         $fname="$subdir/$fname";
                   4252:     }
1.1090    raeburn  4253:     if ($context eq 'coursedoc') {
1.638     albertel 4254: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4255: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4256:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4257:             return &finishuserfileupload($docuname,$docudom,
                   4258: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4259: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4260:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4261:         } else {
1.1218    raeburn  4262:             if ($env{'form.folder'}) {
                   4263:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4264:             }
1.638     albertel 4265:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4266: 				       $fname,$formname,$parser,
1.1095    raeburn  4267: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4268:         }
1.719     banghart 4269:     } elsif (defined($destuname)) {
                   4270:         my $docuname=$destuname;
                   4271:         my $docudom=$destudom;
1.860     raeburn  4272: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4273: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4274:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4275:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4276:     } else {
1.638     albertel 4277:         my $docuname=$env{'user.name'};
                   4278:         my $docudom=$env{'user.domain'};
1.1220    raeburn  4279:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4280:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4281:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4282:         }
1.860     raeburn  4283: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4284: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4285:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4286:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4287:     }
1.271     www      4288: }
                   4289: 
                   4290: sub finishuserfileupload {
1.860     raeburn  4291:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4292:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4293:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4294:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4295:   
1.860     raeburn  4296:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4297:     $file=$fname;
                   4298:     if ($fname=~m|/|) {
                   4299:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4300: 	$path.=$fnamepath.'/';
                   4301:     }
1.259     www      4302:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4303:     my $count;
                   4304:     for ($count=4;$count<=$#parts;$count++) {
                   4305:         $filepath.="/$parts[$count]";
                   4306:         if ((-e $filepath)!=1) {
                   4307: 	    mkdir($filepath,0777);
                   4308:         }
                   4309:     }
1.984     neumanie 4310: 
1.258     www      4311: # Save the file
                   4312:     {
1.1359    raeburn  4313: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4314: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4315: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4316: 	    return '/adm/notfound.html';
                   4317: 	}
1.1090    raeburn  4318:         if ($context eq 'overwrite') {
1.1117    foxr     4319:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4320:             my $target = $filepath.'/'.$file;
                   4321:             if (-e $source) {
                   4322:                 my @info = stat($source);
                   4323:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4324:                     unless (&File::Copy::move($source,$target)) {
                   4325:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4326:                         return "Moving from $source failed";
                   4327:                     }
                   4328:                 } else {
                   4329:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4330:                 }
                   4331:             } else {
                   4332:                 return "Temporary file: $source missing";
                   4333:             }
                   4334:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4335: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4336: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4337: 	    return '/adm/notfound.html';
                   4338: 	}
1.570     albertel 4339: 	close(FH);
1.1051    raeburn  4340:         if ($resizewidth && $resizeheight) {
                   4341:             my $mm = new File::MMagic;
                   4342:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4343:             if ($mime_type =~ m{^image/}) {
                   4344: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4345:             }  
1.977     amueller 4346: 	}
1.258     www      4347:     }
1.1152    raeburn  4348:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4349:         if (ref($mimetype)) {
                   4350:             if ($$mimetype eq '') {
                   4351:                 my $mm = new File::MMagic;
                   4352:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4353:                 $$mimetype = $type;
                   4354:             }
                   4355:         }
                   4356:     }
1.1401    raeburn  4357:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4358:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4359:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4360:                                                        $allfiles,$codebase);
                   4361:             unless ($parse_result eq 'ok') {
                   4362:                 &logthis('Failed to parse '.$filepath.$file.
                   4363: 	   	         ' for embedded media: '.$parse_result); 
                   4364:             }
1.637     raeburn  4365:         }
1.1401    raeburn  4366:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4367:         my $format = $env{'form.scantron_format'};
                   4368:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4369:     }
1.860     raeburn  4370:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4371:         my $input = $filepath.'/'.$file;
                   4372:         my $output = $filepath.'/'.'tn-'.$file;
                   4373:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  4374:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4375:         system({$args[0]} @args);
1.860     raeburn  4376:         if (-e $filepath.'/'.'tn-'.$file) {
                   4377:             $fetchthumb  = 1; 
                   4378:         }
                   4379:     }
1.858     raeburn  4380:  
1.259     www      4381: # Notify homeserver to grep it
                   4382: #
1.984     neumanie 4383:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4384:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4385:     if ($fetchresult eq 'ok') {
1.860     raeburn  4386:         if ($fetchthumb) {
                   4387:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4388:             if ($thumbresult ne 'ok') {
                   4389:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4390:                          $docuhome.': '.$thumbresult);
                   4391:             }
                   4392:         }
1.259     www      4393: #
1.258     www      4394: # Return the URL to it
1.494     albertel 4395:         return '/uploaded/'.$path.$file;
1.263     www      4396:     } else {
1.494     albertel 4397:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4398: 		 ': '.$fetchresult);
1.263     www      4399:         return '/adm/notfound.html';
1.858     raeburn  4400:     }
1.493     albertel 4401: }
                   4402: 
1.637     raeburn  4403: sub extract_embedded_items {
1.961     raeburn  4404:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4405:     my @state = ();
1.1164    raeburn  4406:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4407:     my %javafiles = (
                   4408:                       codebase => '',
                   4409:                       code => '',
                   4410:                       archive => ''
                   4411:                     );
                   4412:     my %mediafiles = (
                   4413:                       src => '',
                   4414:                       movie => '',
                   4415:                      );
1.648     raeburn  4416:     my $p;
                   4417:     if ($content) {
                   4418:         $p = HTML::LCParser->new($content);
                   4419:     } else {
1.961     raeburn  4420:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4421:     }
1.641     albertel 4422:     while (my $t=$p->get_token()) {
1.640     albertel 4423: 	if ($t->[0] eq 'S') {
                   4424: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4425: 	    push(@state, $tagname);
1.648     raeburn  4426:             if (lc($tagname) eq 'allow') {
                   4427:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4428:             }
1.640     albertel 4429: 	    if (lc($tagname) eq 'img') {
                   4430: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4431: 	    }
1.886     albertel 4432: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4433:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4434:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4435:                 }
1.886     albertel 4436: 	    }
1.645     raeburn  4437:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4438:                 my $src;
1.645     raeburn  4439:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4440:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4441:                 } else {
1.1164    raeburn  4442:                     if ($attr->{'src'} ne '') {
                   4443:                         $src = $attr->{'src'};
                   4444:                         &add_filetype($allfiles,$src,'src');
                   4445:                     }
                   4446:                 }
                   4447:                 my $text = $p->get_trimmed_text();
                   4448:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4449:                     my @swfargs = split(/,/,$1);
                   4450:                     foreach my $item (@swfargs) {
                   4451:                         $item =~ s/["']//g;
                   4452:                         $item =~ s/^\s+//;
                   4453:                         $item =~ s/\s+$//;
                   4454:                     }
                   4455:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4456:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4457:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4458:                         } else {
                   4459:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4460:                         }
                   4461:                     }
1.645     raeburn  4462:                 }
                   4463:             }
                   4464:             if (lc($tagname) eq 'link') {
                   4465:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4466:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4467:                 }
                   4468:             }
1.640     albertel 4469: 	    if (lc($tagname) eq 'object' ||
                   4470: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4471: 		foreach my $item (keys(%javafiles)) {
                   4472: 		    $javafiles{$item} = '';
                   4473: 		}
1.1164    raeburn  4474:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4475:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4476:                 }
1.640     albertel 4477: 	    }
                   4478: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4479: 		my $name = lc($attr->{'name'});
                   4480: 		foreach my $item (keys(%javafiles)) {
                   4481: 		    if ($name eq $item) {
                   4482: 			$javafiles{$item} = $attr->{'value'};
                   4483: 			last;
                   4484: 		    }
                   4485: 		}
1.1164    raeburn  4486:                 my $pathfrom;
1.640     albertel 4487: 		foreach my $item (keys(%mediafiles)) {
                   4488: 		    if ($name eq $item) {
1.1164    raeburn  4489:                         $pathfrom = $attr->{'value'};
                   4490:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4491: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4492: 			last;
                   4493: 		    }
                   4494: 		}
1.1164    raeburn  4495:                 if ($name eq 'flashvars') {
                   4496:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4497:                 }
                   4498:                 if ($pathfrom ne '') {
                   4499:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4500:                                          $pathfrom);
                   4501:                 }
1.640     albertel 4502: 	    }
                   4503: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4504: 		foreach my $item (keys(%javafiles)) {
                   4505: 		    if ($attr->{$item}) {
                   4506: 			$javafiles{$item} = $attr->{$item};
                   4507: 			last;
                   4508: 		    }
                   4509: 		}
                   4510: 		foreach my $item (keys(%mediafiles)) {
                   4511: 		    if ($attr->{$item}) {
                   4512: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4513: 			last;
                   4514: 		    }
                   4515: 		}
1.1164    raeburn  4516:                 if (lc($tagname) eq 'embed') {
                   4517:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4518:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4519:                                              $attr->{'src'});
                   4520:                     }
                   4521:                 }
1.640     albertel 4522: 	    }
1.1243    raeburn  4523:             if (lc($tagname) eq 'iframe') {
                   4524:                 my $src = $attr->{'src'} ;
                   4525:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4526:                     &add_filetype($allfiles,$src,'src');
                   4527:                 } elsif ($src =~ m{^/}) {
                   4528:                     if ($env{'request.course.id'}) {
                   4529:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4530:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4531:                         my $url = &hreflocation('',$fullpath);
                   4532:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4533:                             my $relpath = $1;
                   4534:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4535:                                 &add_filetype($allfiles,$1,'src');
                   4536:                             }
                   4537:                         }
                   4538:                     }
                   4539:                 }
                   4540:             }
1.1164    raeburn  4541:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4542:                 pop(@state);
1.1164    raeburn  4543:             }
1.640     albertel 4544: 	} elsif ($t->[0] eq 'E') {
                   4545: 	    my ($tagname) = ($t->[1]);
                   4546: 	    if ($javafiles{'codebase'} ne '') {
                   4547: 		$javafiles{'codebase'} .= '/';
                   4548: 	    }  
                   4549: 	    if (lc($tagname) eq 'applet' ||
                   4550: 		lc($tagname) eq 'object' ||
                   4551: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4552: 		) {
                   4553: 		foreach my $item (keys(%javafiles)) {
                   4554: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4555: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4556: 			&add_filetype($allfiles,$file,$item);
                   4557: 		    }
                   4558: 		}
                   4559: 	    } 
                   4560: 	    pop @state;
                   4561: 	}
                   4562:     }
1.1164    raeburn  4563:     foreach my $id (sort(keys(%flashvars))) {
                   4564:         if ($shockwave{$id} ne '') {
                   4565:             my @pairs = split(/\&/,$flashvars{$id});
                   4566:             foreach my $pair (@pairs) {
                   4567:                 my ($key,$value) = split(/\=/,$pair);
                   4568:                 if ($key eq 'thumb') {
                   4569:                     &add_filetype($allfiles,$value,$key);
                   4570:                 } elsif ($key eq 'content') {
                   4571:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4572:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4573:                     if ($ext ne '') {
                   4574:                         &add_filetype($allfiles,$path.$value,$ext);
                   4575:                     }
                   4576:                 }
                   4577:             }
                   4578:         }
                   4579:     }
1.637     raeburn  4580:     return 'ok';
                   4581: }
                   4582: 
1.639     albertel 4583: sub add_filetype {
                   4584:     my ($allfiles,$file,$type)=@_;
                   4585:     if (exists($allfiles->{$file})) {
                   4586: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4587: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4588: 	}
                   4589:     } else {
                   4590: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4591:     }
                   4592: }
                   4593: 
1.1164    raeburn  4594: sub embedded_dependency {
                   4595:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4596:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4597:         if (($identifier ne '') &&
                   4598:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4599:             ($pathfrom ne '')) {
                   4600:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4601:             foreach my $dep (@{$related->{$identifier}}) {
                   4602:                 &add_filetype($allfiles,$path.$dep,'object');
                   4603:             }
                   4604:         }
                   4605:     }
                   4606:     return;
                   4607: }
                   4608: 
1.1401    raeburn  4609: sub bubblesheet_converter {
                   4610:     my ($cdom,$fullpath,$config,$format) = @_;
                   4611:     if ((&domain($cdom) ne '') &&
1.1403    raeburn  4612:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401    raeburn  4613:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404    raeburn  4614:         my (%csvcols,%csvoptions);
                   4615:         if (ref($config->{'fields'}) eq 'HASH') {  
                   4616:             %csvcols = %{$config->{'fields'}};
                   4617:         }
                   4618:         if (ref($config->{'options'}) eq 'HASH') {
                   4619:             %csvoptions = %{$config->{'options'}};
                   4620:         }
1.1401    raeburn  4621:         my %csvbynum = reverse(%csvcols);
                   4622:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4623:         if (keys(%scantronconf)) {
                   4624:             my %bynum = (
                   4625:                           $scantronconf{CODEstart} => 'CODEstart',
                   4626:                           $scantronconf{IDstart}   => 'IDstart',
                   4627:                           $scantronconf{PaperID}   => 'PaperID',
                   4628:                           $scantronconf{FirstName} => 'FirstName',
                   4629:                           $scantronconf{LastName}  => 'LastName',
                   4630:                           $scantronconf{Qstart}    => 'Qstart',
                   4631:                         );
                   4632:             my @ordered;
                   4633:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403    raeburn  4634:                 push(@ordered,$bynum{$item});
1.1401    raeburn  4635:             }
                   4636:             my %mapstart = (
                   4637:                               CODEstart => 'CODE',
                   4638:                               IDstart   => 'ID',
                   4639:                               PaperID   => 'PaperID',
                   4640:                               FirstName => 'FirstName',
                   4641:                               LastName  => 'LastName',
                   4642:                               Qstart    => 'FirstQuestion',
                   4643:                            );
                   4644:             my %maplength = (
                   4645:                               CODEstart => 'CODElength',
                   4646:                               IDstart   => 'IDlength',
                   4647:                               PaperID   => 'PaperIDlength',
                   4648:                               FirstName => 'FirstNamelength',
                   4649:                               LastName  => 'LastNamelength',
                   4650:             );
                   4651:             if (open(my $fh,'<',$fullpath)) {
                   4652:                 my $output;
1.1403    raeburn  4653:                 my %lettdig = &letter_to_digits();
                   4654:                 my %diglett = reverse(%lettdig);
                   4655:                 my $numletts = scalar(keys(%lettdig));
1.1404    raeburn  4656:                 my $num = 0;
1.1401    raeburn  4657:                 while (my $line=<$fh>) {
1.1404    raeburn  4658:                     $num ++;
                   4659:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401    raeburn  4660:                     $line =~ s{[\r\n]+$}{};
                   4661:                     my %found;
                   4662:                     my @values = split(/,/,$line);
                   4663:                     my ($qstart,$record);
                   4664:                     for (my $i=0; $i<@values; $i++) {
1.1403    raeburn  4665:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4666:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4667:                             if ($values[$i] eq '') {
                   4668:                                 $values[$i] = $scantronconf{'Qoff'};
                   4669:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4670:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4671:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4672:                                 }
                   4673:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4674:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4675:                                     $values[$i] = $diglett{$values[$i]};
                   4676:                                 }
                   4677:                             } else {
                   4678:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4679:                                     my $digit;
                   4680:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4681:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4682:                                         if ($values[$i] eq 'J') {
                   4683:                                             $digit += $numletts;
                   4684:                                         }
                   4685:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4686:                                         $digit = $values[$i]-1;
                   4687:                                         if ($values[$i] eq '0') {
                   4688:                                             $digit += $numletts;
                   4689:                                         }
                   4690:                                     }
                   4691:                                     my $qval='';
                   4692:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4693:                                         if ($j == $digit) {
                   4694:                                             $qval .= $scantronconf{'Qon'};
                   4695:                                         } else {
                   4696:                                             $qval .= $scantronconf{'Qoff'};
                   4697:                                         }
                   4698:                                     }
                   4699:                                     $values[$i] = $qval;
                   4700:                                 }
                   4701:                             }
                   4702:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4703:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4704:                             }
                   4705:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4706:                             if ($numblank > 0) {
                   4707:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4708:                             }
1.1401    raeburn  4709:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4710:                                 $qstart = $i;
1.1403    raeburn  4711:                                 $found{$csvbynum{$i}} = $values[$i];
1.1401    raeburn  4712:                             } else {
1.1403    raeburn  4713:                                 $found{'FirstQuestion'} .= $values[$i];
                   4714:                             }
                   4715:                         } elsif (exists($csvbynum{$i})) {
1.1404    raeburn  4716:                             if ($csvoptions{'rem'}) {
                   4717:                                 $values[$i] =~ s/^\s+//;
                   4718:                             }
                   4719:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403    raeburn  4720:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4721:                                     $values[$i] = '0'.$values[$i];
1.1401    raeburn  4722:                                 }
                   4723:                             }
                   4724:                             $found{$csvbynum{$i}} = $values[$i];
                   4725:                         }
                   4726:                     }
                   4727:                     foreach my $item (@ordered) {
                   4728:                         my $currlength = 1+length($record);
                   4729:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4730:                         if ($numspaces > 0) {
                   4731:                             $record .= (' ' x $numspaces);
                   4732:                         }
                   4733:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4734:                             unless ($item eq 'Qstart') {
                   4735:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4736:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4737:                                 }
                   4738:                             }
                   4739:                             $record .= $found{$mapstart{$item}};
                   4740:                         }
                   4741:                     }
                   4742:                     $output .= "$record\n";
                   4743:                 }
                   4744:                 close($fh);
                   4745:                 if ($output) {
                   4746:                     if (open(my $fh,'>',$fullpath)) {
                   4747:                         print $fh $output;
                   4748:                         close($fh);
                   4749:                     }
                   4750:                 }
                   4751:             }
                   4752:         }
                   4753:         return;
                   4754:     }
                   4755: }
                   4756: 
1.1403    raeburn  4757: sub letter_to_digits {
                   4758:     my %lettdig = (
                   4759:                     A => 1,
                   4760:                     B => 2,
                   4761:                     C => 3,
                   4762:                     D => 4,
                   4763:                     E => 5,
                   4764:                     F => 6,
                   4765:                     G => 7,
                   4766:                     H => 8,
                   4767:                     I => 9,
                   4768:                     J => 0,
                   4769:                   );
                   4770:     return %lettdig;
                   4771: }
                   4772: 
1.1401    raeburn  4773: sub get_scantron_config {
                   4774:     my ($which,$cdom) = @_;
                   4775:     my @lines = &get_scantronformat_file($cdom);
                   4776:     my %config;
                   4777:     #FIXME probably should move to XML it has already gotten a bit much now
                   4778:     foreach my $line (@lines) {
                   4779:         my ($name,$descrip)=split(/:/,$line);
                   4780:         if ($name ne $which ) { next; }
                   4781:         chomp($line);
                   4782:         my @config=split(/:/,$line);
                   4783:         $config{'name'}=$config[0];
                   4784:         $config{'description'}=$config[1];
                   4785:         $config{'CODElocation'}=$config[2];
                   4786:         $config{'CODEstart'}=$config[3];
                   4787:         $config{'CODElength'}=$config[4];
                   4788:         $config{'IDstart'}=$config[5];
                   4789:         $config{'IDlength'}=$config[6];
                   4790:         $config{'Qstart'}=$config[7];
                   4791:         $config{'Qlength'}=$config[8];
                   4792:         $config{'Qoff'}=$config[9];
                   4793:         $config{'Qon'}=$config[10];
                   4794:         $config{'PaperID'}=$config[11];
                   4795:         $config{'PaperIDlength'}=$config[12];
                   4796:         $config{'FirstName'}=$config[13];
                   4797:         $config{'FirstNamelength'}=$config[14];
                   4798:         $config{'LastName'}=$config[15];
                   4799:         $config{'LastNamelength'}=$config[16];
                   4800:         $config{'BubblesPerRow'}=$config[17];
                   4801:         last;
                   4802:     }
                   4803:     return %config;
                   4804: }
                   4805: 
                   4806: sub get_scantronformat_file {
                   4807:     my ($cdom) = @_;
                   4808:     if ($cdom eq '') {
                   4809:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4810:     }
                   4811:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4812:     my $gottab = 0;
                   4813:     my @lines;
                   4814:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4815:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4816:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4817:             if ($formatfile ne '-1') {
                   4818:                 @lines = split("\n",$formatfile,-1);
                   4819:                 $gottab = 1;
                   4820:             }
                   4821:         }
                   4822:     }
                   4823:     if (!$gottab) {
                   4824:         my $confname = $cdom.'-domainconfig';
                   4825:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4826:         my $formatfile = &getfile($default);
                   4827:         if ($formatfile ne '-1') {
                   4828:             @lines = split("\n",$formatfile,-1);
                   4829:             $gottab = 1;
                   4830:         }
                   4831:     }
                   4832:     if (!$gottab) {
                   4833:         my @domains = &current_machine_domains();
                   4834:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4835:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4836:                 @lines = <$fh>;
                   4837:                 close($fh);
1.1403    raeburn  4838:             }
1.1401    raeburn  4839:         } else {
                   4840:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4841:                 @lines = <$fh>;
                   4842:                 close($fh);
                   4843:             }
                   4844:         }
                   4845:     }
                   4846:     return @lines;
                   4847: }
                   4848: 
1.493     albertel 4849: sub removeuploadedurl {
1.984     neumanie 4850:     my ($url)=@_;	
                   4851:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4852:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4853: }
                   4854: 
                   4855: sub removeuserfile {
                   4856:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4857:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4858:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4859:     if ($result eq 'ok') {	
1.798     raeburn  4860:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4861:             my $metafile = $fname.'.meta';
                   4862:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4863: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4864:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4865:             my $sqlresult = 
1.823     albertel 4866:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4867:                                         'portfolio_metadata',$group,
                   4868:                                         'delete');
1.798     raeburn  4869:         }
                   4870:     }
                   4871:     return $result;
1.257     www      4872: }
1.15      www      4873: 
1.530     albertel 4874: sub mkdiruserfile {
                   4875:     my ($docuname,$docudom,$dir)=@_;
                   4876:     my $home=&homeserver($docuname,$docudom);
                   4877:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4878: }
                   4879: 
1.531     albertel 4880: sub renameuserfile {
                   4881:     my ($docuname,$docudom,$old,$new)=@_;
                   4882:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4883:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4884:                         &escape("$old").':'.&escape("$new"),$home);
                   4885:     if ($result eq 'ok') {
                   4886:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4887:             my $oldmeta = $old.'.meta';
                   4888:             my $newmeta = $new.'.meta';
                   4889:             my $metaresult = 
                   4890:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4891: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4892:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4893:             my $sqlresult = 
1.823     albertel 4894:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4895:                                         'portfolio_metadata',$group,
                   4896:                                         'delete');
1.798     raeburn  4897:         }
                   4898:     }
                   4899:     return $result;
1.531     albertel 4900: }
                   4901: 
1.14      www      4902: # ------------------------------------------------------------------------- Log
                   4903: 
                   4904: sub log {
                   4905:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4906:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4907: }
                   4908: 
                   4909: # ------------------------------------------------------------------ Course Log
1.352     www      4910: #
                   4911: # This routine flushes several buffers of non-mission-critical nature
                   4912: #
1.157     www      4913: 
                   4914: sub flushcourselogs {
1.352     www      4915:     &logthis('Flushing log buffers');
                   4916: #
                   4917: # course logs
                   4918: # This is a log of all transactions in a course, which can be used
                   4919: # for data mining purposes
                   4920: #
                   4921: # It also collects the courseid database, which lists last transaction
                   4922: # times and course titles for all courseids
                   4923: #
                   4924:     my %courseidbuffer=();
1.921     raeburn  4925:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4926:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4927: 		          &escape($courselogs{$crsid}),
                   4928: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4929: 	    delete $courselogs{$crsid};
                   4930:         } else {
                   4931:             &logthis('Failed to flush log buffer for '.$crsid);
                   4932:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4933:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4934:                         " exceeded maximum size, deleting.</font>");
                   4935:                delete $courselogs{$crsid};
                   4936:             }
1.352     www      4937:         }
1.920     raeburn  4938:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4939:             'description' => $coursedescrbuf{$crsid},
                   4940:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4941:             'type'        => $coursetypebuf{$crsid},
                   4942:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4943:         };
1.191     harris41 4944:     }
1.352     www      4945: #
                   4946: # Write course id database (reverse lookup) to homeserver of courses 
                   4947: # Is used in pickcourse
                   4948: #
1.840     albertel 4949:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4950:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4951:                                     $courseidbuffer{$crs_home},
                   4952:                                     $crs_home,'timeonly');
1.352     www      4953:     }
                   4954: #
                   4955: # File accesses
                   4956: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4957: #
1.449     matthew  4958:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4959:         if ($entry =~ /___count$/) {
                   4960:             my ($dom,$name);
1.807     albertel 4961:             ($dom,$name,undef)=
1.811     albertel 4962: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4963:             if (! defined($dom) || $dom eq '' || 
                   4964:                 ! defined($name) || $name eq '') {
1.620     albertel 4965:                 my $cid = $env{'request.course.id'};
1.1472  ! raeburn  4966: #
        !          4967: # FIXME 11/29/2021
        !          4968: # Typo in rev. 1.458 (2003/12/09)??
        !          4969: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
        !          4970: #
        !          4971: # While these ramain as  $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
        !          4972: # $dom and $name will always be null, so the &inc() call will default to storing this data
        !          4973: # in a nohist_accesscount.db file for the user rather than the course.
        !          4974: #
        !          4975: # That said there is a lot of noise in the data being stored.
        !          4976: # So counts for prtspool/  and adm/ etc. are recorded.
        !          4977: #
        !          4978: # A review of which items ending '___count' are written to %accesshash should likely be 
        !          4979: # made before deciding whether to set these to 'course.' instead of 'request.'
        !          4980: #
        !          4981: # Under the current scheme each user receives a nohist_accesscount.db file listing 
        !          4982: # accesses for things which are not published resources, regardless of course, and
        !          4983: # there is not a nohist_accesscount.db file in a course, which might log accesses from
        !          4984: # anyone in the course for things which are not published resources.
        !          4985: #
        !          4986: # For an author, nohist_accesscount.db ends up having records for other items
        !          4987: # mixed up with the legitimate access counts for the author's published resources.
        !          4988: #
1.620     albertel 4989:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4990:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4991:             }
1.450     matthew  4992:             my $value = $accesshash{$entry};
                   4993:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4994:             my %temphash=($url => $value);
1.449     matthew  4995:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4996:             if ($result eq 'ok') {
                   4997:                 delete $accesshash{$entry};
                   4998:             }
                   4999:         } else {
1.811     albertel 5000:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      5001:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  5002:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  5003:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   5004:                 delete $accesshash{$entry};
                   5005:             }
1.185     www      5006:         }
1.191     harris41 5007:     }
1.352     www      5008: #
                   5009: # Roles
                   5010: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   5011: #
1.800     albertel 5012:     foreach my $entry (keys(%userrolehash)) {
1.351     www      5013:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      5014: 	    split(/\:/,$entry);
                   5015:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      5016:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      5017:                 $rudom,$runame) eq 'ok') {
                   5018: 	    delete $userrolehash{$entry};
                   5019:         }
                   5020:     }
1.662     raeburn  5021: #
1.1334    raeburn  5022: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  5023: #
                   5024:     my %domrolebuffer = ();
1.1000    raeburn  5025:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 5026:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  5027:         if ($domrolebuffer{$rudom}) {
                   5028:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   5029:                       '='.&escape($domainrolehash{$entry});
                   5030:         } else {
                   5031:             $domrolebuffer{$rudom}.=&escape($entry).
                   5032:                       '='.&escape($domainrolehash{$entry});
                   5033:         }
                   5034:         delete $domainrolehash{$entry};
                   5035:     }
                   5036:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  5037: 	my %servers;
                   5038: 	if (defined(&domain($dom,'primary'))) {
                   5039: 	    my $primary=&domain($dom,'primary');
                   5040: 	    my $hostname=&hostname($primary);
                   5041: 	    $servers{$primary} = $hostname;
                   5042: 	} else { 
                   5043: 	    %servers = &get_servers($dom,'library');
                   5044: 	}
1.841     albertel 5045: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  5046: 	    if (&reply('domroleput:'.$dom.':'.
                   5047: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   5048: 		last;
                   5049: 	    } else {  
1.841     albertel 5050: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   5051: 	    }
1.662     raeburn  5052:         }
                   5053:     }
1.186     www      5054:     $dumpcount++;
1.157     www      5055: }
                   5056: 
                   5057: sub courselog {
                   5058:     my $what=shift;
1.158     www      5059:     $what=time.':'.$what;
1.620     albertel 5060:     unless ($env{'request.course.id'}) { return ''; }
                   5061:     $coursedombuf{$env{'request.course.id'}}=
                   5062:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5063:     $coursenumbuf{$env{'request.course.id'}}=
                   5064:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   5065:     $coursehombuf{$env{'request.course.id'}}=
                   5066:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   5067:     $coursedescrbuf{$env{'request.course.id'}}=
                   5068:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   5069:     $courseinstcodebuf{$env{'request.course.id'}}=
                   5070:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   5071:     $courseownerbuf{$env{'request.course.id'}}=
                   5072:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  5073:     $coursetypebuf{$env{'request.course.id'}}=
                   5074:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 5075:     if (defined $courselogs{$env{'request.course.id'}}) {
                   5076: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      5077:     } else {
1.620     albertel 5078: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      5079:     }
1.620     albertel 5080:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      5081: 	&flushcourselogs();
                   5082:     }
1.158     www      5083: }
                   5084: 
                   5085: sub courseacclog {
                   5086:     my $fnsymb=shift;
1.620     albertel 5087:     unless ($env{'request.course.id'}) { return ''; }
                   5088:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      5089:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      5090:         $what.=':POST';
1.583     matthew  5091:         # FIXME: Probably ought to escape things....
1.800     albertel 5092: 	foreach my $key (keys(%env)) {
                   5093:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  5094:                 my $formitem = $1;
                   5095:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   5096:                     $what.=':'.$formitem.'='.$env{$key};
                   5097:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1432    raeburn  5098:                     if ($formitem eq 'proctorpassword') {
1.1433    raeburn  5099:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1432    raeburn  5100:                     } else {
                   5101:                         $what.=':'.$formitem.'='.$env{$key};
                   5102:                     }
1.975     raeburn  5103:                 }
1.158     www      5104:             }
1.191     harris41 5105:         }
1.583     matthew  5106:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   5107:         # FIXME: We should not be depending on a form parameter that someone
                   5108:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 5109:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  5110:             $what.= ':POST';
                   5111:             # FIXME: Probably ought to escape things....
                   5112:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   5113:                                  'crsdiscuss') {
1.620     albertel 5114:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  5115:             }
                   5116:         }
1.158     www      5117:     }
                   5118:     &courselog($what);
1.149     www      5119: }
                   5120: 
1.185     www      5121: sub countacc {
                   5122:     my $url=&declutter(shift);
1.458     matthew  5123:     return if (! defined($url) || $url eq '');
1.620     albertel 5124:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      5125: #
                   5126: # Mark that this url was used in this course
                   5127: #
1.620     albertel 5128:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      5129: #
                   5130: # Increase the access count for this resource in this child process
                   5131: #
1.281     www      5132:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  5133:     $accesshash{$key}++;
1.185     www      5134: }
1.349     www      5135: 
1.361     www      5136: sub linklog {
                   5137:     my ($from,$to)=@_;
                   5138:     $from=&declutter($from);
                   5139:     $to=&declutter($to);
                   5140:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   5141:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   5142: }
1.1160    www      5143: 
                   5144: sub statslog {
                   5145:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   5146:     if ($users<2) { return; }
                   5147:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   5148:             'course'       => $env{'request.course.id'},
                   5149:             'sections'     => '"all"',
                   5150:             'num_students' => $users,
                   5151:             'part'         => $part,
                   5152:             'symb'         => $symb,
                   5153:             'mean_tries'   => $av_attempts,
                   5154:             'deg_of_diff'  => $degdiff});
                   5155:     foreach my $key (keys(%dynstore)) {
                   5156:         $accesshash{$key}=$dynstore{$key};
                   5157:     }
                   5158: }
1.361     www      5159:   
1.349     www      5160: sub userrolelog {
                   5161:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 5162:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      5163:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5164:        $userrolehash
                   5165:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      5166:                     =$tend.':'.$tstart;
1.662     raeburn  5167:     }
1.1169    droeschl 5168:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 5169:        $userrolehash
                   5170:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   5171:                     =$tend.':'.$tstart;
                   5172:     }
1.1334    raeburn  5173:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  5174:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5175:        $domainrolehash
                   5176:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   5177:                     = $tend.':'.$tstart;
                   5178:     }
1.351     www      5179: }
                   5180: 
1.957     raeburn  5181: sub courserolelog {
                   5182:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  5183:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   5184:         my $cdom = $1;
                   5185:         my $cnum = $2;
                   5186:         my $sec = $3;
                   5187:         my $namespace = 'rolelog';
                   5188:         my %storehash = (
                   5189:                            role    => $trole,
                   5190:                            start   => $tstart,
                   5191:                            end     => $tend,
                   5192:                            selfenroll => $selfenroll,
                   5193:                            context    => $context,
                   5194:                         );
                   5195:         if ($trole eq 'gr') {
                   5196:             $namespace = 'groupslog';
                   5197:             $storehash{'group'} = $sec;
                   5198:         } else {
                   5199:             $storehash{'section'} = $sec;
                   5200:         }
1.1188    raeburn  5201:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   5202:                    $domain,$cnum,$cdom);
1.1184    raeburn  5203:         if (($trole ne 'st') || ($sec ne '')) {
                   5204:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  5205:         }
                   5206:     }
                   5207:     return;
                   5208: }
                   5209: 
1.1184    raeburn  5210: sub domainrolelog {
                   5211:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5212:     if ($area =~ m{^/($match_domain)/$}) {
                   5213:         my $cdom = $1;
                   5214:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   5215:         my $namespace = 'rolelog';
                   5216:         my %storehash = (
                   5217:                            role    => $trole,
                   5218:                            start   => $tstart,
                   5219:                            end     => $tend,
                   5220:                            context => $context,
                   5221:                         );
1.1188    raeburn  5222:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5223:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  5224:     }
                   5225:     return;
                   5226: 
                   5227: }
                   5228: 
                   5229: sub coauthorrolelog {
                   5230:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5231:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5232:         my $audom = $1;
                   5233:         my $auname = $2;
                   5234:         my $namespace = 'rolelog';
                   5235:         my %storehash = (
                   5236:                            role    => $trole,
                   5237:                            start   => $tstart,
                   5238:                            end     => $tend,
                   5239:                            context => $context,
                   5240:                         );
1.1188    raeburn  5241:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5242:                    $domain,$auname,$audom);
1.1184    raeburn  5243:     }
                   5244:     return;
                   5245: }
                   5246: 
1.351     www      5247: sub get_course_adv_roles {
1.948     raeburn  5248:     my ($cid,$codes) = @_;
1.620     albertel 5249:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5250:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5251:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5252:     my %nothide=();
1.800     albertel 5253:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5254:         if ($user !~ /:/) {
                   5255: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5256:         } else {
                   5257:             $nothide{$user}=1;
                   5258:         }
1.470     www      5259:     }
1.1219    raeburn  5260:     my @possdoms = ($coursehash{'domain'});
                   5261:     if ($coursehash{'checkforpriv'}) {
                   5262:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5263:     }
1.351     www      5264:     my %returnhash=();
                   5265:     my %dumphash=
                   5266:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5267:     my $now=time;
1.997     raeburn  5268:     my %privileged;
1.1000    raeburn  5269:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5270: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5271:         if (($tstart) && ($tstart<0)) { next; }
                   5272:         if (($tend) && ($tend<$now)) { next; }
                   5273:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5274:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5275: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  5276:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5277:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5278: 	if ($role eq 'cr') { next; }
1.948     raeburn  5279:         if ($codes) {
                   5280:             if ($section) { $role .= ':'.$section; }
                   5281:             if ($returnhash{$role}) {
                   5282:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5283:             } else {
                   5284:                 $returnhash{$role}=$username.':'.$domain;
                   5285:             }
1.351     www      5286:         } else {
1.988     raeburn  5287:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5288:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5289:             if ($returnhash{$key}) {
                   5290: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5291:             } else {
                   5292:                 $returnhash{$key}=$username.':'.$domain;
                   5293:             }
1.351     www      5294:         }
1.948     raeburn  5295:     }
1.400     www      5296:     return %returnhash;
                   5297: }
                   5298: 
                   5299: sub get_my_roles {
1.937     raeburn  5300:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5301:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5302:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5303:     my (%dumphash,%nothide);
1.1086    raeburn  5304:     if ($context eq 'userroles') {
1.1166    raeburn  5305:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5306:     } else {
1.1219    raeburn  5307:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5308:         if ($hidepriv) {
                   5309:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5310:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5311:                 if ($user !~ /:/) {
                   5312:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5313:                 } else {
                   5314:                     $nothide{$user} = 1;
                   5315:                 }
                   5316:             }
                   5317:         }
1.858     raeburn  5318:     }
1.400     www      5319:     my %returnhash=();
                   5320:     my $now=time;
1.999     raeburn  5321:     my %privileged;
1.800     albertel 5322:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5323:         my ($role,$tend,$tstart);
                   5324:         if ($context eq 'userroles') {
1.1149    raeburn  5325:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5326: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5327:         } else {
                   5328:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5329:         }
1.400     www      5330:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5331:         my $status = 'active';
1.939     raeburn  5332:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5333:             $status = 'previous';
                   5334:         } 
                   5335:         if (($tstart) && ($now<$tstart)) {
                   5336:             $status = 'future';
                   5337:         }
                   5338:         if (ref($types) eq 'ARRAY') {
                   5339:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5340:                 next;
                   5341:             } 
                   5342:         } else {
                   5343:             if ($status ne 'active') {
                   5344:                 next;
                   5345:             }
                   5346:         }
1.867     raeburn  5347:         my ($rolecode,$username,$domain,$section,$area);
                   5348:         if ($context eq 'userroles') {
1.1186    raeburn  5349:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5350:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5351:         } else {
                   5352:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5353:         }
1.832     raeburn  5354:         if (ref($roledoms) eq 'ARRAY') {
                   5355:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5356:                 next;
                   5357:             }
                   5358:         }
                   5359:         if (ref($roles) eq 'ARRAY') {
                   5360:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5361:                 if ($role =~ /^cr\//) {
                   5362:                     if (!grep(/^cr$/,@{$roles})) {
                   5363:                         next;
                   5364:                     }
1.1104    raeburn  5365:                 } elsif ($role =~ /^gr\//) {
                   5366:                     if (!grep(/^gr$/,@{$roles})) {
                   5367:                         next;
                   5368:                     }
1.922     raeburn  5369:                 } else {
                   5370:                     next;
                   5371:                 }
1.832     raeburn  5372:             }
1.867     raeburn  5373:         }
1.937     raeburn  5374:         if ($hidepriv) {
1.1219    raeburn  5375:             my @privroles = ('dc','su');
1.999     raeburn  5376:             if ($context eq 'userroles') {
1.1219    raeburn  5377:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5378:             } else {
1.1219    raeburn  5379:                 my $possdoms = [$domain];
                   5380:                 if (ref($roledoms) eq 'ARRAY') {
                   5381:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  5382:                 }
1.1219    raeburn  5383:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5384:                     if (!$nothide{$username.':'.$domain}) {
                   5385:                         next;
                   5386:                     }
                   5387:                 }
1.937     raeburn  5388:             }
                   5389:         }
1.933     raeburn  5390:         if ($withsec) {
                   5391:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5392:                 $tstart.':'.$tend;
                   5393:         } else {
                   5394:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5395:         }
1.832     raeburn  5396:     }
1.373     www      5397:     return %returnhash;
1.399     www      5398: }
                   5399: 
1.1333    raeburn  5400: sub get_all_adhocroles {
                   5401:     my ($dom) = @_;
                   5402:     my @roles_by_num = ();
                   5403:     my %domdefaults = &get_domain_defaults($dom);
                   5404:     my (%description,%access_in_dom,%access_info);
                   5405:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5406:         my $count = 0;
                   5407:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5408:         my %ordered;
                   5409:         foreach my $role (sort(keys(%domcurrent))) {
                   5410:             my ($order,$desc,$access_in_dom);
                   5411:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5412:                 $order = $domcurrent{$role}{'order'};
                   5413:                 $desc = $domcurrent{$role}{'desc'};
                   5414:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5415:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5416:             }
                   5417:             if ($order eq '') {
                   5418:                 $order = $count;
                   5419:             }
                   5420:             $ordered{$order} = $role;
                   5421:             if ($desc ne '') {
                   5422:                 $description{$role} = $desc;
                   5423:             } else {
                   5424:                 $description{$role}= $role;
                   5425:             }
                   5426:             $count++;
                   5427:         }
                   5428:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5429:             push(@roles_by_num,$ordered{$item});
                   5430:         }
                   5431:     }
                   5432:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5433: }
                   5434: 
1.1332    raeburn  5435: sub get_my_adhocroles {
1.1333    raeburn  5436:     my ($cid,$checkreg) = @_;
                   5437:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5438:     if ($env{'request.course.id'} eq $cid) {
                   5439:         $cdom = $env{'course.'.$cid.'.domain'};
                   5440:         $cnum = $env{'course.'.$cid.'.num'};
                   5441:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5442:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5443:         $cdom = $1;
                   5444:         $cnum = $2;
                   5445:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5446:                                      $cdom,$cnum);
                   5447:     }
                   5448:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5449:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5450:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5451:         if ($rosterhash{$user} ne '') {
                   5452:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5453:             return ([],{}) if ($type eq 'auto');
                   5454:         }
                   5455:     }
                   5456:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  5457:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  5458:             my $then=$env{'user.login.time'};
                   5459:             my $update=$env{'user.update.time'};
1.1335    raeburn  5460:             if (!$update) {
                   5461:                 $update = $then;
                   5462:             }
                   5463:             my @liveroles;
1.1334    raeburn  5464:             foreach my $role ('dh','da') {
                   5465:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  5466:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  5467:                     my $limit = $update;
                   5468:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5469:                         $limit = $then;
                   5470:                     }
1.1335    raeburn  5471:                     my $activerole = 1;
                   5472:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5473:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5474:                     if ($activerole) {
                   5475:                         push(@liveroles,$role);
                   5476:                     }
1.1334    raeburn  5477:                 }
1.1332    raeburn  5478:             }
1.1335    raeburn  5479:             if (@liveroles) {
1.1332    raeburn  5480:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  5481:                     my ($accessref,$accessinfo,%access_in_dom);
                   5482:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5483:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5484:                         if (@{$roles_by_num}) {
1.1332    raeburn  5485:                             my %settings;
                   5486:                             if ($env{'request.course.id'} eq $cid) {
                   5487:                                 foreach my $envkey (keys(%env)) {
                   5488:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5489:                                         $settings{$1} = $env{$envkey};
                   5490:                                     }
                   5491:                                 }
                   5492:                             } else {
                   5493:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5494:                             }
                   5495:                             my %setincrs;
                   5496:                             if ($settings{'internal.adhocaccess'}) {
                   5497:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5498:                             }
                   5499:                             my @statuses;
                   5500:                             if ($env{'environment.inststatus'}) {
                   5501:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5502:                             }
                   5503:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  5504:                             if (ref($accessref) eq 'HASH') {
                   5505:                                 %access_in_dom = %{$accessref};
                   5506:                             }
                   5507:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  5508:                                 my ($curraccess,@okstatus,@personnel);
                   5509:                                 if ($setincrs{$role}) {
                   5510:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5511:                                     if ($curraccess eq 'status') {
                   5512:                                         @okstatus = split(/\&/,$rest);
                   5513:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5514:                                         @personnel = split(/\&/,$rest);
                   5515:                                     }
                   5516:                                 } else {
                   5517:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  5518:                                     if (ref($accessinfo) eq 'HASH') {
                   5519:                                         if ($curraccess eq 'status') {
                   5520:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5521:                                                 @okstatus = @{$accessinfo->{$role}};
                   5522:                                             }
                   5523:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5524:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5525:                                                 @personnel = @{$accessinfo->{$role}};
                   5526:                                             }
1.1332    raeburn  5527:                                         }
                   5528:                                     }
                   5529:                                 }
                   5530:                                 if ($curraccess eq 'none') {
                   5531:                                     next;
                   5532:                                 } elsif ($curraccess eq 'all') {
                   5533:                                     push(@possroles,$role);
1.1336    raeburn  5534:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  5535:                                     if (grep(/^dh$/,@liveroles)) {
                   5536:                                         push(@possroles,$role);
                   5537:                                     } else {
                   5538:                                         next;
                   5539:                                     }
1.1336    raeburn  5540:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  5541:                                     if (grep(/^da$/,@liveroles)) {
                   5542:                                         push(@possroles,$role);
                   5543:                                     } else {
                   5544:                                         next;
                   5545:                                     }
1.1332    raeburn  5546:                                 } elsif ($curraccess eq 'status') {
                   5547:                                     if (@okstatus) {
                   5548:                                         if (!@statuses) {
                   5549:                                             if (grep(/^default$/,@okstatus)) {
                   5550:                                                 push(@possroles,$role);
                   5551:                                             }
                   5552:                                         } else {
                   5553:                                             foreach my $status (@okstatus) {
                   5554:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5555:                                                     push(@possroles,$role);
                   5556:                                                     last;
                   5557:                                                 }
                   5558:                                             }
                   5559:                                         }
                   5560:                                     }
                   5561:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5562:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5563:                                         if ($curraccess eq 'exc') {
                   5564:                                             push(@possroles,$role);
                   5565:                                         }
                   5566:                                     } elsif ($curraccess eq 'inc') {
                   5567:                                         push(@possroles,$role);
                   5568:                                     }
                   5569:                                 }
                   5570:                             }
                   5571:                         }
                   5572:                     }
                   5573:                 }
                   5574:             }
                   5575:         }
                   5576:     }
1.1333    raeburn  5577:     unless (ref($description) eq 'HASH') {
                   5578:         if (ref($roles_by_num) eq 'ARRAY') {
                   5579:             my %desc;
                   5580:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5581:             $description = \%desc;
                   5582:         } else {
                   5583:             $description = {};
                   5584:         }
                   5585:     }
                   5586:     return (\@possroles,$description);
1.1332    raeburn  5587: }
                   5588: 
1.399     www      5589: # ----------------------------------------------------- Frontpage Announcements
                   5590: #
                   5591: #
                   5592: 
                   5593: sub postannounce {
                   5594:     my ($server,$text)=@_;
1.844     albertel 5595:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5596:     unless ($text=~/\w/) { $text=''; }
                   5597:     return &reply('setannounce:'.&escape($text),$server);
                   5598: }
                   5599: 
                   5600: sub getannounce {
1.448     albertel 5601: 
1.1359    raeburn  5602:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5603: 	my $announcement='';
1.800     albertel 5604: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5605: 	close($fh);
1.399     www      5606: 	if ($announcement=~/\w/) { 
                   5607: 	    return 
                   5608:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5609:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5610: 	} else {
                   5611: 	    return '';
                   5612: 	}
                   5613:     } else {
                   5614: 	return '';
                   5615:     }
1.351     www      5616: }
1.353     www      5617: 
                   5618: # ---------------------------------------------------------- Course ID routines
                   5619: # Deal with domain's nohist_courseid.db files
                   5620: #
                   5621: 
                   5622: sub courseidput {
1.921     raeburn  5623:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5624:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5625:     my $outcome;
                   5626:     if ($caller eq 'timeonly') {
                   5627:         my $cids = '';
                   5628:         foreach my $item (keys(%$storehash)) {
                   5629:             $cids.=&escape($item).'&';
                   5630:         }
                   5631:         $cids=~s/\&$//;
                   5632:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5633:                           $coursehome);       
                   5634:     } else {
                   5635:         my $items = '';
                   5636:         foreach my $item (keys(%$storehash)) {
                   5637:             $items.= &escape($item).'='.
                   5638:                      &freeze_escape($$storehash{$item}).'&';
                   5639:         }
                   5640:         $items=~s/\&$//;
                   5641:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5642:                           $coursehome);
1.918     raeburn  5643:     }
                   5644:     if ($outcome eq 'unknown_cmd') {
                   5645:         my $what;
                   5646:         foreach my $cid (keys(%$storehash)) {
                   5647:             $what .= &escape($cid).'=';
1.921     raeburn  5648:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5649:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5650:             }
                   5651:             $what =~ s/\:$/&/;
                   5652:         }
                   5653:         $what =~ s/\&$//;  
                   5654:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5655:     } else {
                   5656:         return $outcome;
                   5657:     }
1.353     www      5658: }
                   5659: 
                   5660: sub courseiddump {
1.921     raeburn  5661:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5662:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5663:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  5664:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  5665:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5666:     my $as_hash = 1;
                   5667:     my %returnhash;
                   5668:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5669:     my %libserv = &all_library();
                   5670:     foreach my $tryserver (keys(%libserv)) {
                   5671:         if ( (  $hostidflag == 1 
                   5672: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5673: 	     || (!defined($hostidflag)) ) {
                   5674: 
1.918     raeburn  5675: 	    if (($domfilter eq '') ||
                   5676: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5677:                 my $rep;
                   5678:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5679:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5680:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5681:                                 &escape($descfilter), &escape($instcodefilter), 
                   5682:                                 &escape($ownerfilter), &escape($coursefilter),
                   5683:                                 &escape($typefilter), &escape($regexp_ok), 
                   5684:                                 $as_hash, &escape($selfenrollonly), 
                   5685:                                 &escape($catfilter), $showhidden, $caller, 
                   5686:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5687:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5688:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5689:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5690:                 } else {
                   5691:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5692:                              $sincefilter.':'.&escape($descfilter).':'.
                   5693:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5694:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5695:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5696:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5697:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5698:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5699:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5700:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5701:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5702:                 }
                   5703:                      
1.918     raeburn  5704:                 my @pairs=split(/\&/,$rep);
                   5705:                 foreach my $item (@pairs) {
                   5706:                     my ($key,$value)=split(/\=/,$item,2);
                   5707:                     $key = &unescape($key);
                   5708:                     next if ($key =~ /^error: 2 /);
                   5709:                     my $result = &thaw_unescape($value);
                   5710:                     if (ref($result) eq 'HASH') {
                   5711:                         $returnhash{$key}=$result;
                   5712:                     } else {
1.921     raeburn  5713:                         my @responses = split(/:/,$value);
                   5714:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5715:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5716:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5717:                         }
1.1008    raeburn  5718:                     }
1.353     www      5719:                 }
                   5720:             }
                   5721:         }
                   5722:     }
                   5723:     return %returnhash;
                   5724: }
                   5725: 
1.1055    raeburn  5726: sub courselastaccess {
                   5727:     my ($cdom,$cnum,$hostidref) = @_;
                   5728:     my %returnhash;
                   5729:     if ($cdom && $cnum) {
                   5730:         my $chome = &homeserver($cnum,$cdom);
                   5731:         if ($chome ne 'no_host') {
                   5732:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5733:             &extract_lastaccess(\%returnhash,$rep);
                   5734:         }
                   5735:     } else {
                   5736:         if (!$cdom) { $cdom=''; }
                   5737:         my %libserv = &all_library();
                   5738:         foreach my $tryserver (keys(%libserv)) {
                   5739:             if (ref($hostidref) eq 'ARRAY') {
                   5740:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5741:             } 
                   5742:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5743:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5744:                 &extract_lastaccess(\%returnhash,$rep);
                   5745:             }
                   5746:         }
                   5747:     }
                   5748:     return %returnhash;
                   5749: }
                   5750: 
                   5751: sub extract_lastaccess {
                   5752:     my ($returnhash,$rep) = @_;
                   5753:     if (ref($returnhash) eq 'HASH') {
                   5754:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5755:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5756:                  $rep eq '') {
                   5757:             my @pairs=split(/\&/,$rep);
                   5758:             foreach my $item (@pairs) {
                   5759:                 my ($key,$value)=split(/\=/,$item,2);
                   5760:                 $key = &unescape($key);
                   5761:                 next if ($key =~ /^error: 2 /);
                   5762:                 $returnhash->{$key} = &thaw_unescape($value);
                   5763:             }
                   5764:         }
                   5765:     }
                   5766:     return;
                   5767: }
                   5768: 
1.658     raeburn  5769: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5770: 
                   5771: sub dcmailput {
1.685     raeburn  5772:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5773:     my $status = &Apache::lonnet::critical(
1.740     www      5774:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5775:        &escape($message),$server);
1.662     raeburn  5776:     return $status;
                   5777: }
                   5778: 
1.658     raeburn  5779: sub dcmaildump {
                   5780:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5781:     my %returnhash=();
1.846     albertel 5782: 
                   5783:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5784:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5785:                                                          &escape($enddate).':';
                   5786: 	my @esc_senders=map { &escape($_)} @$senders;
                   5787: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5788: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5789:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5790:             if (($key) && ($value)) {
                   5791:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5792:             }
                   5793:         }
                   5794:     }
                   5795:     return %returnhash;
                   5796: }
1.662     raeburn  5797: # ---------------------------------------------------------- Domain roles
                   5798: 
                   5799: sub get_domain_roles {
                   5800:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5801:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5802:         $startdate = '.';
                   5803:     }
1.1018    raeburn  5804:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5805:         $enddate = '.';
                   5806:     }
1.922     raeburn  5807:     my $rolelist;
                   5808:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5809:         $rolelist = join('&',@{$roles});
1.922     raeburn  5810:     }
1.662     raeburn  5811:     my %personnel = ();
1.841     albertel 5812: 
                   5813:     my %servers = &get_servers($dom,'library');
                   5814:     foreach my $tryserver (keys(%servers)) {
                   5815: 	%{$personnel{$tryserver}}=();
                   5816: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5817: 					    &escape($startdate).':'.
                   5818: 					    &escape($enddate).':'.
                   5819: 					    &escape($rolelist), $tryserver))) {
                   5820: 	    my ($key,$value) = split(/\=/,$line,2);
                   5821: 	    if (($key) && ($value)) {
                   5822: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5823: 	    }
                   5824: 	}
1.662     raeburn  5825:     }
                   5826:     return %personnel;
                   5827: }
1.658     raeburn  5828: 
1.1332    raeburn  5829: sub get_active_domroles {
                   5830:     my ($dom,$roles) = @_;
                   5831:     return () unless (ref($roles) eq 'ARRAY');
                   5832:     my $now = time;
                   5833:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5834:     my %domroles;
                   5835:     foreach my $server (keys(%dompersonnel)) {
                   5836:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5837:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5838:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5839:         }
                   5840:     }
                   5841:     return %domroles;
                   5842: }
                   5843: 
1.1057    www      5844: # ----------------------------------------------------------- Interval timing 
1.149     www      5845: 
1.1153    www      5846: {
                   5847: # Caches needed for speedup of navmaps
                   5848: # We don't want to cache this for very long at all (5 seconds at most)
                   5849: # 
                   5850: # The user for whom we cache
                   5851: my $cachedkey='';
                   5852: # The cached times for this user
                   5853: my %cachedtimes=();
                   5854: # When this was last done
1.1282    raeburn  5855: my $cachedtime='';
1.1153    www      5856: 
                   5857: sub load_all_first_access {
1.1308    raeburn  5858:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5859:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5860:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5861:         (!$ignorecache)) {
1.1154    raeburn  5862:         return;
                   5863:     }
                   5864:     $cachedtime=time;
                   5865:     $cachedkey=$uname.':'.$udom;
                   5866:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5867: }
                   5868: 
1.504     albertel 5869: sub get_first_access {
1.1308    raeburn  5870:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5871:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5872:     if ($argsymb) { $symb=$argsymb; }
                   5873:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5874:     if ($argmap) { $map = $argmap; }
1.926     albertel 5875:     if ($type eq 'course') {
                   5876: 	$res='course';
                   5877:     } elsif ($type eq 'map') {
1.588     albertel 5878: 	$res=&symbread($map);
                   5879:     } else {
                   5880: 	$res=$symb;
                   5881:     }
1.1308    raeburn  5882:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5883:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5884: }
                   5885: 
                   5886: sub set_first_access {
1.1162    raeburn  5887:     my ($type,$interval)=@_;
1.790     albertel 5888:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5889:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5890:     if ($type eq 'course') {
                   5891: 	$res='course';
                   5892:     } elsif ($type eq 'map') {
1.588     albertel 5893: 	$res=&symbread($map);
                   5894:     } else {
                   5895: 	$res=$symb;
                   5896:     }
1.1153    www      5897:     $cachedkey='';
1.1162    raeburn  5898:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  5899:     if ($firstaccess) {
                   5900:         &logthis("First access time already set ($firstaccess) when attempting ".
1.1393    raeburn  5901:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5902:                  "in $courseid");
1.1386    raeburn  5903:         return 'already_set';
                   5904:     } else {
1.1162    raeburn  5905:         my $start = time;
                   5906: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5907:                           $udom,$uname);
                   5908:         if ($putres eq 'ok') {
                   5909:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5910:                  $udom,$uname); 
                   5911:             &appenv(
                   5912:                      {
                   5913:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5914:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5915:                      }
                   5916:                   );
1.1365    raeburn  5917:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5918:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5919:             }
1.1386    raeburn  5920:         } elsif ($putres ne 'refused') {
                   5921:             &logthis("Result: $putres when attempting to set first access time ".
                   5922:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5923:         }
                   5924:         return $putres;
1.505     albertel 5925:     }
                   5926:     return 'already_set';
1.504     albertel 5927: }
1.1153    www      5928: }
1.1282    raeburn  5929: 
1.110     www      5930: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5931: 
                   5932: sub expirespread {
                   5933:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5934:     my $cid=$env{'request.course.id'}; 
1.110     www      5935:     if ($cid) {
                   5936:        my $now=time;
                   5937:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5938:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5939:                             $env{'course.'.$cid.'.num'}.
1.110     www      5940: 	        	    ':nohist_expirationdates:'.
                   5941:                             &escape($key).'='.$now,
1.620     albertel 5942:                             $env{'course.'.$cid.'.home'})
1.110     www      5943:     }
                   5944:     return 'ok';
1.14      www      5945: }
                   5946: 
1.109     www      5947: # ----------------------------------------------------- Devalidate Spreadsheets
                   5948: 
                   5949: sub devalidate {
1.325     www      5950:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5951:     my $cid=$env{'request.course.id'}; 
1.109     www      5952:     if ($cid) {
1.391     matthew  5953:         # delete the stored spreadsheets for
                   5954:         # - the student level sheet of this user in course's homespace
                   5955:         # - the assessment level sheet for this resource 
                   5956:         #   for this user in user's homespace
1.553     albertel 5957: 	# - current conditional state info
1.325     www      5958: 	my $key=$uname.':'.$udom.':';
1.109     www      5959:         my $status=
1.299     matthew  5960: 	    &del('nohist_calculatedsheets',
1.391     matthew  5961: 		 [$key.'studentcalc:'],
1.620     albertel 5962: 		 $env{'course.'.$cid.'.domain'},
                   5963: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5964: 		.' '.
                   5965: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5966: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5967:         unless ($status eq 'ok ok') {
                   5968:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5969:                     $uname.' at '.$udom.' for '.
1.109     www      5970: 		    $symb.': '.$status);
1.133     albertel 5971:         }
1.553     albertel 5972: 	&delenv('user.state.'.$cid);
1.109     www      5973:     }
                   5974: }
                   5975: 
1.265     albertel 5976: sub get_scalar {
                   5977:     my ($string,$end) = @_;
                   5978:     my $value;
                   5979:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5980: 	$value = $1;
                   5981:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5982: 	$value = $1;
                   5983:     }
                   5984:     return &unescape($value);
                   5985: }
                   5986: 
                   5987: sub array2str {
                   5988:   my (@array) = @_;
                   5989:   my $result=&arrayref2str(\@array);
                   5990:   $result=~s/^__ARRAY_REF__//;
                   5991:   $result=~s/__END_ARRAY_REF__$//;
                   5992:   return $result;
                   5993: }
                   5994: 
1.204     albertel 5995: sub arrayref2str {
                   5996:   my ($arrayref) = @_;
1.265     albertel 5997:   my $result='__ARRAY_REF__';
1.204     albertel 5998:   foreach my $elem (@$arrayref) {
1.265     albertel 5999:     if(ref($elem) eq 'ARRAY') {
                   6000:       $result.=&arrayref2str($elem).'&';
                   6001:     } elsif(ref($elem) eq 'HASH') {
                   6002:       $result.=&hashref2str($elem).'&';
                   6003:     } elsif(ref($elem)) {
                   6004:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 6005:     } else {
                   6006:       $result.=&escape($elem).'&';
                   6007:     }
                   6008:   }
                   6009:   $result=~s/\&$//;
1.265     albertel 6010:   $result .= '__END_ARRAY_REF__';
1.204     albertel 6011:   return $result;
                   6012: }
                   6013: 
1.168     albertel 6014: sub hash2str {
1.204     albertel 6015:   my (%hash) = @_;
                   6016:   my $result=&hashref2str(\%hash);
1.265     albertel 6017:   $result=~s/^__HASH_REF__//;
                   6018:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 6019:   return $result;
                   6020: }
                   6021: 
                   6022: sub hashref2str {
                   6023:   my ($hashref)=@_;
1.265     albertel 6024:   my $result='__HASH_REF__';
1.800     albertel 6025:   foreach my $key (sort(keys(%$hashref))) {
                   6026:     if (ref($key) eq 'ARRAY') {
                   6027:       $result.=&arrayref2str($key).'=';
                   6028:     } elsif (ref($key) eq 'HASH') {
                   6029:       $result.=&hashref2str($key).'=';
                   6030:     } elsif (ref($key)) {
1.265     albertel 6031:       $result.='=';
1.800     albertel 6032:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 6033:     } else {
1.1132    raeburn  6034: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 6035:     }
                   6036: 
1.800     albertel 6037:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   6038:       $result.=&arrayref2str($hashref->{$key}).'&';
                   6039:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   6040:       $result.=&hashref2str($hashref->{$key}).'&';
                   6041:     } elsif(ref($hashref->{$key})) {
1.265     albertel 6042:        $result.='&';
1.800     albertel 6043:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 6044:     } else {
1.800     albertel 6045:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 6046:     }
                   6047:   }
1.168     albertel 6048:   $result=~s/\&$//;
1.265     albertel 6049:   $result .= '__END_HASH_REF__';
1.168     albertel 6050:   return $result;
                   6051: }
                   6052: 
                   6053: sub str2hash {
1.265     albertel 6054:     my ($string)=@_;
                   6055:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   6056:     return %$hash;
                   6057: }
                   6058: 
                   6059: sub str2hashref {
1.168     albertel 6060:   my ($string) = @_;
1.265     albertel 6061: 
                   6062:   my %hash;
                   6063: 
                   6064:   if($string !~ /^__HASH_REF__/) {
                   6065:       if (! ($string eq '' || !defined($string))) {
                   6066: 	  $hash{'error'}='Not hash reference';
                   6067:       }
                   6068:       return (\%hash, $string);
                   6069:   }
                   6070: 
                   6071:   $string =~ s/^__HASH_REF__//;
                   6072: 
                   6073:   while($string !~ /^__END_HASH_REF__/) {
                   6074:       #key
                   6075:       my $key='';
                   6076:       if($string =~ /^__HASH_REF__/) {
                   6077:           ($key, $string)=&str2hashref($string);
                   6078:           if(defined($key->{'error'})) {
                   6079:               $hash{'error'}='Bad data';
                   6080:               return (\%hash, $string);
                   6081:           }
                   6082:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6083:           ($key, $string)=&str2arrayref($string);
                   6084:           if($key->[0] eq 'Array reference error') {
                   6085:               $hash{'error'}='Bad data';
                   6086:               return (\%hash, $string);
                   6087:           }
                   6088:       } else {
                   6089:           $string =~ s/^(.*?)=//;
1.267     albertel 6090: 	  $key=&unescape($1);
1.265     albertel 6091:       }
                   6092:       $string =~ s/^=//;
                   6093: 
                   6094:       #value
                   6095:       my $value='';
                   6096:       if($string =~ /^__HASH_REF__/) {
                   6097:           ($value, $string)=&str2hashref($string);
                   6098:           if(defined($value->{'error'})) {
                   6099:               $hash{'error'}='Bad data';
                   6100:               return (\%hash, $string);
                   6101:           }
                   6102:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6103:           ($value, $string)=&str2arrayref($string);
                   6104:           if($value->[0] eq 'Array reference error') {
                   6105:               $hash{'error'}='Bad data';
                   6106:               return (\%hash, $string);
                   6107:           }
                   6108:       } else {
                   6109: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   6110:       }
                   6111:       $string =~ s/^&//;
                   6112: 
                   6113:       $hash{$key}=$value;
1.204     albertel 6114:   }
1.265     albertel 6115: 
                   6116:   $string =~ s/^__END_HASH_REF__//;
                   6117: 
                   6118:   return (\%hash, $string);
1.204     albertel 6119: }
                   6120: 
                   6121: sub str2array {
1.265     albertel 6122:     my ($string)=@_;
                   6123:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   6124:     return @$array;
                   6125: }
                   6126: 
                   6127: sub str2arrayref {
1.204     albertel 6128:   my ($string) = @_;
1.265     albertel 6129:   my @array;
                   6130: 
                   6131:   if($string !~ /^__ARRAY_REF__/) {
                   6132:       if (! ($string eq '' || !defined($string))) {
                   6133: 	  $array[0]='Array reference error';
                   6134:       }
                   6135:       return (\@array, $string);
                   6136:   }
                   6137: 
                   6138:   $string =~ s/^__ARRAY_REF__//;
                   6139: 
                   6140:   while($string !~ /^__END_ARRAY_REF__/) {
                   6141:       my $value='';
                   6142:       if($string =~ /^__HASH_REF__/) {
                   6143:           ($value, $string)=&str2hashref($string);
                   6144:           if(defined($value->{'error'})) {
                   6145:               $array[0] ='Array reference error';
                   6146:               return (\@array, $string);
                   6147:           }
                   6148:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6149:           ($value, $string)=&str2arrayref($string);
                   6150:           if($value->[0] eq 'Array reference error') {
                   6151:               $array[0] ='Array reference error';
                   6152:               return (\@array, $string);
                   6153:           }
                   6154:       } else {
                   6155: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   6156:       }
                   6157:       $string =~ s/^&//;
                   6158: 
                   6159:       push(@array, $value);
1.191     harris41 6160:   }
1.265     albertel 6161: 
                   6162:   $string =~ s/^__END_ARRAY_REF__//;
                   6163: 
                   6164:   return (\@array, $string);
1.168     albertel 6165: }
                   6166: 
1.167     albertel 6167: # -------------------------------------------------------------------Temp Store
                   6168: 
1.168     albertel 6169: sub tmpreset {
                   6170:   my ($symb,$namespace,$domain,$stuname) = @_;
                   6171:   if (!$symb) {
                   6172:     $symb=&symbread();
1.620     albertel 6173:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6174:   }
                   6175:   $symb=escape($symb);
                   6176: 
1.620     albertel 6177:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 6178:   $namespace=~s/\//\_/g;
                   6179:   $namespace=~s/\W//g;
                   6180: 
1.620     albertel 6181:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6182:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6183:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6184:       $stuname=&get_requestor_ip();
1.591     albertel 6185:   }
1.1117    foxr     6186:   my $path=LONCAPA::tempdir();
1.168     albertel 6187:   my %hash;
                   6188:   if (tie(%hash,'GDBM_File',
                   6189: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6190: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6191:     foreach my $key (keys(%hash)) {
1.180     albertel 6192:       if ($key=~ /:$symb/) {
1.168     albertel 6193: 	delete($hash{$key});
                   6194:       }
                   6195:     }
                   6196:   }
                   6197: }
                   6198: 
1.167     albertel 6199: sub tmpstore {
1.168     albertel 6200:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6201: 
                   6202:   if (!$symb) {
                   6203:     $symb=&symbread();
1.620     albertel 6204:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6205:   }
                   6206:   $symb=escape($symb);
                   6207: 
                   6208:   if (!$namespace) {
                   6209:     # I don't think we would ever want to store this for a course.
                   6210:     # it seems this will only be used if we don't have a course.
1.620     albertel 6211:     #$namespace=$env{'request.course.id'};
1.168     albertel 6212:     #if (!$namespace) {
1.620     albertel 6213:       $namespace=$env{'request.state'};
1.168     albertel 6214:     #}
                   6215:   }
                   6216:   $namespace=~s/\//\_/g;
                   6217:   $namespace=~s/\W//g;
1.620     albertel 6218:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6219:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6220:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6221:       $stuname=&get_requestor_ip();
1.591     albertel 6222:   }
1.168     albertel 6223:   my $now=time;
                   6224:   my %hash;
1.1117    foxr     6225:   my $path=LONCAPA::tempdir();
1.168     albertel 6226:   if (tie(%hash,'GDBM_File',
                   6227: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6228: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6229:     $hash{"version:$symb"}++;
                   6230:     my $version=$hash{"version:$symb"};
                   6231:     my $allkeys=''; 
                   6232:     foreach my $key (keys(%$storehash)) {
                   6233:       $allkeys.=$key.':';
1.591     albertel 6234:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6235:     }
                   6236:     $hash{"$version:$symb:timestamp"}=$now;
                   6237:     $allkeys.='timestamp';
                   6238:     $hash{"$version:keys:$symb"}=$allkeys;
                   6239:     if (untie(%hash)) {
                   6240:       return 'ok';
                   6241:     } else {
                   6242:       return "error:$!";
                   6243:     }
                   6244:   } else {
                   6245:     return "error:$!";
                   6246:   }
                   6247: }
1.167     albertel 6248: 
1.168     albertel 6249: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6250: 
1.168     albertel 6251: sub tmprestore {
                   6252:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6253: 
1.168     albertel 6254:   if (!$symb) {
                   6255:     $symb=&symbread();
1.620     albertel 6256:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6257:   }
                   6258:   $symb=escape($symb);
                   6259: 
1.620     albertel 6260:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6261: 
1.620     albertel 6262:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6263:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6264:   if ($domain eq 'public' && $stuname eq 'public') {
1.1434    raeburn  6265:       $stuname=&get_requestor_ip();
1.591     albertel 6266:   }
1.168     albertel 6267:   my %returnhash;
                   6268:   $namespace=~s/\//\_/g;
                   6269:   $namespace=~s/\W//g;
                   6270:   my %hash;
1.1117    foxr     6271:   my $path=LONCAPA::tempdir();
1.168     albertel 6272:   if (tie(%hash,'GDBM_File',
                   6273: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6274: 	  &GDBM_READER(),0640)) {
1.168     albertel 6275:     my $version=$hash{"version:$symb"};
                   6276:     $returnhash{'version'}=$version;
                   6277:     my $scope;
                   6278:     for ($scope=1;$scope<=$version;$scope++) {
                   6279:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6280:       my @keys=split(/:/,$vkeys);
                   6281:       my $key;
                   6282:       $returnhash{"$scope:keys"}=$vkeys;
                   6283:       foreach $key (@keys) {
1.591     albertel 6284: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6285: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6286:       }
                   6287:     }
1.168     albertel 6288:     if (!(untie(%hash))) {
                   6289:       return "error:$!";
                   6290:     }
                   6291:   } else {
                   6292:     return "error:$!";
                   6293:   }
                   6294:   return %returnhash;
1.167     albertel 6295: }
                   6296: 
1.9       www      6297: # ----------------------------------------------------------------------- Store
                   6298: 
                   6299: sub store {
1.1269    raeburn  6300:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6301:     my $home='';
                   6302: 
1.168     albertel 6303:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6304: 
1.213     www      6305:     $symb=&symbclean($symb);
1.122     albertel 6306:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6307: 
1.620     albertel 6308:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6309:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6310: 
                   6311:     &devalidate($symb,$stuname,$domain);
1.109     www      6312: 
                   6313:     $symb=escape($symb);
1.187     www      6314:     if (!$namespace) { 
1.620     albertel 6315:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6316:           return ''; 
                   6317:        } 
                   6318:     }
1.620     albertel 6319:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6320: 
1.1434    raeburn  6321:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6322:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6323: 
1.12      www      6324:     my $namevalue='';
1.800     albertel 6325:     foreach my $key (keys(%$storehash)) {
                   6326:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6327:     }
1.12      www      6328:     $namevalue=~s/\&$//;
1.187     www      6329:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  6330:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6331: }
                   6332: 
1.47      www      6333: # -------------------------------------------------------------- Critical Store
                   6334: 
                   6335: sub cstore {
1.1269    raeburn  6336:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6337:     my $home='';
                   6338: 
1.168     albertel 6339:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6340: 
1.213     www      6341:     $symb=&symbclean($symb);
1.122     albertel 6342:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6343: 
1.620     albertel 6344:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6345:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6346: 
                   6347:     &devalidate($symb,$stuname,$domain);
1.109     www      6348: 
                   6349:     $symb=escape($symb);
1.187     www      6350:     if (!$namespace) { 
1.620     albertel 6351:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6352:           return ''; 
                   6353:        } 
                   6354:     }
1.620     albertel 6355:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6356: 
1.1434    raeburn  6357:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6358:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6359: 
1.47      www      6360:     my $namevalue='';
1.800     albertel 6361:     foreach my $key (keys(%$storehash)) {
                   6362:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6363:     }
1.47      www      6364:     $namevalue=~s/\&$//;
1.187     www      6365:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6366:     return critical
1.1269    raeburn  6367:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6368: }
                   6369: 
1.9       www      6370: # --------------------------------------------------------------------- Restore
                   6371: 
                   6372: sub restore {
1.124     www      6373:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6374:     my $home='';
                   6375: 
1.168     albertel 6376:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6377: 
1.122     albertel 6378:     if (!$symb) {
1.1224    raeburn  6379:         return if ($namespace eq 'courserequests');
                   6380:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6381:     } else {
1.1224    raeburn  6382:         unless ($namespace eq 'courserequests') {
                   6383:             $symb=&escape(&symbclean($symb));
                   6384:         }
1.122     albertel 6385:     }
1.188     www      6386:     if (!$namespace) { 
1.620     albertel 6387:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6388:           return ''; 
                   6389:        } 
                   6390:     }
1.620     albertel 6391:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6392:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6393:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6394:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6395: 
1.12      www      6396:     my %returnhash=();
1.800     albertel 6397:     foreach my $line (split(/\&/,$answer)) {
                   6398: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6399:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6400:     }
1.75      www      6401:     my $version;
                   6402:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6403:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6404:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6405:        }
1.75      www      6406:     }
1.13      www      6407:     return %returnhash;
1.34      www      6408: }
                   6409: 
                   6410: # ---------------------------------------------------------- Course Description
1.1118    foxr     6411: #
                   6412: #  
1.34      www      6413: 
                   6414: sub coursedescription {
1.731     albertel 6415:     my ($courseid,$args)=@_;
1.34      www      6416:     $courseid=~s/^\///;
1.49      www      6417:     $courseid=~s/\_/\//g;
1.34      www      6418:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6419:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6420:     my $normalid=$cdomain.'_'.$cnum;
                   6421:     # need to always cache even if we get errors otherwise we keep 
                   6422:     # trying and trying and trying to get the course description.
                   6423:     my %envhash=();
                   6424:     my %returnhash=();
1.731     albertel 6425:     
                   6426:     my $expiretime=600;
                   6427:     if ($env{'request.course.id'} eq $normalid) {
                   6428: 	$expiretime=120;
                   6429:     }
                   6430: 
                   6431:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6432:     if (!$args->{'freshen_cache'}
                   6433: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6434: 	foreach my $key (keys(%env)) {
                   6435: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6436: 	    my ($setting) = $1;
                   6437: 	    $returnhash{$setting} = $env{$key};
                   6438: 	}
                   6439: 	return %returnhash;
                   6440:     }
                   6441: 
1.1118    foxr     6442:     # get the data again
                   6443: 
1.731     albertel 6444:     if (!$args->{'one_time'}) {
                   6445: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6446:     }
1.811     albertel 6447: 
1.34      www      6448:     if ($chome ne 'no_host') {
1.302     albertel 6449:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6450:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6451: 	   my $username = $env{'user.name'}; # Defult username
                   6452: 	   if(defined $args->{'user'}) {
                   6453: 	       $username = $args->{'user'};
                   6454: 	   }
1.129     albertel 6455:            $returnhash{'home'}= $chome;
                   6456: 	   $returnhash{'domain'} = $cdomain;
                   6457: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6458:            if (!defined($returnhash{'type'})) {
                   6459:                $returnhash{'type'} = 'Course';
                   6460:            }
1.130     albertel 6461:            while (my ($name,$value) = each %returnhash) {
1.53      www      6462:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6463:            }
1.270     www      6464:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6465:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6466: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6467:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6468:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6469:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6470:        }
                   6471:     }
1.731     albertel 6472:     if (!$args->{'one_time'}) {
1.949     raeburn  6473: 	&appenv(\%envhash);
1.731     albertel 6474:     }
1.302     albertel 6475:     return %returnhash;
1.461     www      6476: }
                   6477: 
1.1080    raeburn  6478: sub update_released_required {
                   6479:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6480:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6481:         $cid = $env{'request.course.id'};
                   6482:         $cdom = $env{'course.'.$cid.'.domain'};
                   6483:         $cnum = $env{'course.'.$cid.'.num'};
                   6484:         $chome = $env{'course.'.$cid.'.home'};
                   6485:     }
                   6486:     if ($needsrelease) {
                   6487:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6488:         my $needsupdate;
                   6489:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6490:             $needsupdate = 1;
                   6491:         } else {
                   6492:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6493:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6494:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6495:                 $needsupdate = 1;
                   6496:             }
                   6497:         }
                   6498:         if ($needsupdate) {
                   6499:             my %needshash = (
                   6500:                              'internal.releaserequired' => $needsrelease,
                   6501:                             );
                   6502:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6503:             if ($putresult eq 'ok') {
                   6504:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6505:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6506:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6507:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6508:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6509:                 }
                   6510:             }
                   6511:         }
                   6512:     }
                   6513:     return;
                   6514: }
                   6515: 
1.461     www      6516: # -------------------------------------------------See if a user is privileged
                   6517: 
                   6518: sub privileged {
1.1219    raeburn  6519:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6520:     my $now = time;
1.1219    raeburn  6521:     my $roles;
                   6522:     if (ref($possroles) eq 'ARRAY') {
                   6523:         $roles = $possroles; 
                   6524:     } else {
                   6525:         $roles = ['dc','su'];
                   6526:     }
                   6527:     if (ref($possdomains) eq 'ARRAY') {
                   6528:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6529:         foreach my $dom (@{$possdomains}) {
                   6530:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6531:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6532:                 foreach my $role (@{$roles}) {
                   6533:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6534:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6535:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6536:                             return 1 unless (($end && $end < $now) ||
                   6537:                                              ($start && $start > $now));
                   6538:                         }
                   6539:                     }
                   6540:                 }
                   6541:             }
                   6542:         }
                   6543:     } else {
                   6544:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6545:         my $now = time;
1.1170    droeschl 6546: 
1.1275    musolffc 6547:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6548:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  6549:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 6550:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  6551:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6552:             }
1.1219    raeburn  6553:         }
                   6554:     }
                   6555:     return 0;
                   6556: }
1.1170    droeschl 6557: 
1.1219    raeburn  6558: sub privileged_by_domain {
                   6559:     my ($domains,$roles) = @_;
                   6560:     my %privileged = ();
                   6561:     my $cachetime = 60*60*24;
                   6562:     my $now = time;
                   6563:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6564:         return %privileged;
                   6565:     }
                   6566:     foreach my $dom (@{$domains}) {
                   6567:         next if (ref($privileged{$dom}) eq 'HASH');
                   6568:         my $needroles;
                   6569:         foreach my $role (@{$roles}) {
                   6570:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6571:             if (defined($cached)) {
                   6572:                 if (ref($result) eq 'HASH') {
                   6573:                     $privileged{$dom}{$role} = $result;
                   6574:                 }
                   6575:             } else {
                   6576:                 $needroles = 1;
                   6577:             }
                   6578:         }
                   6579:         if ($needroles) {
                   6580:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6581:             $privileged{$dom} = {};
                   6582:             foreach my $server (keys(%dompersonnel)) {
                   6583:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6584:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6585:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6586:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6587:                         next if ($end && $end < $now);
                   6588:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   6589:                             $dompersonnel{$server}{$item};
                   6590:                     }
                   6591:                 }
                   6592:             }
                   6593:             if (ref($privileged{$dom}) eq 'HASH') {
                   6594:                 foreach my $role (@{$roles}) {
                   6595:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6596:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6597:                     } else {
                   6598:                         my %hash = ();
                   6599:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6600:                     }
                   6601:                 }
                   6602:             }
                   6603:         }
                   6604:     }
                   6605:     return %privileged;
1.9       www      6606: }
1.1       albertel 6607: 
1.103     harris41 6608: # -------------------------------------------------------- Get user privileges
1.11      www      6609: 
                   6610: sub rolesinit {
1.1169    droeschl 6611:     my ($domain, $username) = @_;
                   6612:     my %userroles = ('user.login.time' => time);
                   6613:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6614: 
                   6615:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6616:     # also, blocking can be triggered by an activating timer
                   6617:     # it's saved in the user's %env.
                   6618:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6619:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6620:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6621:         %timerintchk, %timerintenv);
                   6622: 
1.1162    raeburn  6623:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6624:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6625:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6626:     }
1.1169    droeschl 6627: 
1.1162    raeburn  6628:     foreach my $key (keys(%timerinterval)) {
                   6629:         my ($cid,$rest) = split(/\0/,$key);
                   6630:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6631:     }
1.1169    droeschl 6632: 
1.11      www      6633:     my %allroles=();
1.1162    raeburn  6634:     my %allgroups=();
1.11      www      6635: 
1.1274    raeburn  6636:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6637:         my $role = $rolesdump{$area};
                   6638:         $area =~ s/\_\w\w$//;
                   6639: 
                   6640:         my ($trole, $tend, $tstart, $group_privs);
                   6641: 
                   6642:         if ($role =~ /^cr/) {
                   6643:         # Custom role, defined by a user 
                   6644:         # e.g., user.role.cr/msu/smith/mynewrole
                   6645:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6646:                 $trole = $1;
                   6647:                 ($tend, $tstart) = split('_', $2);
                   6648:             } else {
                   6649:                 $trole = $role;
                   6650:             }
                   6651:         } elsif ($role =~ m|^gr/|) {
                   6652:         # Role of member in a group, defined within a course/community
                   6653:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6654:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6655:             next if $tstart eq '-1';
                   6656:             ($trole, $group_privs) = split(/\//, $trole);
                   6657:             $group_privs = &unescape($group_privs);
                   6658:         } else {
                   6659:         # Just a normal role, defined in roles.tab
                   6660:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6661:         }
                   6662: 
                   6663:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6664:                  $username);
                   6665:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6666: 
                   6667:         # role expired or not available yet?
                   6668:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6669:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6670: 
                   6671:         next if $area eq '' or $trole eq '';
                   6672: 
                   6673:         my $spec = "$trole.$area";
                   6674:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6675: 
                   6676:         if ($trole =~ /^cr\//) {
                   6677:         # Custom role, defined by a user
                   6678:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6679:         } elsif ($trole eq 'gr') {
                   6680:         # Role of a member in a group, defined within a course/community
                   6681:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6682:             next;
                   6683:         } else {
                   6684:         # Normal role, defined in roles.tab
                   6685:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6686:         }
                   6687: 
                   6688:         my $cid = $tdomain.'_'.$trest;
                   6689:         unless ($firstaccchk{$cid}) {
                   6690:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6691:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6692:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6693:                         $coursetimerstarts{$cid}{$item}; 
                   6694:                 }
                   6695:             }
                   6696:             $firstaccchk{$cid} = 1;
                   6697:         }
                   6698:         unless ($timerintchk{$cid}) {
                   6699:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6700:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6701:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6702:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6703:                 }
1.12      www      6704:             }
1.1169    droeschl 6705:             $timerintchk{$cid} = 1;
1.191     harris41 6706:         }
1.11      www      6707:     }
1.1169    droeschl 6708: 
1.1341    raeburn  6709:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6710:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6711:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6712:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6713: 
1.1162    raeburn  6714:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6715: }
                   6716: 
1.567     raeburn  6717: sub set_arearole {
1.1215    raeburn  6718:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6719:     unless ($nolog) {
1.567     raeburn  6720: # log the associated role with the area
1.1215    raeburn  6721:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6722:     }
1.743     albertel 6723:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6724: }
                   6725: 
                   6726: sub custom_roleprivs {
                   6727:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6728:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6729:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6730:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6731:         my ($rdummy,$roledef)=
                   6732:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6733:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6734:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6735:             if (defined($syspriv)) {
1.1043    raeburn  6736:                 if ($trest =~ /^$match_community$/) {
                   6737:                     $syspriv =~ s/bre\&S//; 
                   6738:                 }
1.567     raeburn  6739:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6740:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6741:             }
                   6742:             if ($tdomain ne '') {
                   6743:                 if (defined($dompriv)) {
                   6744:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6745:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6746:                 }
                   6747:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6748:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6749:                         my $rolename = $1;
                   6750:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6751:                     }
1.567     raeburn  6752:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6753:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6754:                 }
                   6755:             }
                   6756:         }
                   6757:     }
                   6758: }
                   6759: 
1.1332    raeburn  6760: sub course_adhocrole_privs {
                   6761:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6762:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6763:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6764:         my (%currprivs,%storeprivs);
                   6765:         foreach my $item (split(/:/,$coursepriv)) {
                   6766:             my ($priv,$restrict) = split(/\&/,$item);
                   6767:             $currprivs{$priv} = $restrict;
                   6768:         }
                   6769:         my (%possadd,%possremove,%full);
                   6770:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6771:             my ($priv,$restrict)=split(/\&/,$item);
                   6772:             $full{$priv} = $restrict;
                   6773:         }
                   6774:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6775:              next if ($item eq '');
                   6776:              my ($rule,$rest) = split(/=/,$item);
                   6777:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6778:              foreach my $priv (split(/:/,$rest)) {
                   6779:                  if ($priv ne '') {
                   6780:                      if ($rule eq 'off') {
                   6781:                          $possremove{$priv} = 1;
                   6782:                      } else {
                   6783:                          $possadd{$priv} = 1;
                   6784:                      }
                   6785:                  }
                   6786:              }
                   6787:          }
                   6788:          foreach my $priv (sort(keys(%full))) {
                   6789:              if (exists($currprivs{$priv})) {
                   6790:                  unless (exists($possremove{$priv})) {
                   6791:                      $storeprivs{$priv} = $currprivs{$priv};
                   6792:                  }
                   6793:              } elsif (exists($possadd{$priv})) {
                   6794:                  $storeprivs{$priv} = $full{$priv};
                   6795:              }
                   6796:          }
                   6797:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6798:      }
                   6799:      return $coursepriv;
                   6800: }
                   6801: 
1.678     raeburn  6802: sub group_roleprivs {
                   6803:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6804:     my $access = 1;
                   6805:     my $now = time;
                   6806:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6807:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6808:     if ($access) {
1.811     albertel 6809:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6810:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6811:     }
                   6812: }
1.567     raeburn  6813: 
                   6814: sub standard_roleprivs {
                   6815:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6816:     if (defined($pr{$trole.':s'})) {
                   6817:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6818:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6819:     }
                   6820:     if ($tdomain ne '') {
                   6821:         if (defined($pr{$trole.':d'})) {
                   6822:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6823:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6824:         }
                   6825:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6826:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6827:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6828:         }
                   6829:     }
                   6830: }
                   6831: 
                   6832: sub set_userprivs {
1.1064    raeburn  6833:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6834:     my $author=0;
                   6835:     my $adv=0;
1.1341    raeburn  6836:     my $rar=0;
1.678     raeburn  6837:     my %grouproles = ();
                   6838:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6839:         my @groupkeys; 
1.1000    raeburn  6840:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6841:             push(@groupkeys,$role);
                   6842:         }
                   6843:         if (ref($groups_roles) eq 'HASH') {
                   6844:             foreach my $key (keys(%{$groups_roles})) {
                   6845:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6846:                     push(@groupkeys,$key);
                   6847:                 }
                   6848:             }
                   6849:         }
                   6850:         if (@groupkeys > 0) {
                   6851:             foreach my $role (@groupkeys) {
                   6852:                 my ($trole,$area,$sec,$extendedarea);
                   6853:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6854:                     $trole = $1;
                   6855:                     $area = $2;
                   6856:                     $sec = $3;
                   6857:                     $extendedarea = $area.$sec;
                   6858:                     if (exists($$allgroups{$area})) {
                   6859:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6860:                             my $spec = $trole.'.'.$extendedarea;
                   6861:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6862:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6863:                         }
1.678     raeburn  6864:                     }
                   6865:                 }
                   6866:             }
                   6867:         }
                   6868:     }
1.800     albertel 6869:     foreach my $group (keys(%grouproles)) {
                   6870:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6871:     }
1.800     albertel 6872:     foreach my $role (keys(%{$allroles})) {
                   6873:         my %thesepriv;
1.941     raeburn  6874:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6875:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6876:             if ($item ne '') {
                   6877:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6878:                 if ($restrictions eq '') {
                   6879:                     $thesepriv{$privilege}='F';
                   6880:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6881:                     $thesepriv{$privilege}.=$restrictions;
                   6882:                 }
                   6883:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6884:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6885:             }
                   6886:         }
                   6887:         my $thesestr='';
1.1104    raeburn  6888:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6889: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6890: 	}
                   6891:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6892:     }
1.1341    raeburn  6893:     return ($author,$adv,$rar);
1.567     raeburn  6894: }
                   6895: 
1.994     raeburn  6896: sub role_status {
1.1104    raeburn  6897:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6898:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6899:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6900:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6901:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6902:             $$where = '/'.$two;
1.994     raeburn  6903:             $$trolecode=$$role.'.'.$$where;
                   6904:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6905:             $$tstatus='is';
1.1104    raeburn  6906:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6907:                 $$tstatus='future';
1.1034    raeburn  6908:                 if ($$tstart<$now) {
                   6909:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6910:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6911:                             my (%allroles,%allgroups,$group_privs,
                   6912:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6913:                             my %userroles = (
                   6914:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6915:                             );
1.1064    raeburn  6916:                             @rolecodes = ('cm'); 
1.1002    raeburn  6917:                             my $spec=$$role.'.'.$$where;
                   6918:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6919:                             if ($$role =~ /^cr\//) {
                   6920:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6921:                                 push(@rolecodes,'cr');
1.1002    raeburn  6922:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6923:                                 push(@rolecodes,$$role);
1.1002    raeburn  6924:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6925:                                                     $env{'user.name'});
1.1064    raeburn  6926:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6927:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6928:                                 $group_privs = &unescape($group_privs);
                   6929:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6930:                                 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  6931:                                 &get_groups_roles($tdomain,$trest,
                   6932:                                                   \%course_roles,\@rolecodes,
                   6933:                                                   \%groups_roles);
1.1002    raeburn  6934:                             } else {
1.1064    raeburn  6935:                                 push(@rolecodes,$$role);
1.1002    raeburn  6936:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6937:                             }
1.1341    raeburn  6938:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6939:                                                                    \%groups_roles);
1.1064    raeburn  6940:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6941:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6942:                         }
                   6943:                     }
1.1034    raeburn  6944:                     $$tstatus = 'is';
1.1002    raeburn  6945:                 }
1.994     raeburn  6946:             }
                   6947:             if ($$tend) {
1.1104    raeburn  6948:                 if ($$tend<$update) {
1.994     raeburn  6949:                     $$tstatus='expired';
                   6950:                 } elsif ($$tend<$now) {
                   6951:                     $$tstatus='will_not';
                   6952:                 }
                   6953:             }
                   6954:         }
                   6955:     }
                   6956: }
                   6957: 
1.1104    raeburn  6958: sub get_groups_roles {
                   6959:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6960:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6961:                   (ref($rolecodes) eq 'ARRAY') && 
                   6962:                   (ref($groups_roles) eq 'HASH')); 
                   6963:     if (keys(%{$cdom_courseroles}) > 0) {
                   6964:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6965:         if ($cdom ne '' && $cnum ne '') {
                   6966:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6967:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6968:                     my $crsrole = $1;
                   6969:                     my $crssec = $2;
                   6970:                     if ($crsrole =~ /^cr/) {
                   6971:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6972:                             push(@{$rolecodes},'cr');
                   6973:                         }
                   6974:                     } else {
                   6975:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6976:                             push(@{$rolecodes},$crsrole);
                   6977:                         }
                   6978:                     }
                   6979:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6980:                     if ($crssec ne '') {
                   6981:                         $rolekey .= "/$crssec";
                   6982:                     }
                   6983:                     $rolekey .= './';
                   6984:                     $groups_roles->{$rolekey} = $rolecodes;
                   6985:                 }
                   6986:             }
                   6987:         }
                   6988:     }
                   6989:     return;
                   6990: }
                   6991: 
                   6992: sub delete_env_groupprivs {
                   6993:     my ($where,$courseroles,$possroles) = @_;
                   6994:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6995:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6996:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6997:         %{$courseroles->{$udom}} =
                   6998:             &get_my_roles('','','userroles',['active'],
                   6999:                           $possroles,[$udom],1);
                   7000:     }
                   7001:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   7002:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   7003:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   7004:             my $area = '/'.$cdom.'/'.$cnum;
                   7005:             my $privkey = "user.priv.$crsrole.$area";
                   7006:             if ($crssec ne '') {
                   7007:                 $privkey .= '/'.$crssec;
                   7008:             }
                   7009:             $privkey .= ".$area/$group";
                   7010:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   7011:         }
                   7012:     }
                   7013:     return;
                   7014: }
                   7015: 
1.994     raeburn  7016: sub check_adhoc_privs {
1.1329    raeburn  7017:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  7018:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  7019:     if ($sec) {
                   7020:         $cckey .= '/'.$sec;
                   7021:     } 
1.1185    raeburn  7022:     my $setprivs;
1.994     raeburn  7023:     if ($env{$cckey}) {
                   7024:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  7025:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  7026:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  7027:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  7028:             $setprivs = 1;
1.994     raeburn  7029:         }
                   7030:     } else {
1.1330    raeburn  7031:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  7032:         $setprivs = 1;
1.994     raeburn  7033:     }
1.1185    raeburn  7034:     return $setprivs;
1.994     raeburn  7035: }
                   7036: 
                   7037: sub set_adhoc_privileges {
1.1326    raeburn  7038: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  7039:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  7040:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  7041:     if ($sec ne '') {
                   7042:         $area .= '/'.$sec;
                   7043:     }
1.994     raeburn  7044:     my $spec = $role.'.'.$area;
                   7045:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  7046:                                   $env{'user.name'},1);
1.1326    raeburn  7047:     my %rolehash = ();
1.1332    raeburn  7048:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   7049:         my $rolename = $1;
1.1326    raeburn  7050:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  7051:         my %domdef = &get_domain_defaults($dcdom);
                   7052:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   7053:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   7054:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   7055:             }
                   7056:         }
1.1326    raeburn  7057:     } else {
                   7058:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   7059:     }
1.1341    raeburn  7060:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  7061:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  7062:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402    raeburn  7063:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   7064:             ($caller eq 'tiny')) {
1.1088    raeburn  7065:         &appenv( {'request.role'        => $spec,
                   7066:                   'request.role.domain' => $dcdom,
1.1332    raeburn  7067:                   'request.course.sec'  => $sec,
1.1088    raeburn  7068:                  }
                   7069:                );
                   7070:         my $tadv=0;
                   7071:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   7072:         &appenv({'request.role.adv'    => $tadv});
                   7073:     }
1.994     raeburn  7074: }
                   7075: 
1.12      www      7076: # --------------------------------------------------------------- get interface
                   7077: 
                   7078: sub get {
1.131     albertel 7079:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7080:    my $items='';
1.800     albertel 7081:    foreach my $item (@$storearr) {
                   7082:        $items.=&escape($item).'&';
1.191     harris41 7083:    }
1.12      www      7084:    $items=~s/\&$//;
1.620     albertel 7085:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7086:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 7087:    my $uhome=&homeserver($uname,$udomain);
                   7088: 
1.133     albertel 7089:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7090:    my @pairs=split(/\&/,$rep);
1.273     albertel 7091:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   7092:      return @pairs;
                   7093:    }
1.15      www      7094:    my %returnhash=();
1.42      www      7095:    my $i=0;
1.800     albertel 7096:    foreach my $item (@$storearr) {
                   7097:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7098:       $i++;
1.191     harris41 7099:    }
1.15      www      7100:    return %returnhash;
1.27      www      7101: }
                   7102: 
                   7103: # --------------------------------------------------------------- del interface
                   7104: 
                   7105: sub del {
1.133     albertel 7106:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      7107:    my $items='';
1.800     albertel 7108:    foreach my $item (@$storearr) {
                   7109:        $items.=&escape($item).'&';
1.191     harris41 7110:    }
1.984     neumanie 7111: 
1.27      www      7112:    $items=~s/\&$//;
1.620     albertel 7113:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7114:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7115:    my $uhome=&homeserver($uname,$udomain);
                   7116:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7117: }
                   7118: 
                   7119: # -------------------------------------------------------------- dump interface
                   7120: 
1.1180    droeschl 7121: sub unserialize {
                   7122:     my ($rep, $escapedkeys) = @_;
                   7123: 
                   7124:     return {} if $rep =~ /^error/;
                   7125: 
                   7126:     my %returnhash=();
1.1252    raeburn  7127: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 7128: 	    my ($key, $value) = split(/=/, $item, 2);
                   7129: 	    $key = unescape($key) unless $escapedkeys;
                   7130: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  7131: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 7132: 	}
                   7133:     #return %returnhash;
                   7134:     return \%returnhash;
                   7135: }        
                   7136: 
                   7137: # see Lond::dump_with_regexp
                   7138: # if $escapedkeys hash keys won't get unescaped.
1.15      www      7139: sub dump {
1.1462    raeburn  7140:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755     albertel 7141:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7142:     if (!$uname) { $uname=$env{'user.name'}; }
                   7143:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 7144: 
1.1266    raeburn  7145:     if ($regexp) {
                   7146:         $regexp=&escape($regexp);
                   7147:     } else {
                   7148:         $regexp='.';
                   7149:     }
1.1180    droeschl 7150:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   7151:         # user is hosted on this machine
1.1266    raeburn  7152:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  7153:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 7154:         return %{unserialize($reply, $escapedkeys)};
                   7155:     }
1.1462    raeburn  7156:     my $rep;
                   7157:     if ($encrypt) {
                   7158:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.1463    raeburn  7159:     } else {
1.1462    raeburn  7160:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7161:     }
1.755     albertel 7162:     my @pairs=split(/\&/,$rep);
                   7163:     my %returnhash=();
1.1098    foxr     7164:     if (!($rep =~ /^error/ )) {
                   7165: 	foreach my $item (@pairs) {
                   7166: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 7167:         $key = unescape($key) unless $escapedkeys;
                   7168:         #$key = &unescape($key);
1.1098    foxr     7169: 	    next if ($key =~ /^error: 2 /);
                   7170: 	    $returnhash{$key}=&thaw_unescape($value);
                   7171: 	}
1.755     albertel 7172:     }
                   7173:     return %returnhash;
1.407     www      7174: }
                   7175: 
1.1098    foxr     7176: 
1.717     albertel 7177: # --------------------------------------------------------- dumpstore interface
                   7178: 
                   7179: sub dumpstore {
                   7180:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 7181:    # same as dump but keys must be escaped. They may contain colon separated
                   7182:    # lists of values that may themself contain colons (e.g. symbs).
                   7183:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7184: }
                   7185: 
1.407     www      7186: # -------------------------------------------------------------- keys interface
                   7187: 
                   7188: sub getkeys {
                   7189:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7190:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7191:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7192:    my $uhome=&homeserver($uname,$udomain);
                   7193:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7194:    my @keyarray=();
1.800     albertel 7195:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7196:       next if ($key =~ /^error: 2 /);
1.800     albertel 7197:       push(@keyarray,&unescape($key));
1.407     www      7198:    }
                   7199:    return @keyarray;
1.318     matthew  7200: }
                   7201: 
1.319     matthew  7202: # --------------------------------------------------------------- currentdump
                   7203: sub currentdump {
1.328     matthew  7204:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7205:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7206:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7207:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7208:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 7209:    my $rep;
                   7210: 
                   7211:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7212:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   7213:                    $courseid)));
                   7214:    } else {
                   7215:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7216:    }
                   7217: 
1.318     matthew  7218:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7219:    #
1.318     matthew  7220:    my %returnhash=();
1.319     matthew  7221:    #
1.1343    raeburn  7222:    if ($rep eq 'unknown_cmd') {
1.319     matthew  7223:        # an old lond will not know currentdump
                   7224:        # Do a dump and make it look like a currentdump
1.822     albertel 7225:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7226:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7227:        my %hash = @tmp;
                   7228:        @tmp=();
1.424     matthew  7229:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7230:    } else {
                   7231:        my @pairs=split(/\&/,$rep);
1.800     albertel 7232:        foreach my $pair (@pairs) {
                   7233:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7234:            my ($symb,$param) = split(/:/,$key);
                   7235:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7236:                                                         &thaw_unescape($value);
1.319     matthew  7237:        }
1.191     harris41 7238:    }
1.12      www      7239:    return %returnhash;
1.424     matthew  7240: }
                   7241: 
                   7242: sub convert_dump_to_currentdump{
                   7243:     my %hash = %{shift()};
                   7244:     my %returnhash;
                   7245:     # Code ripped from lond, essentially.  The only difference
                   7246:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7247:     # we might run in to problems with parameter names =~ /^v\./
                   7248:     while (my ($key,$value) = each(%hash)) {
                   7249:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7250: 	$symb  = &unescape($symb);
                   7251: 	$param = &unescape($param);
1.424     matthew  7252:         next if ($v eq 'version' || $symb eq 'keys');
                   7253:         next if (exists($returnhash{$symb}) &&
                   7254:                  exists($returnhash{$symb}->{$param}) &&
                   7255:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7256:         $returnhash{$symb}->{$param}=$value;
                   7257:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7258:     }
                   7259:     #
                   7260:     # Remove all of the keys in the hashes which keep track of
                   7261:     # the version of the parameter.
                   7262:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7263:         # use a foreach because we are going to delete from the hash.
                   7264:         foreach my $key (keys(%$param_hash)) {
                   7265:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7266:         }
                   7267:     }
                   7268:     return \%returnhash;
1.12      www      7269: }
                   7270: 
1.627     albertel 7271: # ------------------------------------------------------ critical inc interface
                   7272: 
                   7273: sub cinc {
                   7274:     return &inc(@_,'critical');
                   7275: }
                   7276: 
1.449     matthew  7277: # --------------------------------------------------------------- inc interface
                   7278: 
                   7279: sub inc {
1.627     albertel 7280:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7281:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7282:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7283:     my $uhome=&homeserver($uname,$udomain);
                   7284:     my $items='';
                   7285:     if (! ref($store)) {
                   7286:         # got a single value, so use that instead
                   7287:         $items = &escape($store).'=&';
                   7288:     } elsif (ref($store) eq 'SCALAR') {
                   7289:         $items = &escape($$store).'=&';        
                   7290:     } elsif (ref($store) eq 'ARRAY') {
                   7291:         $items = join('=&',map {&escape($_);} @{$store});
                   7292:     } elsif (ref($store) eq 'HASH') {
                   7293:         while (my($key,$value) = each(%{$store})) {
                   7294:             $items.= &escape($key).'='.&escape($value).'&';
                   7295:         }
                   7296:     }
                   7297:     $items=~s/\&$//;
1.627     albertel 7298:     if ($critical) {
                   7299: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7300:     } else {
                   7301: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7302:     }
1.449     matthew  7303: }
                   7304: 
1.12      www      7305: # --------------------------------------------------------------- put interface
                   7306: 
                   7307: sub put {
1.1462    raeburn  7308:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620     albertel 7309:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7310:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7311:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7312:    my $items='';
1.800     albertel 7313:    foreach my $item (keys(%$storehash)) {
                   7314:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7315:    }
1.12      www      7316:    $items=~s/\&$//;
1.1462    raeburn  7317:    if ($encrypt) {
                   7318:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
                   7319:    } else {
                   7320:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   7321:    }
1.47      www      7322: }
                   7323: 
1.631     albertel 7324: # ------------------------------------------------------------ newput interface
                   7325: 
                   7326: sub newput {
                   7327:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7328:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7329:    if (!$uname) { $uname=$env{'user.name'}; }
                   7330:    my $uhome=&homeserver($uname,$udomain);
                   7331:    my $items='';
                   7332:    foreach my $key (keys(%$storehash)) {
                   7333:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7334:    }
                   7335:    $items=~s/\&$//;
                   7336:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7337: }
                   7338: 
                   7339: # ---------------------------------------------------------  putstore interface
                   7340: 
1.524     raeburn  7341: sub putstore {
1.1269    raeburn  7342:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7343:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7344:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7345:    my $uhome=&homeserver($uname,$udomain);
                   7346:    my $items='';
1.715     albertel 7347:    foreach my $key (keys(%$storehash)) {
                   7348:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7349:    }
1.715     albertel 7350:    $items=~s/\&$//;
1.716     albertel 7351:    my $esc_symb=&escape($symb);
                   7352:    my $esc_v=&escape($version);
1.715     albertel 7353:    my $reply =
1.716     albertel 7354:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7355: 	      $uhome);
1.1269    raeburn  7356:    if (($tolog) && ($reply eq 'ok')) {
                   7357:        my $namevalue='';
                   7358:        foreach my $key (keys(%{$storehash})) {
                   7359:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7360:        }
1.1434    raeburn  7361:        my $ip = &get_requestor_ip();
                   7362:        $namevalue .= 'ip='.&escape($ip).
1.1269    raeburn  7363:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7364:                      '&version='.$esc_v.
                   7365:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7366:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7367:    }
1.715     albertel 7368:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7369:        # gfall back to way things use to be done
1.715     albertel 7370:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7371: 			    $uname);
1.524     raeburn  7372:    }
1.715     albertel 7373:    return $reply;
                   7374: }
                   7375: 
                   7376: sub old_putstore {
1.716     albertel 7377:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7378:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7379:     if (!$uname) { $uname=$env{'user.name'}; }
                   7380:     my $uhome=&homeserver($uname,$udomain);
                   7381:     my %newstorehash;
1.800     albertel 7382:     foreach my $item (keys(%$storehash)) {
                   7383: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7384: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7385:     }
                   7386:     my $items='';
                   7387:     my %allitems = ();
1.800     albertel 7388:     foreach my $item (keys(%newstorehash)) {
                   7389: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7390: 	    my $key = $1.':keys:'.$2;
                   7391: 	    $allitems{$key} .= $3.':';
                   7392: 	}
1.800     albertel 7393: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7394:     }
1.800     albertel 7395:     foreach my $item (keys(%allitems)) {
                   7396: 	$allitems{$item} =~ s/\:$//;
                   7397: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7398:     }
                   7399:     $items=~s/\&$//;
                   7400:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7401: }
                   7402: 
1.47      www      7403: # ------------------------------------------------------ critical put interface
                   7404: 
                   7405: sub cput {
1.134     albertel 7406:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7407:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7408:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7409:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7410:    my $items='';
1.800     albertel 7411:    foreach my $item (keys(%$storehash)) {
                   7412:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7413:    }
1.47      www      7414:    $items=~s/\&$//;
1.134     albertel 7415:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7416: }
                   7417: 
                   7418: # -------------------------------------------------------------- eget interface
                   7419: 
                   7420: sub eget {
1.133     albertel 7421:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7422:    my $items='';
1.800     albertel 7423:    foreach my $item (@$storearr) {
                   7424:        $items.=&escape($item).'&';
1.191     harris41 7425:    }
1.12      www      7426:    $items=~s/\&$//;
1.620     albertel 7427:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7428:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7429:    my $uhome=&homeserver($uname,$udomain);
                   7430:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7431:    my @pairs=split(/\&/,$rep);
                   7432:    my %returnhash=();
1.42      www      7433:    my $i=0;
1.800     albertel 7434:    foreach my $item (@$storearr) {
                   7435:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7436:       $i++;
1.191     harris41 7437:    }
1.12      www      7438:    return %returnhash;
                   7439: }
                   7440: 
1.667     albertel 7441: # ------------------------------------------------------------ tmpput interface
                   7442: sub tmpput {
1.802     raeburn  7443:     my ($storehash,$server,$context)=@_;
1.667     albertel 7444:     my $items='';
1.800     albertel 7445:     foreach my $item (keys(%$storehash)) {
                   7446: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7447:     }
                   7448:     $items=~s/\&$//;
1.802     raeburn  7449:     if (defined($context)) {
                   7450:         $items .= ':'.&escape($context);
                   7451:     }
1.667     albertel 7452:     return &reply("tmpput:$items",$server);
                   7453: }
                   7454: 
                   7455: # ------------------------------------------------------------ tmpget interface
                   7456: sub tmpget {
1.688     albertel 7457:     my ($token,$server)=@_;
                   7458:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7459:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7460:     my %returnhash;
1.1328    raeburn  7461:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7462:         return %returnhash;
                   7463:     }
1.667     albertel 7464:     foreach my $item (split(/\&/,$rep)) {
                   7465: 	my ($key,$value)=split(/=/,$item);
                   7466: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7467:     }
                   7468:     return %returnhash;
                   7469: }
                   7470: 
1.1113    raeburn  7471: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7472: sub tmpdel {
                   7473:     my ($token,$server)=@_;
                   7474:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7475:     return &reply("tmpdel:$token",$server);
                   7476: }
                   7477: 
1.1198    raeburn  7478: # ------------------------------------------------------------ get_timebased_id 
                   7479: 
                   7480: sub get_timebased_id {
                   7481:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7482:         $maxtries) = @_;
                   7483:     my ($newid,$error,$dellock);
                   7484:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   7485:         return ('','ok','invalid call to get suffix');
                   7486:     }
                   7487: 
                   7488: # set defaults for any optional args for which values were not supplied
                   7489:     if ($who eq '') {
                   7490:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7491:     }
                   7492:     if (!$locktries) {
                   7493:         $locktries = 3;
                   7494:     }
                   7495:     if (!$maxtries) {
                   7496:         $maxtries = 10;
                   7497:     }
                   7498:     
                   7499:     if (($cdom eq '') || ($cnum eq '')) {
                   7500:         if ($env{'request.course.id'}) {
                   7501:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7502:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7503:         }
                   7504:         if (($cdom eq '') || ($cnum eq '')) {
                   7505:             return ('','ok','call to get suffix not in course context');
                   7506:         }
                   7507:     }
                   7508: 
                   7509: # construct locking item
                   7510:     my $lockhash = {
                   7511:                       $prefix."\0".'locked_'.$keyid => $who,
                   7512:                    };
                   7513:     my $tries = 0;
                   7514: 
                   7515: # attempt to get lock on nohist_$namespace file
                   7516:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7517:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7518:         $tries ++;
                   7519:         sleep 1;
                   7520:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7521:     }
                   7522: 
                   7523: # attempt to get unique identifier, based on current timestamp
                   7524:     if ($gotlock eq 'ok') {
                   7525:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7526:         my $id = time;
                   7527:         $newid = $id;
1.1268    raeburn  7528:         if ($idtype eq 'addcode') {
                   7529:             $newid .= &sixnum_code();
                   7530:         }
1.1198    raeburn  7531:         my $idtries = 0;
                   7532:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7533:             if ($idtype eq 'concat') {
                   7534:                 $newid = $id.$idtries;
1.1268    raeburn  7535:             } elsif ($idtype eq 'addcode') {
                   7536:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  7537:             } else {
                   7538:                 $newid ++;
                   7539:             }
                   7540:             $idtries ++;
                   7541:         }
                   7542:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7543:             my %new_item =  (
                   7544:                               $prefix."\0".$newid => $who,
                   7545:                             );
                   7546:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7547:                                                  $cdom,$cnum);
                   7548:             if ($putresult ne 'ok') {
                   7549:                 undef($newid);
                   7550:                 $error = 'error saving new item: '.$putresult;
                   7551:             }
                   7552:         } else {
1.1268    raeburn  7553:              undef($newid);
1.1198    raeburn  7554:              $error = ('error: no unique suffix available for the new item ');
                   7555:         }
                   7556: #  remove lock
                   7557:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7558:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7559:     } else {
                   7560:         $error = "error: could not obtain lockfile\n";
                   7561:         $dellock = 'ok';
1.1276    raeburn  7562:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7563:             $dellock = 'nolock';
                   7564:         }
1.1198    raeburn  7565:     }
                   7566:     return ($newid,$dellock,$error);
                   7567: }
                   7568: 
1.1268    raeburn  7569: sub sixnum_code {
                   7570:     my $code;
                   7571:     for (0..6) {
                   7572:         $code .= int( rand(9) );
                   7573:     }
                   7574:     return $code;
                   7575: }
                   7576: 
1.765     albertel 7577: # -------------------------------------------------- portfolio access checking
                   7578: 
                   7579: sub portfolio_access {
1.1270    raeburn  7580:     my ($requrl,$clientip) = @_;
1.765     albertel 7581:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  7582:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7583:     if ($result) {
                   7584:         my %setters;
                   7585:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7586:             my ($startblock,$endblock) =
                   7587:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7588:             if ($startblock && $endblock) {
                   7589:                 return 'B';
                   7590:             }
                   7591:         } else {
                   7592:             my ($startblock,$endblock) =
                   7593:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7594:             if ($startblock && $endblock) {
                   7595:                 return 'B';
                   7596:             }
                   7597:         }
                   7598:     }
1.765     albertel 7599:     if ($result eq 'ok') {
1.766     albertel 7600:        return 'F';
1.765     albertel 7601:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7602:        return 'A';
1.765     albertel 7603:     }
1.766     albertel 7604:     return '';
1.765     albertel 7605: }
                   7606: 
                   7607: sub get_portfolio_access {
1.1270    raeburn  7608:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7609: 
                   7610:     if (!ref($access_hash)) {
                   7611: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7612: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7613: 						   $file_name);
                   7614: 	$access_hash = $access_controls{$file_name};
                   7615:     }
                   7616: 
1.1270    raeburn  7617:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7618:     my $now = time;
                   7619:     if (ref($access_hash) eq 'HASH') {
                   7620:         foreach my $key (keys(%{$access_hash})) {
                   7621:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7622:             if ($start > $now) {
                   7623:                 next;
                   7624:             }
                   7625:             if ($end && $end<$now) {
                   7626:                 next;
                   7627:             }
                   7628:             if ($scope eq 'public') {
                   7629:                 $public = $key;
                   7630:                 last;
                   7631:             } elsif ($scope eq 'guest') {
                   7632:                 $guest = $key;
                   7633:             } elsif ($scope eq 'domains') {
                   7634:                 push(@domains,$key);
                   7635:             } elsif ($scope eq 'users') {
                   7636:                 push(@users,$key);
                   7637:             } elsif ($scope eq 'course') {
                   7638:                 push(@courses,$key);
                   7639:             } elsif ($scope eq 'group') {
                   7640:                 push(@groups,$key);
1.1270    raeburn  7641:             } elsif ($scope eq 'ip') {
                   7642:                 push(@ips,$key);
1.765     albertel 7643:             }
                   7644:         }
                   7645:         if ($public) {
                   7646:             return 'ok';
1.1270    raeburn  7647:         } elsif (@ips > 0) {
                   7648:             my $allowed;
                   7649:             foreach my $ipkey (@ips) {
                   7650:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7651:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7652:                         $allowed = 1;
                   7653:                         last; 
                   7654:                     }
                   7655:                 }
                   7656:             }
                   7657:             if ($allowed) {
                   7658:                 return 'ok';
                   7659:             }
1.765     albertel 7660:         }
                   7661:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7662:             if ($guest) {
                   7663:                 return $guest;
                   7664:             }
                   7665:         } else {
                   7666:             if (@domains > 0) {
                   7667:                 foreach my $domkey (@domains) {
                   7668:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7669:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7670:                             return 'ok';
                   7671:                         }
                   7672:                     }
                   7673:                 }
                   7674:             }
                   7675:             if (@users > 0) {
                   7676:                 foreach my $userkey (@users) {
1.865     raeburn  7677:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7678:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7679:                             if (ref($item) eq 'HASH') {
                   7680:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7681:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7682:                                     return 'ok';
                   7683:                                 }
                   7684:                             }
                   7685:                         }
                   7686:                     } 
1.765     albertel 7687:                 }
                   7688:             }
                   7689:             my %roleshash;
                   7690:             my @courses_and_groups = @courses;
                   7691:             push(@courses_and_groups,@groups); 
                   7692:             if (@courses_and_groups > 0) {
                   7693:                 my (%allgroups,%allroles); 
                   7694:                 my ($start,$end,$role,$sec,$group);
                   7695:                 foreach my $envkey (%env) {
1.1060    raeburn  7696:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7697:                         my $cid = $2.'_'.$3; 
                   7698:                         if ($1 eq 'gr') {
                   7699:                             $group = $4;
                   7700:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7701:                         } else {
                   7702:                             if ($4 eq '') {
                   7703:                                 $sec = 'none';
                   7704:                             } else {
                   7705:                                 $sec = $4;
                   7706:                             }
                   7707:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7708:                         }
1.811     albertel 7709:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7710:                         my $cid = $2.'_'.$3;
                   7711:                         if ($4 eq '') {
                   7712:                             $sec = 'none';
                   7713:                         } else {
                   7714:                             $sec = $4;
                   7715:                         }
                   7716:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7717:                     }
                   7718:                 }
                   7719:                 if (keys(%allroles) == 0) {
                   7720:                     return;
                   7721:                 }
                   7722:                 foreach my $key (@courses_and_groups) {
                   7723:                     my %content = %{$$access_hash{$key}};
                   7724:                     my $cnum = $content{'number'};
                   7725:                     my $cdom = $content{'domain'};
                   7726:                     my $cid = $cdom.'_'.$cnum;
                   7727:                     if (!exists($allroles{$cid})) {
                   7728:                         next;
                   7729:                     }    
                   7730:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7731:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7732:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7733:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7734:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7735:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7736:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7737:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7738:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7739:                                         if (grep/^all$/,@sections) {
                   7740:                                             return 'ok';
                   7741:                                         } else {
                   7742:                                             if (grep/^$sec$/,@sections) {
                   7743:                                                 return 'ok';
                   7744:                                             }
                   7745:                                         }
                   7746:                                     }
                   7747:                                 }
                   7748:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7749:                                     if (grep/^none$/,@groups) {
                   7750:                                         return 'ok';
                   7751:                                     }
                   7752:                                 } else {
                   7753:                                     if (grep/^all$/,@groups) {
                   7754:                                         return 'ok';
                   7755:                                     } 
                   7756:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7757:                                         if (grep/^$group$/,@groups) {
                   7758:                                             return 'ok';
                   7759:                                         }
                   7760:                                     }
                   7761:                                 } 
                   7762:                             }
                   7763:                         }
                   7764:                     }
                   7765:                 }
                   7766:             }
                   7767:             if ($guest) {
                   7768:                 return $guest;
                   7769:             }
                   7770:         }
                   7771:     }
                   7772:     return;
                   7773: }
                   7774: 
                   7775: sub course_group_datechecker {
                   7776:     my ($dates,$now,$status) = @_;
                   7777:     my ($start,$end) = split(/\./,$dates);
                   7778:     if (!$start && !$end) {
                   7779:         return 'ok';
                   7780:     }
                   7781:     if (grep/^active$/,@{$status}) {
                   7782:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7783:             return 'ok';
                   7784:         }
                   7785:     }
                   7786:     if (grep/^previous$/,@{$status}) {
                   7787:         if ($end > $now ) {
                   7788:             return 'ok';
                   7789:         }
                   7790:     }
                   7791:     if (grep/^future$/,@{$status}) {
                   7792:         if ($start > $now) {
                   7793:             return 'ok';
                   7794:         }
                   7795:     }
                   7796:     return; 
                   7797: }
                   7798: 
                   7799: sub parse_portfolio_url {
                   7800:     my ($url) = @_;
                   7801: 
                   7802:     my ($type,$udom,$unum,$group,$file_name);
                   7803:     
1.823     albertel 7804:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7805: 	$type = 1;
                   7806:         $udom = $1;
                   7807:         $unum = $2;
                   7808:         $file_name = $3;
1.823     albertel 7809:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7810: 	$type = 2;
                   7811:         $udom = $1;
                   7812:         $unum = $2;
                   7813:         $group = $3;
                   7814:         $file_name = $3.'/'.$4;
                   7815:     }
                   7816:     if (wantarray) {
                   7817: 	return ($type,$udom,$unum,$file_name,$group);
                   7818:     }
                   7819:     return $type;
                   7820: }
                   7821: 
                   7822: sub is_portfolio_url {
                   7823:     my ($url) = @_;
                   7824:     return scalar(&parse_portfolio_url($url));
                   7825: }
                   7826: 
1.798     raeburn  7827: sub is_portfolio_file {
                   7828:     my ($file) = @_;
1.820     raeburn  7829:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7830:         return 1;
                   7831:     }
                   7832:     return;
                   7833: }
                   7834: 
1.976     raeburn  7835: sub usertools_access {
1.1084    raeburn  7836:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7837:     my ($access,%tools);
                   7838:     if ($context eq '') {
                   7839:         $context = 'tools';
                   7840:     }
                   7841:     if ($context eq 'requestcourses') {
                   7842:         %tools = (
                   7843:                       official   => 1,
                   7844:                       unofficial => 1,
1.1006    raeburn  7845:                       community  => 1,
1.1246    raeburn  7846:                       textbook   => 1,
1.1305    raeburn  7847:                       placement  => 1,
1.1368    raeburn  7848:                       lti        => 1,
1.985     raeburn  7849:                  );
1.1183    raeburn  7850:     } elsif ($context eq 'requestauthor') {
                   7851:         %tools = (
                   7852:                       requestauthor => 1,
                   7853:                  );
1.985     raeburn  7854:     } else {
                   7855:         %tools = (
                   7856:                       aboutme   => 1,
                   7857:                       blog      => 1,
1.1177    raeburn  7858:                       webdav    => 1,
1.985     raeburn  7859:                       portfolio => 1,
                   7860:                  );
                   7861:     }
1.976     raeburn  7862:     return if (!defined($tools{$tool}));
                   7863: 
1.1242    raeburn  7864:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7865:         $udom = $env{'user.domain'};
                   7866:         $uname = $env{'user.name'};
                   7867:     }
                   7868: 
1.978     raeburn  7869:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7870:         if ($action ne 'reload') {
1.985     raeburn  7871:             if ($context eq 'requestcourses') {
                   7872:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7873:             } elsif ($context eq 'requestauthor') {
                   7874:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7875:             } else {
                   7876:                 return $env{'environment.availabletools.'.$tool};
                   7877:             }
                   7878:         }
1.976     raeburn  7879:     }
                   7880: 
1.1183    raeburn  7881:     my ($toolstatus,$inststatus,$envkey);
                   7882:     if ($context eq 'requestauthor') {
                   7883:         $envkey = $context; 
                   7884:     } else {
                   7885:         $envkey = $context.'.'.$tool;
                   7886:     }
1.976     raeburn  7887: 
1.985     raeburn  7888:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7889:          ($action ne 'reload')) {
1.1183    raeburn  7890:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7891:         $inststatus = $env{'environment.inststatus'};
                   7892:     } else {
1.1084    raeburn  7893:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7894:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7895:             $inststatus = $userenvref->{'inststatus'};
                   7896:         } else {
1.1183    raeburn  7897:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7898:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7899:             $inststatus = $userenv{'inststatus'};
                   7900:         }
1.976     raeburn  7901:     }
                   7902: 
                   7903:     if ($toolstatus ne '') {
                   7904:         if ($toolstatus) {
                   7905:             $access = 1;
                   7906:         } else {
                   7907:             $access = 0;
                   7908:         }
                   7909:         return $access;
                   7910:     }
                   7911: 
1.1084    raeburn  7912:     my ($is_adv,%domdef);
                   7913:     if (ref($is_advref) eq 'HASH') {
                   7914:         $is_adv = $is_advref->{'is_adv'};
                   7915:     } else {
                   7916:         $is_adv = &is_advanced_user($udom,$uname);
                   7917:     }
                   7918:     if (ref($domdefref) eq 'HASH') {
                   7919:         %domdef = %{$domdefref};
                   7920:     } else {
                   7921:         %domdef = &get_domain_defaults($udom);
                   7922:     }
1.976     raeburn  7923:     if (ref($domdef{$tool}) eq 'HASH') {
                   7924:         if ($is_adv) {
                   7925:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7926:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7927:                     $access = 1;
                   7928:                 } else {
                   7929:                     $access = 0;
                   7930:                 }
                   7931:                 return $access;
                   7932:             }
                   7933:         }
                   7934:         if ($inststatus ne '') {
                   7935:             my ($hasaccess,$hasnoaccess);
                   7936:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7937:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7938:                     if ($domdef{$tool}{$affiliation}) {
                   7939:                         $hasaccess = 1;
                   7940:                     } else {
                   7941:                         $hasnoaccess = 1;
                   7942:                     }
                   7943:                 }
                   7944:             }
                   7945:             if ($hasaccess || $hasnoaccess) {
                   7946:                 if ($hasaccess) {
                   7947:                     $access = 1;
                   7948:                 } elsif ($hasnoaccess) {
                   7949:                     $access = 0; 
                   7950:                 }
                   7951:                 return $access;
                   7952:             }
                   7953:         } else {
                   7954:             if ($domdef{$tool}{'default'} ne '') {
                   7955:                 if ($domdef{$tool}{'default'}) {
                   7956:                     $access = 1;
                   7957:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7958:                     $access = 0;
                   7959:                 }
                   7960:                 return $access;
                   7961:             }
                   7962:         }
                   7963:     } else {
1.1177    raeburn  7964:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7965:             $access = 1;
                   7966:         } else {
                   7967:             $access = 0;
                   7968:         }
1.976     raeburn  7969:         return $access;
                   7970:     }
                   7971: }
                   7972: 
1.1050    raeburn  7973: sub is_course_owner {
                   7974:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7975:     if (($udom eq '') || ($uname eq '')) {
                   7976:         $udom = $env{'user.domain'};
                   7977:         $uname = $env{'user.name'};
                   7978:     }
                   7979:     unless (($udom eq '') || ($uname eq '')) {
                   7980:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7981:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7982:                 return 1;
                   7983:             } else {
                   7984:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7985:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7986:                     return 1;
                   7987:                 }
                   7988:             }
                   7989:         }
                   7990:     }
                   7991:     return;
                   7992: }
                   7993: 
1.976     raeburn  7994: sub is_advanced_user {
                   7995:     my ($udom,$uname) = @_;
1.1085    raeburn  7996:     if ($udom ne '' && $uname ne '') {
                   7997:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7998:             if (wantarray) {
                   7999:                 return ($env{'user.adv'},$env{'user.author'});
                   8000:             } else {
                   8001:                 return $env{'user.adv'};
                   8002:             }
1.1085    raeburn  8003:         }
                   8004:     }
1.976     raeburn  8005:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   8006:     my %allroles;
1.1128    raeburn  8007:     my ($is_adv,$is_author);
1.976     raeburn  8008:     foreach my $role (keys(%roleshash)) {
                   8009:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   8010:         my $area = '/'.$tdomain.'/'.$trest;
                   8011:         if ($sec ne '') {
                   8012:             $area .= '/'.$sec;
                   8013:         }
                   8014:         if (($area ne '') && ($trole ne '')) {
                   8015:             my $spec=$trole.'.'.$area;
                   8016:             if ($trole =~ /^cr\//) {
                   8017:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   8018:             } elsif ($trole ne 'gr') {
                   8019:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   8020:             }
1.1128    raeburn  8021:             if ($trole eq 'au') {
                   8022:                 $is_author = 1;
                   8023:             }
1.976     raeburn  8024:         }
                   8025:     }
                   8026:     foreach my $role (keys(%allroles)) {
                   8027:         last if ($is_adv);
                   8028:         foreach my $item (split(/:/,$allroles{$role})) {
                   8029:             if ($item ne '') {
                   8030:                 my ($privilege,$restrictions)=split(/&/,$item);
                   8031:                 if ($privilege eq 'adv') {
                   8032:                     $is_adv = 1;
                   8033:                     last;
                   8034:                 }
                   8035:             }
                   8036:         }
                   8037:     }
1.1128    raeburn  8038:     if (wantarray) {
                   8039:         return ($is_adv,$is_author);
                   8040:     }
1.976     raeburn  8041:     return $is_adv;
                   8042: }
1.798     raeburn  8043: 
1.1035    raeburn  8044: sub check_can_request {
1.1368    raeburn  8045:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  8046:     my $canreq = 0;
1.1368    raeburn  8047:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8048:         $uname = $env{'user.name'};
                   8049:         $udom = $env{'user.domain'};
                   8050:     }
1.1035    raeburn  8051:     my ($types,$typename) = &Apache::loncommon::course_types();
                   8052:     my @options = ('approval','validate','autolimit');
                   8053:     my $optregex = join('|',@options);
                   8054:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   8055:         foreach my $type (@{$types}) {
1.1368    raeburn  8056:             if (&usertools_access($uname,$udom,$type,undef,
                   8057:                                   'requestcourses')) {
1.1035    raeburn  8058:                 $canreq ++;
1.1036    raeburn  8059:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  8060:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  8061:                 }
1.1368    raeburn  8062:                 if ($dom eq $udom) {
1.1035    raeburn  8063:                     $can_request->{$type} = 1;
                   8064:                 }
                   8065:             }
1.1368    raeburn  8066:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   8067:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  8068:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   8069:                 if (@curr > 0) {
1.1036    raeburn  8070:                     foreach my $item (@curr) {
                   8071:                         if (ref($request_domains) eq 'HASH') {
                   8072:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   8073:                             if ($otherdom ne '') {
                   8074:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   8075:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   8076:                                         push(@{$request_domains->{$type}},$otherdom);
                   8077:                                     }
                   8078:                                 } else {
                   8079:                                     push(@{$request_domains->{$type}},$otherdom);
                   8080:                                 }
                   8081:                             }
                   8082:                         }
                   8083:                     }
1.1368    raeburn  8084:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  8085:                         $canreq ++;
1.1035    raeburn  8086:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   8087:                             $can_request->{$type} = 1;
                   8088:                         }
                   8089:                     }
                   8090:                 }
                   8091:             }
                   8092:         }
                   8093:     }
                   8094:     return $canreq;
                   8095: }
                   8096: 
1.341     www      8097: # ---------------------------------------------- Custom access rule evaluation
                   8098: 
                   8099: sub customaccess {
                   8100:     my ($priv,$uri)=@_;
1.807     albertel 8101:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      8102:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 8103:     $udom = &LONCAPA::clean_domain($udom);
                   8104:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      8105:     my $access=0;
1.800     albertel 8106:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 8107: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   8108: 	if ($type eq 'user') {
                   8109: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 8110: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 8111: 		if ($tdom) {
                   8112: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   8113: 		}
1.896     albertel 8114: 		if ($tuname) {
                   8115: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 8116: 		}
                   8117: 		$access=($effect eq 'allow');
                   8118: 		last;
                   8119: 	    }
                   8120: 	} else {
                   8121: 	    if ($role) {
                   8122: 		if ($role ne $urole) { next; }
                   8123: 	    }
                   8124: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   8125: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   8126: 		if ($tdom) {
                   8127: 		    if ($tdom ne $udom) { next; }
                   8128: 		}
                   8129: 		if ($tcrs) {
                   8130: 		    if ($tcrs ne $ucrs) { next; }
                   8131: 		}
                   8132: 		if ($tsec) {
                   8133: 		    if ($tsec ne $usec) { next; }
                   8134: 		}
                   8135: 		$access=($effect eq 'allow');
                   8136: 		last;
                   8137: 	    }
                   8138: 	    if ($realm eq '' && $role eq '') {
                   8139: 		$access=($effect eq 'allow');
                   8140: 	    }
1.402     bowersj2 8141: 	}
1.341     www      8142:     }
                   8143:     return $access;
                   8144: }
                   8145: 
1.103     harris41 8146: # ------------------------------------------------- Check for a user privilege
1.12      www      8147: 
                   8148: sub allowed {
1.1461    raeburn  8149:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705     albertel 8150:     my $ver_orguri=$uri;
1.439     www      8151:     $uri=&deversion($uri);
1.152     www      8152:     my $orguri=$uri;
1.52      www      8153:     $uri=&declutter($uri);
1.809     raeburn  8154: 
1.810     raeburn  8155:     if ($priv eq 'evb') {
                   8156: # Evade communication block restrictions for specified role in a course
                   8157:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   8158:             return $1;
                   8159:         } else {
                   8160:             return;
                   8161:         }
                   8162:     }
                   8163: 
1.620     albertel 8164:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      8165: # Free bre access to adm and meta resources
1.1436    raeburn  8166:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 8167: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   8168: 	&& ($priv eq 'bre')) {
1.14      www      8169: 	return 'F';
1.159     www      8170:     }
                   8171: 
1.545     banghart 8172: # Free bre access to user's own portfolio contents
1.714     raeburn  8173:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  8174:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  8175: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8176:         my %setters;
                   8177:         my ($startblock,$endblock) = 
                   8178:             &Apache::loncommon::blockcheck(\%setters,'port');
                   8179:         if ($startblock && $endblock) {
                   8180:             return 'B';
                   8181:         } else {
                   8182:             return 'F';
                   8183:         }
1.545     banghart 8184:     }
                   8185: 
1.762     raeburn  8186: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8187:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8188:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8189:         if (exists($env{'request.course.id'})) {
                   8190:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8191:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8192:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8193:                 my $courseprivid=$env{'request.course.id'};
                   8194:                 $courseprivid=~s/\_/\//;
                   8195:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8196:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8197:                     return $1; 
1.762     raeburn  8198:                 } else {
                   8199:                     if ($env{'request.course.sec'}) {
                   8200:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8201:                     }
                   8202:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8203:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8204:                         return $2;
                   8205:                     }
1.714     raeburn  8206:                 }
                   8207:             }
                   8208:         }
                   8209:     }
                   8210: 
1.159     www      8211: # Free bre to public access
                   8212: 
                   8213:     if ($priv eq 'bre') {
1.1362    raeburn  8214:         my $copyright;
                   8215:         unless ($uri =~ /ext\.tool/) {
                   8216:             $copyright=&metadata($uri,'copyright');
                   8217:         }
1.620     albertel 8218: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8219:            return 'F'; 
                   8220:         }
1.238     www      8221:         if ($copyright eq 'priv') {
                   8222:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8223: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8224: 		return '';
                   8225:             }
                   8226:         }
                   8227:         if ($copyright eq 'domain') {
                   8228:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8229: 	    unless (($env{'user.domain'} eq $1) ||
                   8230:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8231: 		return '';
                   8232:             }
1.262     matthew  8233:         }
1.620     albertel 8234:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8235:             # Library role, so allow browsing of resources in this domain.
                   8236:             return 'F';
1.238     www      8237:         }
1.341     www      8238:         if ($copyright eq 'custom') {
                   8239: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8240:         }
1.14      www      8241:     }
1.264     matthew  8242:     # Domain coordinator is trying to create a course
1.620     albertel 8243:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8244:         # uri is the requested domain in this case.
                   8245:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8246:         # a role of dc for the domain in question.
1.620     albertel 8247:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8248:     }
1.29      www      8249: 
1.52      www      8250:     my $thisallowed='';
                   8251:     my $statecond=0;
                   8252:     my $courseprivid='';
                   8253: 
1.1039    raeburn  8254:     my $ownaccess;
1.1043    raeburn  8255:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8256:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8257:         if ($uri eq '') {
                   8258:             $ownaccess = 1;
                   8259:         } else {
                   8260:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8261:                 my $udom = $env{'user.domain'};
                   8262:                 my $uname = $env{'user.name'};
                   8263:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8264:                     $ownaccess = 1;
1.1040    raeburn  8265:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8266:                     unless ($uri =~ m{\.\./}) {
                   8267:                         $ownaccess = 1;
                   8268:                     }
                   8269:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8270:                     my $now = time;
                   8271:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8272:                         my $adom = $1;
                   8273:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8274:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1452    raeburn  8275:                                 my ($start,$end) = split(/\./,$env{$key});
                   8276:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  8277:                                     $ownaccess = 1;
                   8278:                                     last;
                   8279:                                 }
                   8280:                             }
                   8281:                         }
                   8282:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8283:                         my $adom = $1;
                   8284:                         my $aname = $2;
1.1042    raeburn  8285:                         foreach my $role ('ca','aa') { 
                   8286:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8287:                                 my ($start,$end) =
1.1452    raeburn  8288:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8289:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8290:                                     $ownaccess = 1;
                   8291:                                     last;
                   8292:                                 }
1.1039    raeburn  8293:                             }
                   8294:                         }
                   8295:                     }
                   8296:                 }
                   8297:             }
                   8298:         }
                   8299:     }
                   8300: 
1.52      www      8301: # Course
                   8302: 
1.620     albertel 8303:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8304:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8305:             $thisallowed.=$1;
                   8306:         }
1.52      www      8307:     }
1.29      www      8308: 
1.52      www      8309: # Domain
                   8310: 
1.620     albertel 8311:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8312:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8313:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8314:             $thisallowed.=$1;
                   8315:         }
1.12      www      8316:     }
1.52      www      8317: 
1.1141    raeburn  8318: # User who is not author or co-author might still be able to edit
                   8319: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8320:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8321:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8322:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8323:             $thisallowed.=$1;
                   8324:         }
                   8325:     }
                   8326: 
1.52      www      8327: # Course: uri itself is a course
1.66      www      8328:     my $courseuri=$uri;
                   8329:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8330:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8331: 
1.620     albertel 8332:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8333:        =~/\Q$priv\E\&([^\:]*)/) {
1.1409    raeburn  8334:         if ($priv eq 'mip') {
                   8335:             my $rem = $1;
                   8336:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8337:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8338:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8339:                 if ($cdom ne '') {
1.1410    raeburn  8340:                     my %passwdconf = &get_passwdconf($cdom);
                   8341:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8342:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8343:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8344:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8345:                                 unless (@inststatuses) {
                   8346:                                     @inststatuses = ('default');
                   8347:                                 }
                   8348:                                 foreach my $status (@inststatuses) {
                   8349:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8350:                                         $thisallowed.=$rem;
                   8351:                                     }
                   8352:                                 }
                   8353:                             }
                   8354:                         }
1.1409    raeburn  8355:                     }
                   8356:                 }
                   8357:             }
                   8358:         } else {
                   8359:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8360:                 $thisallowed.=$1;
                   8361:             }
1.1039    raeburn  8362:         }
1.12      www      8363:     }
1.29      www      8364: 
1.665     albertel 8365: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8366: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8367:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8368: 	$thisallowed='';
1.671     raeburn  8369:         my ($match)=&is_on_map($uri);
                   8370:         if ($match) {
                   8371:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8372:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  8373:                 my $value = $1;
1.1461    raeburn  8374:                 my $deeplinkblock;
                   8375:                 unless ($nodeeplinkcheck) {
                   8376:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8377:                 }
1.1402    raeburn  8378:                 if ($deeplinkblock) {
                   8379:                     $thisallowed='D';
                   8380:                 } elsif ($noblockcheck) {
1.1281    raeburn  8381:                     $thisallowed.=$value;
1.1162    raeburn  8382:                 } else {
1.1424    raeburn  8383:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281    raeburn  8384:                     if (@blockers > 0) {
                   8385:                         $thisallowed = 'B';
                   8386:                     } else {
                   8387:                         $thisallowed.=$value;
                   8388:                     }
1.1162    raeburn  8389:                 }
1.671     raeburn  8390:             }
                   8391:         } else {
1.705     albertel 8392:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8393:             if ($refuri) {
                   8394:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8395:                     $thisallowed='F';
1.671     raeburn  8396:                 } else {
                   8397:                     $refuri=&declutter($refuri);
                   8398:                     my ($match) = &is_on_map($refuri);
                   8399:                     if ($match) {
1.1461    raeburn  8400:                         my $deeplinkblock;
                   8401:                         unless ($nodeeplinkcheck) {
                   8402:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8403:                         }
1.1402    raeburn  8404:                         if ($deeplinkblock) {
                   8405:                             $thisallowed='D';
                   8406:                         } elsif ($noblockcheck) {
1.1281    raeburn  8407:                             $thisallowed='F';
1.1162    raeburn  8408:                         } else {
1.1426    raeburn  8409:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281    raeburn  8410:                             if (@blockers > 0) {
                   8411:                                 $thisallowed = 'B';
                   8412:                             } else {
                   8413:                                 $thisallowed='F';
                   8414:                             }
1.1162    raeburn  8415:                         }
1.671     raeburn  8416:                     }
1.669     raeburn  8417:                 }
1.671     raeburn  8418:             }
                   8419:         }
1.314     www      8420:     }
1.492     albertel 8421: 
1.766     albertel 8422:     if ($priv eq 'bre'
                   8423: 	&& $thisallowed ne 'F' 
                   8424: 	&& $thisallowed ne '2'
                   8425: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  8426: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8427:     }
1.1250    raeburn  8428: 
1.52      www      8429: # Full access at system, domain or course-wide level? Exit.
1.29      www      8430:     if ($thisallowed=~/F/) {
                   8431: 	return 'F';
                   8432:     }
                   8433: 
1.52      www      8434: # If this is generating or modifying users, exit with special codes
1.29      www      8435: 
1.643     www      8436:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8437: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8438: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8439: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8440: 	    unless ($auname) { return $thisallowed; }
                   8441: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8442: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8443: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8444: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8445: 	}
1.52      www      8446: 	return $thisallowed;
                   8447:     }
                   8448: #
1.103     harris41 8449: # Gathered so far: system, domain and course wide privileges
1.52      www      8450: #
                   8451: # Course: See if uri or referer is an individual resource that is part of 
                   8452: # the course
                   8453: 
1.620     albertel 8454:     if ($env{'request.course.id'}) {
1.232     www      8455: 
1.1409    raeburn  8456: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8457: 
                   8458:         if ($priv eq 'mip') {
                   8459:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8460:                 return $thisallowed;
                   8461:             } else {
                   8462:                 return '';
                   8463:             }
                   8464:         }
                   8465: 
1.620     albertel 8466:        $courseprivid=$env{'request.course.id'};
                   8467:        if ($env{'request.course.sec'}) {
                   8468:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8469:        }
                   8470:        $courseprivid=~s/\_/\//;
                   8471:        my $checkreferer=1;
1.232     www      8472:        my ($match,$cond)=&is_on_map($uri);
                   8473:        if ($match) {
                   8474:            $statecond=$cond;
1.620     albertel 8475:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8476:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8477:                my $value = $1;
                   8478:                if ($priv eq 'bre') {
1.1461    raeburn  8479:                    my $deeplinkblock;
                   8480:                    unless ($nodeeplinkcheck) {
                   8481:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8482:                    }
1.1458    raeburn  8483:                    if ($deeplinkblock) {
                   8484:                        $thisallowed = 'D';
                   8485:                    } elsif ($noblockcheck) {
1.1281    raeburn  8486:                        $thisallowed.=$value;
1.1162    raeburn  8487:                    } else {
1.1424    raeburn  8488:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281    raeburn  8489:                        if (@blockers > 0) {
                   8490:                            $thisallowed = 'B';
                   8491:                        } else {
                   8492:                            $thisallowed.=$value;
                   8493:                        }
1.1162    raeburn  8494:                    }
                   8495:                } else {
                   8496:                    $thisallowed.=$value;
                   8497:                }
1.52      www      8498:                $checkreferer=0;
                   8499:            }
1.29      www      8500:        }
1.1424    raeburn  8501: 
1.148     www      8502:        if ($checkreferer) {
1.620     albertel 8503: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8504:             unless ($refuri) {
1.800     albertel 8505:                 foreach my $key (keys(%env)) {
                   8506: 		    if ($key=~/^httpref\..*\*/) {
                   8507: 			my $pattern=$key;
1.156     www      8508:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8509:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8510:                         $pattern=~s/\//\\\//g;
1.152     www      8511:                         if ($orguri=~/$pattern/) {
1.800     albertel 8512: 			    $refuri=$env{$key};
1.148     www      8513:                         }
                   8514:                     }
1.191     harris41 8515:                 }
1.148     www      8516:             }
1.232     www      8517: 
1.148     www      8518:          if ($refuri) { 
1.152     www      8519: 	  $refuri=&declutter($refuri);
1.232     www      8520:           my ($match,$cond)=&is_on_map($refuri);
                   8521:             if ($match) {
                   8522:               my $refstatecond=$cond;
1.620     albertel 8523:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8524:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8525:                   my $value = $1;
                   8526:                   if ($priv eq 'bre') {
1.1461    raeburn  8527:                       my $deeplinkblock;
                   8528:                       unless ($nodeeplinkcheck) {
                   8529:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8530:                       }
1.1402    raeburn  8531:                       if ($deeplinkblock) {
                   8532:                           $thisallowed = 'D';
                   8533:                       } elsif ($noblockcheck) {
1.1281    raeburn  8534:                           $thisallowed.=$value;
1.1162    raeburn  8535:                       } else {
1.1426    raeburn  8536:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281    raeburn  8537:                           if (@blockers > 0) {
                   8538:                               $thisallowed = 'B';
                   8539:                           } else {
                   8540:                               $thisallowed.=$value;
                   8541:                           }
1.1162    raeburn  8542:                       }
                   8543:                   } else {
                   8544:                       $thisallowed.=$value;
                   8545:                   }
1.53      www      8546:                   $uri=$refuri;
                   8547:                   $statecond=$refstatecond;
1.52      www      8548:               }
                   8549:           }
1.148     www      8550:         }
1.29      www      8551:        }
1.52      www      8552:    }
1.29      www      8553: 
1.52      www      8554: #
1.103     harris41 8555: # Gathered now: all privileges that could apply, and condition number
1.52      www      8556: # 
                   8557: #
                   8558: # Full or no access?
                   8559: #
1.29      www      8560: 
1.52      www      8561:     if ($thisallowed=~/F/) {
                   8562: 	return 'F';
                   8563:     }
1.29      www      8564: 
1.52      www      8565:     unless ($thisallowed) {
                   8566:         return '';
                   8567:     }
1.29      www      8568: 
1.52      www      8569: # Restrictions exist, deal with them
                   8570: #
                   8571: #   C:according to course preferences
                   8572: #   R:according to resource settings
                   8573: #   L:unless locked
                   8574: #   X:according to user session state
                   8575: #
                   8576: 
                   8577: # Possibly locked functionality, check all courses
1.1454    raeburn  8578: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      8579: # Locks might take effect only after 10 minutes cache expiration for other
1.1454    raeburn  8580: # courses, and 2 minutes for current course, in which user has st or ta role
                   8581: # which is neither expired nor a future role (unless current course).
1.52      www      8582: 
1.1454    raeburn  8583:     my ($needlockcheck,$now,$crsonly);
1.52      www      8584:     if ($thisallowed=~/L/) {
1.1454    raeburn  8585:         $now = time;
                   8586:         if ($priv eq 'bre') {
                   8587:             if ($uri ne '') {
                   8588:                 if ($orguri =~ m{^/+res/}) {
                   8589:                     if ($uri =~ m{^lib/templates/}) {
                   8590:                         if ($env{'request.course.id'}) {
                   8591:                             $crsonly = 1;
                   8592:                             $needlockcheck = 1;
                   8593:                         }
                   8594:                     } else {
                   8595:                         $needlockcheck = 1;
                   8596:                     }
                   8597:                 } elsif ($env{'request.course.id'}) {
                   8598:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   8599:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   8600:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   8601:                         $crsonly = 1;
                   8602:                     }
                   8603:                     $needlockcheck = 1;
                   8604:                 }
                   8605:             }
                   8606:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   8607:             $needlockcheck = 1;
                   8608:         }
                   8609:     }
                   8610:     if ($needlockcheck) {
1.1453    raeburn  8611:         foreach my $envkey (keys(%env)) {
1.54      www      8612:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8613:                my $courseid=$2;
                   8614:                my $roleid=$1.'.'.$2;
1.92      www      8615:                $courseid=~s/^\///;
1.1453    raeburn  8616:                unless ($env{'request.role'} eq $roleid) {
                   8617:                    my ($start,$end) = split(/\./,$env{$envkey});
                   8618:                    next unless (($now >= $start) && (!$end || $end > $now));
                   8619:                }
1.54      www      8620:                my $expiretime=600;
1.620     albertel 8621:                if ($env{'request.role'} eq $roleid) {
1.54      www      8622: 		  $expiretime=120;
                   8623:                }
                   8624: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8625:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8626:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8627: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8628:                }
1.620     albertel 8629:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8630:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8631: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8632:                        &log($env{'user.domain'},$env{'user.name'},
                   8633:                             $env{'user.home'},
1.57      www      8634:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8635:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8636:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8637: 		       return '';
                   8638:                    }
                   8639:                }
1.620     albertel 8640:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8641:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1455    raeburn  8642: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 8643:                        &log($env{'user.domain'},$env{'user.name'},
                   8644:                             $env{'user.home'},
1.57      www      8645:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8646:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8647:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8648: 		       return '';
                   8649:                    }
                   8650:                }
                   8651: 	   }
1.29      www      8652:        }
1.52      www      8653:     }
1.1424    raeburn  8654: 
1.52      www      8655: #
                   8656: # Rest of the restrictions depend on selected course
                   8657: #
                   8658: 
1.620     albertel 8659:     unless ($env{'request.course.id'}) {
1.766     albertel 8660: 	if ($thisallowed eq 'A') {
                   8661: 	    return 'A';
1.814     raeburn  8662:         } elsif ($thisallowed eq 'B') {
                   8663:             return 'B';
1.766     albertel 8664: 	} else {
                   8665: 	    return '1';
                   8666: 	}
1.52      www      8667:     }
1.29      www      8668: 
1.52      www      8669: #
                   8670: # Now user is definitely in a course
                   8671: #
1.53      www      8672: 
                   8673: 
                   8674: # Course preferences
                   8675: 
                   8676:    if ($thisallowed=~/C/) {
1.620     albertel 8677:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8678:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8679:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8680: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  8681: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8682: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8683: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8684: 			$env{'request.course.id'});
                   8685: 	   }
1.237     www      8686:            return '';
                   8687:        }
                   8688: 
1.620     albertel 8689:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8690: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  8691: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8692: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8693: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8694: 			$env{'request.course.id'});
                   8695: 	   }
1.54      www      8696:            return '';
                   8697:        }
1.53      www      8698:    }
                   8699: 
                   8700: # Resource preferences
                   8701: 
                   8702:    if ($thisallowed=~/R/) {
1.620     albertel 8703:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8704:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8705: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8706: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8707: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8708: 	   }
                   8709: 	   return '';
1.54      www      8710:        }
1.53      www      8711:    }
1.30      www      8712: 
1.1461    raeburn  8713: # Restricted for deeplinked session?
                   8714: 
                   8715:     if ($env{'request.deeplink.login'}) {
                   8716:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
                   8717:             if (!$symb) { $symb=&symbread($uri,1); }
                   8718:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
                   8719:                 return '';
                   8720:             }
                   8721:         }
                   8722:     }
                   8723: 
1.246     www      8724: # Restricted by state or randomout?
1.30      www      8725: 
1.52      www      8726:    if ($thisallowed=~/X/) {
1.620     albertel 8727:       if ($env{'acc.randomout'}) {
1.579     albertel 8728: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8729:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8730:             return ''; 
                   8731:          }
1.247     www      8732:       }
                   8733:       if (&condval($statecond)) {
1.52      www      8734: 	 return '2';
                   8735:       } else {
                   8736:          return '';
                   8737:       }
                   8738:    }
1.30      www      8739: 
1.766     albertel 8740:     if ($thisallowed eq 'A') {
                   8741: 	return 'A';
1.814     raeburn  8742:     } elsif ($thisallowed eq 'B') {
                   8743:         return 'B';
1.1402    raeburn  8744:     } elsif ($thisallowed eq 'D') {
                   8745:         return 'D';
1.766     albertel 8746:     }
1.52      www      8747:    return 'F';
1.232     www      8748: }
1.1162    raeburn  8749: 
1.1192    raeburn  8750: # ------------------------------------------- Check construction space access
                   8751: 
                   8752: sub constructaccess {
                   8753:     my ($url,$setpriv)=@_;
                   8754: 
                   8755: # We do not allow editing of previous versions of files
                   8756:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8757: 
                   8758: # Get username and domain from URL
                   8759:     my ($ownername,$ownerdomain,$ownerhome);
                   8760: 
                   8761:     ($ownerdomain,$ownername) =
1.1325    raeburn  8762:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  8763: 
                   8764: # The URL does not really point to any authorspace, forget it
                   8765:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8766: 
                   8767: # Now we need to see if the user has access to the authorspace of
                   8768: # $ownername at $ownerdomain
                   8769: 
                   8770:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8771: # Real author for this?
                   8772:        $ownerhome = $env{'user.home'};
                   8773:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8774:           return ($ownername,$ownerdomain,$ownerhome);
                   8775:        }
                   8776:     } else {
                   8777: # Co-author for this?
                   8778:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8779:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8780:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8781:             return ($ownername,$ownerdomain,$ownerhome);
                   8782:         }
1.1312    raeburn  8783:         if ($env{'request.course.id'}) {
                   8784:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   8785:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   8786:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   8787:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   8788:                     return ($ownername,$ownerdomain,$ownerhome);
                   8789:                 }
                   8790:             }
                   8791:         }
1.1192    raeburn  8792:     }
                   8793: 
                   8794: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8795: # we might as well leave
                   8796:    unless ($setpriv) { return ''; }
                   8797: 
                   8798: # Backdoor access?
                   8799:     my $allowed=&allowed('eco',$ownerdomain);
                   8800: # Nope
                   8801:     unless ($allowed) { return ''; }
                   8802: # Looks like we may have access, but could be locked by the owner of the construction space
                   8803:     if ($allowed eq 'U') {
                   8804:         my %blocked=&get('environment',['domcoord.author'],
                   8805:                          $ownerdomain,$ownername);
                   8806: # Is blocked by owner
                   8807:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8808:     }
                   8809:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8810: # Grant temporary access
                   8811:         my $then=$env{'user.login.time'};
1.1209    raeburn  8812:         my $update=$env{'user.update.time'};
1.1192    raeburn  8813:         if (!$update) { $update = $then; }
                   8814:         my $refresh=$env{'user.refresh.time'};
                   8815:         if (!$refresh) { $refresh = $update; }
                   8816:         my $now = time;
                   8817:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8818:                            $now,'ca','constructaccess');
                   8819:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8820:         return($ownername,$ownerdomain,$ownerhome);
                   8821:     }
                   8822: # No business here
                   8823:     return '';
                   8824: }
                   8825: 
1.1282    raeburn  8826: # ----------------------------------------------------------- Content Blocking
                   8827: 
                   8828: {
                   8829: # Caches for faster Course Contents display where content blocking
                   8830: # is in operation (i.e., interval param set) for timed quiz.
                   8831: #
                   8832: # User for whom data are being temporarily cached.
                   8833: my $cacheduser='';
1.1424    raeburn  8834: # Course for which data are being temporarily cached.
                   8835: my $cachedcid='';
1.1282    raeburn  8836: # Cached blockers for this user (a hash of blocking items). 
                   8837: my %cachedblockers=();
                   8838: # When the data were last cached.
                   8839: my $cachedlast='';
                   8840: 
                   8841: sub load_all_blockers {
1.1427    raeburn  8842:     my ($uname,$udom)=@_;
1.1282    raeburn  8843:     if (($uname ne '') && ($udom ne '')) { 
                   8844:         if (($cacheduser eq $uname.':'.$udom) &&
1.1424    raeburn  8845:             ($cachedcid eq $env{'request.course.id'}) &&
1.1427    raeburn  8846:             (abs($cachedlast-time)<5)) {
1.1282    raeburn  8847:             return;
                   8848:         }
                   8849:     }
                   8850:     $cachedlast=time;
                   8851:     $cacheduser=$uname.':'.$udom;
1.1424    raeburn  8852:     $cachedcid=$env{'request.course.id'};
1.1427    raeburn  8853:     %cachedblockers = &get_commblock_resources();
1.1424    raeburn  8854:     return;
1.1282    raeburn  8855: }
                   8856: 
1.1162    raeburn  8857: sub get_comm_blocks {
                   8858:     my ($cdom,$cnum) = @_;
                   8859:     if ($cdom eq '' || $cnum eq '') {
                   8860:         return unless ($env{'request.course.id'});
                   8861:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8862:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8863:     }
                   8864:     my %commblocks;
                   8865:     my $hashid=$cdom.'_'.$cnum;
                   8866:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8867:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8868:         %commblocks = %{$blocksref};
                   8869:     } else {
                   8870:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8871:         my $cachetime = 600;
                   8872:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8873:     }
                   8874:     return %commblocks;
                   8875: }
                   8876: 
1.1282    raeburn  8877: sub get_commblock_resources {
                   8878:     my ($blocks) = @_;
                   8879:     my %blockers = ();
                   8880:     return %blockers unless ($env{'request.course.id'});
1.1470    raeburn  8881:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8882:     if ($env{'request.course.sec'}) {
                   8883:         $courseurl .= '/'.$env{'request.course.sec'};
                   8884:     }
                   8885:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  8886:     my %commblocks;
                   8887:     if (ref($blocks) eq 'HASH') {
                   8888:         %commblocks = %{$blocks};
                   8889:     } else {
                   8890:         %commblocks = &get_comm_blocks();
                   8891:     }
1.1282    raeburn  8892:     return %blockers unless (keys(%commblocks) > 0); 
                   8893:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8894:     return %blockers unless (ref($navmap));
1.1162    raeburn  8895:     my $now = time;
                   8896:     foreach my $block (keys(%commblocks)) {
                   8897:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8898:             my ($start,$end) = ($1,$2);
                   8899:             if ($start <= $now && $end >= $now) {
                   8900:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8901:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8902:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8903:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8904:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8905:                             }
                   8906:                         }
                   8907:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8908:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8909:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8910:                             }
                   8911:                         }
                   8912:                     }
                   8913:                 }
                   8914:             }
                   8915:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8916:             my $item = $1;
                   8917:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8918:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1471    raeburn  8919:                     my (@interval,$mapname);
1.1282    raeburn  8920:                     my $type = 'map';
                   8921:                     if ($item eq 'course') {
                   8922:                         $type = 'course';
                   8923:                         @interval=&EXT("resource.0.interval");
                   8924:                     } else {
                   8925:                         if ($item =~ /___\d+___/) {
                   8926:                             $type = 'resource';
                   8927:                             @interval=&EXT("resource.0.interval",$item);
1.1162    raeburn  8928:                         } else {
1.1471    raeburn  8929:                             $mapname = &deversion($item);
                   8930:                             if (ref($navmap)) {
                   8931:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
                   8932:                                 @interval = ($timelimit,'map');
1.1162    raeburn  8933:                             }
                   8934:                         }
1.1282    raeburn  8935:                     }
1.1310    raeburn  8936:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8937:                         my $timelimit = $1; 
1.1282    raeburn  8938:                         my $first_access;
                   8939:                         if ($type eq 'resource') {
                   8940:                             $first_access=&get_first_access($interval[1],$item);
                   8941:                         } elsif ($type eq 'map') {
                   8942:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8943:                         } else {
                   8944:                             $first_access=&get_first_access($interval[1]);
                   8945:                         }
                   8946:                         if ($first_access) {
1.1292    raeburn  8947:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8948:                             if ($timesup > $now) {
                   8949:                                 my $activeblock;
1.1471    raeburn  8950:                                 if ($type eq 'resource') {
                   8951:                                     if (ref($navmap)) {
                   8952:                                         my $res = $navmap->getBySymb($item);
                   8953:                                         if ($res->answerable()) {
                   8954:                                             $activeblock = 1;
                   8955:                                         }
                   8956:                                     }
                   8957:                                 } elsif ($type eq 'map') {
                   8958:                                     my $mapsymb = &symbread($mapname,1);
                   8959:                                     if (($mapsymb) && (ref($navmap))) {
                   8960:                                         my $mapres = $navmap->getBySymb($mapsymb);
                   8961:                                         if (ref($mapres)) {
                   8962:                                             my $first = $mapres->map_start();
                   8963:                                             my $finish = $mapres->map_finish();
                   8964:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   8965:                                             if (ref($it)) {
                   8966:                                                 my $res;
                   8967:                                                 while ($res = $it->next(undef,1)) {
                   8968:                                                     next unless (ref($res));
                   8969:                                                     my $symb = $res->symb();
                   8970:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
                   8971:                                                     @interval=&EXT("resource.0.interval",$symb);
                   8972:                                                     if ($interval[1] eq 'map') {
                   8973:                                                         if ($res->answerable()) {
                   8974:                                                             $activeblock = 1;
                   8975:                                                             last;
                   8976:                                                         }
                   8977:                                                     }
                   8978:                                                 }
                   8979:                                             }
                   8980:                                         }
1.1282    raeburn  8981:                                     }
                   8982:                                 }
                   8983:                                 if ($activeblock) {
                   8984:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8985:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8986:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8987:                                          }
                   8988:                                     }
                   8989:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8990:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8991:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8992:                                         }
1.1162    raeburn  8993:                                     }
                   8994:                                 }
                   8995:                             }
                   8996:                         }
                   8997:                     }
                   8998:                 }
                   8999:             }
                   9000:         }
                   9001:     }
1.1282    raeburn  9002:     return %blockers;
1.1162    raeburn  9003: }
                   9004: 
1.1282    raeburn  9005: sub has_comm_blocking {
1.1427    raeburn  9006:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1282    raeburn  9007:     my @blockers;
                   9008:     return unless ($env{'request.course.id'});
                   9009:     return unless ($priv eq 'bre');
                   9010:     return if ($env{'request.state'} eq 'construct');
1.1470    raeburn  9011:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   9012:     if ($env{'request.course.sec'}) {
                   9013:         $courseurl .= '/'.$env{'request.course.sec'};
                   9014:     }
                   9015:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1427    raeburn  9016:     my %blockinfo;
                   9017:     if (ref($blocks) eq 'HASH') {
                   9018:         %blockinfo = &get_commblock_resources($blocks);
                   9019:     } else {
                   9020:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   9021:         %blockinfo = %cachedblockers;
                   9022:     }
                   9023:     return unless (keys(%blockinfo) > 0);
1.1282    raeburn  9024:     my (%possibles,@symbs);
                   9025:     if (!$symb) {
1.1427    raeburn  9026:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  9027:     }
1.1282    raeburn  9028:     if ($symb) {
                   9029:         @symbs = ($symb);
                   9030:     } elsif (keys(%possibles)) { 
                   9031:         @symbs = keys(%possibles);
                   9032:     }
                   9033:     my $noblock;
                   9034:     foreach my $symb (@symbs) {
                   9035:         last if ($noblock);
                   9036:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1427    raeburn  9037:         foreach my $block (keys(%blockinfo)) {
1.1282    raeburn  9038:             if ($block =~ /^firstaccess____(.+)$/) {
                   9039:                 my $item = $1;
1.1424    raeburn  9040:                 unless ($blocked) {
                   9041:                     if (($item eq $map) || ($item eq $symb)) {
                   9042:                         $noblock = 1;
                   9043:                         last;
                   9044:                     }
1.1282    raeburn  9045:                 }
                   9046:             }
1.1427    raeburn  9047:             if (ref($blockinfo{$block}) eq 'HASH') {
                   9048:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   9049:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1282    raeburn  9050:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9051:                             push(@blockers,$block);
                   9052:                         }
                   9053:                     }
                   9054:                 }
1.1427    raeburn  9055:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   9056:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1424    raeburn  9057:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9058:                             push(@blockers,$block);
                   9059:                         }
1.1282    raeburn  9060:                     }
                   9061:                 }
1.1162    raeburn  9062:             }
                   9063:         }
                   9064:     }
1.1424    raeburn  9065:     unless ($noblock) { 
                   9066:         return @blockers;
                   9067:     }
                   9068:     return;
1.1282    raeburn  9069: }
1.1162    raeburn  9070: }
                   9071: 
1.1402    raeburn  9072: sub deeplink_check {
                   9073:     my ($priv,$symb,$uri) = @_;
                   9074:     return unless ($env{'request.course.id'});
                   9075:     return unless ($priv eq 'bre');
                   9076:     return if ($env{'request.state'} eq 'construct');
                   9077:     return if ($env{'request.role.adv'});
                   9078:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9079:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9080:     my (%possibles,@symbs);
                   9081:     if (!$symb) {
                   9082:         $symb = &symbread($uri,1,1,1,\%possibles);
                   9083:     }
                   9084:     if ($symb) {
                   9085:         @symbs = ($symb);
                   9086:     } elsif (keys(%possibles)) {
                   9087:         @symbs = keys(%possibles);
                   9088:     }
                   9089: 
1.1461    raeburn  9090:     my ($deeplink_symb,$allow);
                   9091:     if ($env{'request.deeplink.login'}) {
                   9092:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
1.1402    raeburn  9093:     }
                   9094:     foreach my $symb (@symbs) {
                   9095:         last if ($allow);
                   9096:         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   9097:         if ($deeplink eq '') {
                   9098:             $allow = 1;
                   9099:         } else {
1.1463    raeburn  9100:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
                   9101:             if ($state ne 'only') {
1.1402    raeburn  9102:                 $allow = 1;
1.1463    raeburn  9103:             } else {
                   9104:                 my $check_deeplink_entry;
                   9105:                 if ($protect ne 'none') {
                   9106:                     my ($acctype,$item) = split(/:/,$protect);
                   9107:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
                   9108:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
                   9109:                             $check_deeplink_entry = 1
                   9110:                         }
                   9111:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
                   9112:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
                   9113:                             $check_deeplink_entry = 1;
                   9114:                         }
                   9115:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   9116:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   9117:                             $check_deeplink_entry = 1;
                   9118:                         }
                   9119:                     }
                   9120:                 }
                   9121:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
1.1402    raeburn  9122:                     if ($scope eq 'res') {
1.1461    raeburn  9123:                         if ($symb eq $deeplink_symb) {
1.1402    raeburn  9124:                             $allow = 1;
                   9125:                         }
1.1459    raeburn  9126:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
1.1463    raeburn  9127:                         my ($map_from_symb,$map_from_login);
1.1461    raeburn  9128:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
                   9129:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9130:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
                   9131:                         } else {
                   9132:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
                   9133:                         }
1.1459    raeburn  9134:                         if (($map_from_symb) && ($map_from_login)) {
                   9135:                             if ($map_from_symb eq $map_from_login) {
                   9136:                                 $allow = 1;
                   9137:                             } elsif ($scope eq 'rec') {
                   9138:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
                   9139:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
                   9140:                                     $allow = 1;
                   9141:                                 }
                   9142:                             }
                   9143:                         }
1.1402    raeburn  9144:                     }
                   9145:                 }
                   9146:             }
                   9147:         }
                   9148:     }
                   9149:     return if ($allow);
                   9150:     return 1;
                   9151: }
                   9152: 
1.1282    raeburn  9153: # -------------------------------- Deversion and split uri into path an filename   
                   9154: 
1.1133    foxr     9155: #
1.1282    raeburn  9156: #   Removes the version from a URI and
1.1133    foxr     9157: #   splits it in to its filename and path to the filename.
                   9158: #   Seems like File::Basename could have done this more clearly.
                   9159: #   Parameters:
                   9160: #      $uri   - input URI
                   9161: #   Returns:
                   9162: #     Two element list consisting of 
                   9163: #     $pathname  - the URI up to and excluding the trailing /
                   9164: #     $filename  - The part of the URI following the last /
                   9165: #  NOTE:
                   9166: #    Another realization of this is simply:
                   9167: #    use File::Basename;
                   9168: #    ...
                   9169: #    $uri = shift;
                   9170: #    $filename = basename($uri);
                   9171: #    $path     = dirname($uri);
                   9172: #    return ($filename, $path);
                   9173: #
                   9174: #     The implementation below is probably faster however.
                   9175: #
1.710     albertel 9176: sub split_uri_for_cond {
                   9177:     my $uri=&deversion(&declutter(shift));
                   9178:     my @uriparts=split(/\//,$uri);
                   9179:     my $filename=pop(@uriparts);
                   9180:     my $pathname=join('/',@uriparts);
                   9181:     return ($pathname,$filename);
                   9182: }
1.232     www      9183: # --------------------------------------------------- Is a resource on the map?
                   9184: 
                   9185: sub is_on_map {
1.710     albertel 9186:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 9187:     #Trying to find the conditional for the file
1.620     albertel 9188:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 9189: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      9190:     if ($match) {
1.289     bowersj2 9191: 	return (1,$1);
                   9192:     } else {
1.434     www      9193: 	return (0,0);
1.289     bowersj2 9194:     }
1.12      www      9195: }
                   9196: 
1.427     www      9197: # --------------------------------------------------------- Get symb from alias
                   9198: 
                   9199: sub get_symb_from_alias {
                   9200:     my $symb=shift;
                   9201:     my ($map,$resid,$url)=&decode_symb($symb);
                   9202: # Already is a symb
                   9203:     if ($url) { return $symb; }
                   9204: # Must be an alias
                   9205:     my $aliassymb='';
                   9206:     my %bighash;
1.620     albertel 9207:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      9208:                             &GDBM_READER(),0640)) {
                   9209:         my $rid=$bighash{'mapalias_'.$symb};
                   9210: 	if ($rid) {
                   9211: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 9212: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   9213: 				    $resid,$bighash{'src_'.$rid});
1.427     www      9214: 	}
                   9215:         untie %bighash;
                   9216:     }
                   9217:     return $aliassymb;
                   9218: }
                   9219: 
1.12      www      9220: # ----------------------------------------------------------------- Define Role
                   9221: 
                   9222: sub definerole {
                   9223:   if (allowed('mcr','/')) {
1.1326    raeburn  9224:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9225:     foreach my $role (split(':',$sysrole)) {
                   9226: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9227:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9228:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9229: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9230:                return "refused:s:$crole&$cqual"; 
                   9231:             }
                   9232:         }
1.191     harris41 9233:     }
1.800     albertel 9234:     foreach my $role (split(':',$domrole)) {
                   9235: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9236:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9237:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9238: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9239:                return "refused:d:$crole&$cqual"; 
                   9240:             }
                   9241:         }
1.191     harris41 9242:     }
1.800     albertel 9243:     foreach my $role (split(':',$courole)) {
                   9244: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9245:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9246:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9247: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9248:                return "refused:c:$crole&$cqual"; 
                   9249:             }
                   9250:         }
1.191     harris41 9251:     }
1.1326    raeburn  9252:     my $uhome;
                   9253:     if (($uname ne '') && ($udom ne '')) {
                   9254:         $uhome = &homeserver($uname,$udom);
                   9255:         return $uhome if ($uhome eq 'no_host');
                   9256:     } else {
                   9257:         $uname = $env{'user.name'};
                   9258:         $udom = $env{'user.domain'};
                   9259:         $uhome = $env{'user.home'};
                   9260:     }
1.620     albertel 9261:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  9262:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9263:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  9264:     return reply($command,$uhome);
1.12      www      9265:   } else {
                   9266:     return 'refused';
                   9267:   }
1.105     harris41 9268: }
                   9269: 
                   9270: # ---------------- Make a metadata query against the network of library servers
                   9271: 
                   9272: sub metadata_query {
1.1237    raeburn  9273:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9274:     my %rhash;
1.845     albertel 9275:     my %libserv = &all_library();
1.244     matthew  9276:     my @server_list = (defined($server_array) ? @$server_array
                   9277:                                               : keys(%libserv) );
                   9278:     for my $server (@server_list) {
1.1237    raeburn  9279:         my $domains = ''; 
                   9280:         if (ref($domains_hash) eq 'HASH') {
                   9281:             $domains = $domains_hash->{$server}; 
                   9282:         }
1.118     harris41 9283: 	unless ($custom or $customshow) {
1.1237    raeburn  9284: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9285: 	    $rhash{$server}=$reply;
                   9286: 	}
                   9287: 	else {
                   9288: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  9289: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9290: 			     $server);
                   9291: 	    $rhash{$server}=$reply;
                   9292: 	}
1.112     harris41 9293:     }
1.118     harris41 9294:     return \%rhash;
1.240     www      9295: }
                   9296: 
                   9297: # ----------------------------------------- Send log queries and wait for reply
                   9298: 
                   9299: sub log_query {
                   9300:     my ($uname,$udom,$query,%filters)=@_;
                   9301:     my $uhome=&homeserver($uname,$udom);
                   9302:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9303:     my $uhost=&hostname($uhome);
1.800     albertel 9304:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9305:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9306:                        $uhome);
1.479     albertel 9307:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9308:     return get_query_reply($queryid);
                   9309: }
                   9310: 
1.818     raeburn  9311: # -------------------------- Update MySQL table for portfolio file
                   9312: 
                   9313: sub update_portfolio_table {
1.821     raeburn  9314:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9315:     if ($group ne '') {
                   9316:         $file_name =~s /^\Q$group\E//;
                   9317:     }
1.818     raeburn  9318:     my $homeserver = &homeserver($uname,$udom);
                   9319:     my $queryid=
1.821     raeburn  9320:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9321:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9322:     my $reply = &get_query_reply($queryid);
                   9323:     return $reply;
                   9324: }
                   9325: 
1.899     raeburn  9326: # -------------------------- Update MySQL allusers table
                   9327: 
                   9328: sub update_allusers_table {
                   9329:     my ($uname,$udom,$names) = @_;
                   9330:     my $homeserver = &homeserver($uname,$udom);
                   9331:     my $queryid=
                   9332:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9333:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9334:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9335:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9336:                'generation='.&escape($names->{'generation'}).'%%'.
                   9337:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9338:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9339:     return;
1.899     raeburn  9340: }
                   9341: 
1.508     raeburn  9342: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9343: 
                   9344: sub fetch_enrollment_query {
1.511     raeburn  9345:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  9346:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9347:     my $maxtries = 1;
1.508     raeburn  9348:     if ($context eq 'automated') {
                   9349:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  9350:         $sleep = 2;
                   9351:         $loopmax = 100;
1.547     raeburn  9352:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9353:     } else {
                   9354:         $homeserver = &homeserver($cnum,$dom);
                   9355:     }
1.838     albertel 9356:     my $host=&hostname($homeserver);
1.506     raeburn  9357:     my $cmd = '';
1.1000    raeburn  9358:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9359:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9360:     }
                   9361:     $cmd =~ s/%%$//;
                   9362:     $cmd = &escape($cmd);
                   9363:     my $query = 'fetchenrollment';
1.620     albertel 9364:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9365:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9366:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9367:         return 'error: '.$queryid;
                   9368:     }
1.1317    raeburn  9369:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9370:     my $tries = 1;
                   9371:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  9372:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9373:         $tries ++;
                   9374:     }
1.526     raeburn  9375:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9376:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9377:     } else {
1.901     albertel 9378:         my @responses = split(/:/,$reply);
1.1322    raeburn  9379:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9380:             foreach my $line (@responses) {
                   9381:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9382:                 $$replyref{$key} = $value;
                   9383:             }
                   9384:         } else {
1.1117    foxr     9385:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9386:             foreach my $line (@responses) {
                   9387:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9388:                 $$replyref{$key} = $value;
                   9389:                 if ($value > 0) {
1.800     albertel 9390:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9391:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9392:                         my $destname = $pathname.'/'.$filename;
                   9393:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9394:                         if ($xml_classlist =~ /^error/) {
                   9395:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9396:                         } else {
1.1359    raeburn  9397:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9398:                                 print FILE &unescape($xml_classlist);
                   9399:                                 close(FILE);
1.526     raeburn  9400:                             } else {
                   9401:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9402:                             }
                   9403:                         }
                   9404:                     }
                   9405:                 }
                   9406:             }
                   9407:         }
                   9408:         return 'ok';
                   9409:     }
                   9410:     return 'error';
                   9411: }
                   9412: 
1.242     www      9413: sub get_query_reply {
1.1471    raeburn  9414:     my ($queryid,$sleep,$loopmax) = @_;
1.1317    raeburn  9415:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9416:         $sleep = 0.2;
                   9417:     }
                   9418:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9419:         $loopmax = 100;
                   9420:     }
1.1117    foxr     9421:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9422:     my $reply='';
1.1317    raeburn  9423:     for (1..$loopmax) {
                   9424: 	sleep($sleep);
1.240     www      9425:         if (-e $replyfile.'.end') {
1.1359    raeburn  9426: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9427: 		$reply = join('',<$fh>);
                   9428: 		close($fh);
1.240     www      9429: 	   } else { return 'error: reply_file_error'; }
1.242     www      9430:            return &unescape($reply);
                   9431: 	}
1.240     www      9432:     }
1.242     www      9433:     return 'timeout:'.$queryid;
1.240     www      9434: }
                   9435: 
                   9436: sub courselog_query {
1.241     www      9437: #
                   9438: # possible filters:
                   9439: # url: url or symb
                   9440: # username
                   9441: # domain
                   9442: # action: view, submit, grade
                   9443: # start: timestamp
                   9444: # end: timestamp
                   9445: #
1.240     www      9446:     my (%filters)=@_;
1.620     albertel 9447:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9448:     if ($filters{'url'}) {
                   9449: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9450:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9451:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9452:     }
1.620     albertel 9453:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9454:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9455:     return &log_query($cname,$cdom,'courselog',%filters);
                   9456: }
                   9457: 
                   9458: sub userlog_query {
1.858     raeburn  9459: #
                   9460: # possible filters:
                   9461: # action: log check role
                   9462: # start: timestamp
                   9463: # end: timestamp
                   9464: #
1.240     www      9465:     my ($uname,$udom,%filters)=@_;
                   9466:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9467: }
                   9468: 
1.506     raeburn  9469: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9470: 
                   9471: sub auto_run {
1.508     raeburn  9472:     my ($cnum,$cdom) = @_;
1.876     raeburn  9473:     my $response = 0;
                   9474:     my $settings;
                   9475:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9476:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9477:         $settings = $domconfig{'autoenroll'};
                   9478:         if ($settings->{'run'} eq '1') {
                   9479:             $response = 1;
                   9480:         }
                   9481:     } else {
1.934     raeburn  9482:         my $homeserver;
                   9483:         if (&is_course($cdom,$cnum)) {
                   9484:             $homeserver = &homeserver($cnum,$cdom);
                   9485:         } else {
                   9486:             $homeserver = &domain($cdom,'primary');
                   9487:         }
                   9488:         if ($homeserver ne 'no_host') {
                   9489:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9490:         }
1.876     raeburn  9491:     }
1.506     raeburn  9492:     return $response;
                   9493: }
1.776     albertel 9494: 
1.506     raeburn  9495: sub auto_get_sections {
1.508     raeburn  9496:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9497:     my $homeserver;
                   9498:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9499:         $homeserver = &homeserver($cnum,$cdom);
                   9500:     }
                   9501:     if (!defined($homeserver)) { 
                   9502:         if ($cdom =~ /^$match_domain$/) {
                   9503:             $homeserver = &domain($cdom,'primary');
                   9504:         }
                   9505:     }
                   9506:     my @secs;
                   9507:     if (defined($homeserver)) {
                   9508:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9509:         unless ($response eq 'refused') {
                   9510:             @secs = split(/:/,$response);
                   9511:         }
1.506     raeburn  9512:     }
                   9513:     return @secs;
                   9514: }
1.776     albertel 9515: 
1.506     raeburn  9516: sub auto_new_course {
1.1099    raeburn  9517:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9518:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9519:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9520:     return $response;
                   9521: }
1.776     albertel 9522: 
1.506     raeburn  9523: sub auto_validate_courseID {
1.508     raeburn  9524:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9525:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9526:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9527:     return $response;
                   9528: }
1.776     albertel 9529: 
1.1007    raeburn  9530: sub auto_validate_instcode {
1.1020    raeburn  9531:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9532:     my ($homeserver,$response);
                   9533:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9534:         $homeserver = &homeserver($cnum,$cdom);
                   9535:     }
                   9536:     if (!defined($homeserver)) {
                   9537:         if ($cdom =~ /^$match_domain$/) {
                   9538:             $homeserver = &domain($cdom,'primary');
                   9539:         }
                   9540:     }
1.1065    raeburn  9541:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9542:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  9543:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9544:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9545: }
                   9546: 
1.1444    raeburn  9547: sub auto_validate_inst_crosslist {
                   9548:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   9549:     my ($homeserver,$response);
                   9550:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9551:         $homeserver = &homeserver($cnum,$cdom);
                   9552:     }
                   9553:     if (!defined($homeserver)) {
                   9554:         if ($cdom =~ /^$match_domain$/) {
                   9555:             $homeserver = &domain($cdom,'primary');
                   9556:         }
                   9557:     }
                   9558:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   9559:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   9560:                          &escape($instcode).':'.&escape($inst_xlist).':'.
1.1445    raeburn  9561:                          &escape($coowner),$homeserver);
1.1444    raeburn  9562:     }
                   9563:     return $response;
                   9564: }
                   9565: 
1.506     raeburn  9566: sub auto_create_password {
1.873     raeburn  9567:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9568:     my ($homeserver,$response);
1.506     raeburn  9569:     my $create_passwd = 0;
                   9570:     my $authchk = '';
1.873     raeburn  9571:     if ($udom =~ /^$match_domain$/) {
                   9572:         $homeserver = &domain($udom,'primary');
                   9573:     }
                   9574:     if ($homeserver eq '') {
                   9575:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9576:             $homeserver = &homeserver($cnum,$cdom);
                   9577:         }
                   9578:     }
                   9579:     if ($homeserver eq '') {
                   9580:         $authchk = 'nodomain';
1.506     raeburn  9581:     } else {
1.873     raeburn  9582:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9583:         if ($response eq 'refused') {
                   9584:             $authchk = 'refused';
                   9585:         } else {
1.901     albertel 9586:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9587:         }
1.506     raeburn  9588:     }
                   9589:     return ($authparam,$create_passwd,$authchk);
                   9590: }
                   9591: 
1.706     raeburn  9592: sub auto_photo_permission {
                   9593:     my ($cnum,$cdom,$students) = @_;
                   9594:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9595:     my ($outcome,$perm_reqd,$conditions) = 
                   9596: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9597:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9598: 	return (undef,undef);
                   9599:     }
1.706     raeburn  9600:     return ($outcome,$perm_reqd,$conditions);
                   9601: }
                   9602: 
                   9603: sub auto_checkphotos {
                   9604:     my ($uname,$udom,$pid) = @_;
                   9605:     my $homeserver = &homeserver($uname,$udom);
                   9606:     my ($result,$resulttype);
                   9607:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9608: 				   &escape($uname).':'.&escape($pid),
                   9609: 				   $homeserver));
1.709     albertel 9610:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9611: 	return (undef,undef);
                   9612:     }
1.706     raeburn  9613:     if ($outcome) {
                   9614:         ($result,$resulttype) = split(/:/,$outcome);
                   9615:     } 
                   9616:     return ($result,$resulttype);
                   9617: }
                   9618: 
                   9619: sub auto_photochoice {
                   9620:     my ($cnum,$cdom) = @_;
                   9621:     my $homeserver = &homeserver($cnum,$cdom);
                   9622:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9623: 						       &escape($cdom),
                   9624: 						       $homeserver)));
1.709     albertel 9625:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9626: 	return (undef,undef);
                   9627:     }
1.706     raeburn  9628:     return ($update,$comment);
                   9629: }
                   9630: 
                   9631: sub auto_photoupdate {
                   9632:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9633:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9634:     my $host=&hostname($homeserver);
1.706     raeburn  9635:     my $cmd = '';
                   9636:     my $maxtries = 1;
1.800     albertel 9637:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9638:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9639:     }
                   9640:     $cmd =~ s/%%$//;
                   9641:     $cmd = &escape($cmd);
                   9642:     my $query = 'institutionalphotos';
                   9643:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9644:     unless ($queryid=~/^\Q$host\E\_/) {
                   9645:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9646:         return 'error: '.$queryid;
                   9647:     }
                   9648:     my $reply = &get_query_reply($queryid);
                   9649:     my $tries = 1;
                   9650:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9651:         $reply = &get_query_reply($queryid);
                   9652:         $tries ++;
                   9653:     }
                   9654:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9655:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9656:     } else {
                   9657:         my @responses = split(/:/,$reply);
                   9658:         my $outcome = shift(@responses); 
                   9659:         foreach my $item (@responses) {
                   9660:             my ($key,$value) = split(/=/,$item);
                   9661:             $$photo{$key} = $value;
                   9662:         }
                   9663:         return $outcome;
                   9664:     }
                   9665:     return 'error';
                   9666: }
                   9667: 
1.521     raeburn  9668: sub auto_instcode_format {
1.793     albertel 9669:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9670: 	$cat_order) = @_;
1.521     raeburn  9671:     my $courses = '';
1.772     raeburn  9672:     my @homeservers;
1.521     raeburn  9673:     if ($caller eq 'global') {
1.841     albertel 9674: 	my %servers = &get_servers($codedom,'library');
                   9675: 	foreach my $tryserver (keys(%servers)) {
                   9676: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9677: 		push(@homeservers,$tryserver);
                   9678: 	    }
1.584     raeburn  9679:         }
1.1022    raeburn  9680:     } elsif ($caller eq 'requests') {
                   9681:         if ($codedom =~ /^$match_domain$/) {
                   9682:             my $chome = &domain($codedom,'primary');
                   9683:             unless ($chome eq 'no_host') {
                   9684:                 push(@homeservers,$chome);
                   9685:             }
                   9686:         }
1.521     raeburn  9687:     } else {
1.772     raeburn  9688:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9689:     }
1.793     albertel 9690:     foreach my $code (keys(%{$instcodes})) {
                   9691:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9692:     }
                   9693:     chop($courses);
1.772     raeburn  9694:     my $ok_response = 0;
                   9695:     my $response;
                   9696:     while (@homeservers > 0 && $ok_response == 0) {
                   9697:         my $server = shift(@homeservers); 
                   9698:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9699:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9700:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9701: 		split(/:/,$response);
1.772     raeburn  9702:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9703:             push(@{$codetitles},&str2array($codetitles_str));
                   9704:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9705:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9706:             $ok_response = 1;
                   9707:         }
                   9708:     }
                   9709:     if ($ok_response) {
1.521     raeburn  9710:         return 'ok';
1.772     raeburn  9711:     } else {
                   9712:         return $response;
1.521     raeburn  9713:     }
                   9714: }
                   9715: 
1.792     raeburn  9716: sub auto_instcode_defaults {
                   9717:     my ($domain,$returnhash,$code_order) = @_;
                   9718:     my @homeservers;
1.841     albertel 9719: 
                   9720:     my %servers = &get_servers($domain,'library');
                   9721:     foreach my $tryserver (keys(%servers)) {
                   9722: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9723: 	    push(@homeservers,$tryserver);
                   9724: 	}
1.792     raeburn  9725:     }
1.841     albertel 9726: 
1.792     raeburn  9727:     my $response;
1.841     albertel 9728:     foreach my $server (@homeservers) {
1.792     raeburn  9729:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9730:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9731: 	
                   9732: 	foreach my $pair (split(/\&/,$response)) {
                   9733: 	    my ($name,$value)=split(/\=/,$pair);
                   9734: 	    if ($name eq 'code_order') {
                   9735: 		@{$code_order} = split(/\&/,&unescape($value));
                   9736: 	    } else {
                   9737: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9738: 	    }
                   9739: 	}
                   9740: 	return 'ok';
1.792     raeburn  9741:     }
1.841     albertel 9742: 
                   9743:     return $response;
1.1003    raeburn  9744: }
                   9745: 
                   9746: sub auto_possible_instcodes {
1.1007    raeburn  9747:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9748:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9749:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9750:         return;
                   9751:     }
1.1003    raeburn  9752:     my (@homeservers,$uhome);
                   9753:     if (defined(&domain($domain,'primary'))) {
                   9754:         $uhome=&domain($domain,'primary');
                   9755:         push(@homeservers,&domain($domain,'primary'));
                   9756:     } else {
                   9757:         my %servers = &get_servers($domain,'library');
                   9758:         foreach my $tryserver (keys(%servers)) {
                   9759:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9760:                 push(@homeservers,$tryserver);
                   9761:             }
                   9762:         }
                   9763:     }
                   9764:     my $response;
                   9765:     foreach my $server (@homeservers) {
                   9766:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9767:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9768:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9769:             split(':',$response);
                   9770:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9771:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9772:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9773:             my ($name,$value)=split('=',$item);
                   9774:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9775:         }
                   9776:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9777:             my ($name,$value)=split('=',$item);
                   9778:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9779:         }
                   9780:         return 'ok';
                   9781:     }
                   9782:     return $response;
                   9783: }
1.792     raeburn  9784: 
1.1010    raeburn  9785: sub auto_courserequest_checks {
                   9786:     my ($dom) = @_;
1.1020    raeburn  9787:     my ($homeserver,%validations);
                   9788:     if ($dom =~ /^$match_domain$/) {
                   9789:         $homeserver = &domain($dom,'primary');
                   9790:     }
                   9791:     unless ($homeserver eq 'no_host') {
                   9792:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9793:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9794:             my @items = split(/&/,$response);
                   9795:             foreach my $item (@items) {
                   9796:                 my ($key,$value) = split('=',$item);
                   9797:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9798:             }
                   9799:         }
                   9800:     }
1.1010    raeburn  9801:     return %validations; 
                   9802: }
                   9803: 
1.1020    raeburn  9804: sub auto_courserequest_validation {
1.1255    raeburn  9805:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9806:     my ($homeserver,$response);
                   9807:     if ($dom =~ /^$match_domain$/) {
                   9808:         $homeserver = &domain($dom,'primary');
                   9809:     }
1.1255    raeburn  9810:     unless ($homeserver eq 'no_host') {
                   9811:         my $customdata;
                   9812:         if (ref($custominfo) eq 'HASH') {
                   9813:             $customdata = &freeze_escape($custominfo);
                   9814:         }
1.1020    raeburn  9815:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9816:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  9817:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9818:                                     $customdata,$homeserver));
1.1020    raeburn  9819:     }
                   9820:     return $response;
                   9821: }
                   9822: 
1.777     albertel 9823: sub auto_validate_class_sec {
1.918     raeburn  9824:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9825:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9826:     my $ownerlist;
                   9827:     if (ref($owners) eq 'ARRAY') {
                   9828:         $ownerlist = join(',',@{$owners});
                   9829:     } else {
                   9830:         $ownerlist = $owners;
                   9831:     }
1.773     raeburn  9832:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9833:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9834:     return $response;
                   9835: }
                   9836: 
1.1460    raeburn  9837: sub auto_instsec_reformat {
                   9838:     my ($cdom,$action,$instsecref) = @_;
                   9839:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   9840:     my @homeservers;
                   9841:     if (defined(&domain($cdom,'primary'))) {
                   9842:         push(@homeservers,&domain($cdom,'primary'));
                   9843:     } else {
                   9844:         my %servers = &get_servers($cdom,'library');
                   9845:         foreach my $tryserver (keys(%servers)) {
                   9846:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9847:                 push(@homeservers,$tryserver);
                   9848:             }
                   9849:         }
                   9850:     }
                   9851:     my $response;
                   9852:     my %reformatted = %{$instsecref};
                   9853:     foreach my $server (@homeservers) {
                   9854:         if (ref($instsecref) eq 'HASH') {
                   9855:             my $info = &freeze_escape($instsecref);
                   9856:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   9857:                                 $action.':'.$info,$server);
                   9858:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   9859:             my @items = split(/&/,$response);
                   9860:             foreach my $item (@items) {
                   9861:                 my ($key,$value) = split(/=/,$item);
                   9862:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   9863:             }
                   9864:         }
                   9865:     }
                   9866:     return %reformatted;
                   9867: }
                   9868: 
1.1367    raeburn  9869: sub auto_validate_instclasses {
                   9870:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9871:     my ($homeserver,%validations);
                   9872:     $homeserver = &homeserver($cnum,$cdom);
                   9873:     unless ($homeserver eq 'no_host') {
                   9874:         my $ownerlist;
                   9875:         if (ref($owners) eq 'ARRAY') {
                   9876:             $ownerlist = join(',',@{$owners});
                   9877:         } else {
                   9878:             $ownerlist = $owners;
                   9879:         }
                   9880:         if (ref($classesref) eq 'HASH') {
                   9881:             my $classes = &freeze_escape($classesref);
                   9882:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9883:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9884:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9885:                 my @items = split(/&/,$response);
                   9886:                 foreach my $item (@items) {
                   9887:                     my ($key,$value) = split('=',$item);
                   9888:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9889:                 }
                   9890:             }
                   9891:         }
                   9892:     }
                   9893:     return %validations;
                   9894: }
                   9895: 
1.1248    raeburn  9896: sub auto_crsreq_update {
                   9897:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  9898:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  9899:     my ($homeserver,%crsreqresponse);
                   9900:     if ($cdom =~ /^$match_domain$/) {
                   9901:         $homeserver = &domain($cdom,'primary');
                   9902:     }
                   9903:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9904:         my $info;
                   9905:         if (ref($inbound) eq 'HASH') {
                   9906:             $info = &freeze_escape($inbound);
                   9907:         }
                   9908:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9909:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9910:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  9911:                             &escape($title).':'.&escape($code).':'.
                   9912:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   9913:                             $homeserver);
1.1248    raeburn  9914:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9915:             my @items = split(/&/,$response);
                   9916:             foreach my $item (@items) {
                   9917:                 my ($key,$value) = split('=',$item);
                   9918:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9919:             }
                   9920:         }
                   9921:     }
                   9922:     return \%crsreqresponse;
                   9923: }
                   9924: 
1.1305    raeburn  9925: sub auto_export_grades {
1.1309    raeburn  9926:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9927:     my ($homeserver,%exportresponse);
                   9928:     if ($cdom =~ /^$match_domain$/) {
                   9929:         $homeserver = &domain($cdom,'primary');
                   9930:     }
                   9931:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9932:         my $info;
                   9933:         if (ref($inforef) eq 'HASH') {
                   9934:             $info = &freeze_escape($inforef);
                   9935:         }
                   9936:         if (ref($gradesref) eq 'HASH') {
                   9937:             my $grades = &freeze_escape($gradesref);
                   9938:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9939:                                 $info.':'.$grades,$homeserver);
                   9940:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9941:                 my @items = split(/&/,$response);
                   9942:                 foreach my $item (@items) {
                   9943:                     my ($key,$value) = split('=',$item);
                   9944:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9945:                 }
                   9946:             }
                   9947:         }
                   9948:     }
                   9949:     return \%exportresponse;
1.1305    raeburn  9950: }
                   9951: 
1.1287    raeburn  9952: sub check_instcode_cloning {
                   9953:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9954:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9955:         return;
                   9956:     }
                   9957:     my $canclone;
                   9958:     if (@{$code_order} > 0) {
                   9959:         my $instcoderegexp ='^';
                   9960:         my @clonecodes = split(/\&/,$cloner);
                   9961:         foreach my $item (@{$code_order}) {
                   9962:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9963:                 foreach my $pair (@clonecodes) {
                   9964:                     my ($key,$val) = split(/\=/,$pair,2);
                   9965:                     $val = &unescape($val);
                   9966:                     if ($key eq $item) {
                   9967:                         $instcoderegexp .= '('.$val.')';
                   9968:                         last;
                   9969:                     }
                   9970:                 }
                   9971:             } else {
                   9972:                 $instcoderegexp .= $codedefaults->{$item};
                   9973:             }
                   9974:         }
                   9975:         $instcoderegexp .= '$';
                   9976:         my (@from,@to);
                   9977:         eval {
                   9978:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9979:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9980:         };
                   9981:         if ((@from > 0) && (@to > 0)) {
                   9982:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9983:             if (!@diffs) {
                   9984:                 $canclone = 1;
                   9985:             }
                   9986:         }
                   9987:     }
                   9988:     return $canclone;
                   9989: }
                   9990: 
                   9991: sub default_instcode_cloning {
                   9992:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9993:     my (%codedefaults,@code_order,$canclone);
                   9994:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9995:         %codedefaults = %{$codedefaultsref};
                   9996:         @code_order = @{$codeorderref};
                   9997:     } elsif ($clonedom) {
                   9998:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9999:     }
                   10000:     if (($domdefclone) && (@code_order)) {
                   10001:         my @clonecodes = split(/\+/,$domdefclone);
                   10002:         my $instcoderegexp ='^';
                   10003:         foreach my $item (@code_order) {
                   10004:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   10005:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   10006:             } else {
                   10007:                 $instcoderegexp .= $codedefaults{$item};
                   10008:             }
                   10009:         }
                   10010:         $instcoderegexp .= '$';
                   10011:         my (@from,@to);
                   10012:         eval {
                   10013:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10014:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10015:         };
                   10016:         if ((@from > 0) && (@to > 0)) {
                   10017:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10018:             if (!@diffs) {
                   10019:                 $canclone = 1;
                   10020:             }
                   10021:         }
                   10022:     }
                   10023:     return $canclone;
                   10024: }
                   10025: 
1.679     raeburn  10026: # ------------------------------------------------------- Course Group routines
                   10027: 
                   10028: sub get_coursegroups {
1.809     raeburn  10029:     my ($cdom,$cnum,$group,$namespace) = @_;
                   10030:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  10031: }
                   10032: 
1.679     raeburn  10033: sub modify_coursegroup {
                   10034:     my ($cdom,$cnum,$groupsettings) = @_;
                   10035:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   10036: }
                   10037: 
1.809     raeburn  10038: sub toggle_coursegroup_status {
                   10039:     my ($cdom,$cnum,$group,$action) = @_;
                   10040:     my ($from_namespace,$to_namespace);
                   10041:     if ($action eq 'delete') {
                   10042:         $from_namespace = 'coursegroups';
                   10043:         $to_namespace = 'deleted_groups';
                   10044:     } else {
                   10045:         $from_namespace = 'deleted_groups';
                   10046:         $to_namespace = 'coursegroups';
                   10047:     }
                   10048:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  10049:     if (my $tmp = &error(%curr_group)) {
                   10050:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   10051:         return ('read error',$tmp);
                   10052:     } else {
                   10053:         my %savedsettings = %curr_group; 
1.809     raeburn  10054:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  10055:         my $deloutcome;
                   10056:         if ($result eq 'ok') {
1.809     raeburn  10057:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  10058:         } else {
                   10059:             return ('write error',$result);
                   10060:         }
                   10061:         if ($deloutcome eq 'ok') {
                   10062:             return 'ok';
                   10063:         } else {
                   10064:             return ('delete error',$deloutcome);
                   10065:         }
                   10066:     }
                   10067: }
                   10068: 
1.679     raeburn  10069: sub modify_group_roles {
1.957     raeburn  10070:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  10071:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   10072:     my $role = 'gr/'.&escape($userprivs);
                   10073:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  10074:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  10075:     if ($result eq 'ok') {
                   10076:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   10077:     }
1.679     raeburn  10078:     return $result;
                   10079: }
                   10080: 
                   10081: sub modify_coursegroup_membership {
                   10082:     my ($cdom,$cnum,$membership) = @_;
                   10083:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   10084:     return $result;
                   10085: }
                   10086: 
1.682     raeburn  10087: sub get_active_groups {
                   10088:     my ($udom,$uname,$cdom,$cnum) = @_;
                   10089:     my $now = time;
                   10090:     my %groups = ();
                   10091:     foreach my $key (keys(%env)) {
1.811     albertel 10092:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  10093:             my ($start,$end) = split(/\./,$env{$key});
                   10094:             if (($end!=0) && ($end<$now)) { next; }
                   10095:             if (($start!=0) && ($start>$now)) { next; }
                   10096:             if ($1 eq $cdom && $2 eq $cnum) {
                   10097:                 $groups{$3} = $env{$key} ;
                   10098:             }
                   10099:         }
                   10100:     }
                   10101:     return %groups;
                   10102: }
                   10103: 
1.683     raeburn  10104: sub get_group_membership {
                   10105:     my ($cdom,$cnum,$group) = @_;
                   10106:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   10107: }
                   10108: 
                   10109: sub get_users_groups {
                   10110:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  10111:     my @usersgroups;
1.683     raeburn  10112:     my $cachetime=1800;
                   10113: 
                   10114:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  10115:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   10116:     if (defined($cached)) {
1.734     albertel 10117:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  10118:     } else {  
                   10119:         $grouplist = '';
1.816     raeburn  10120:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  10121:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  10122:         my $access_end = $env{'course.'.$courseid.
                   10123:                               '.default_enrollment_end_date'};
                   10124:         my $now = time;
                   10125:         foreach my $key (keys(%roleshash)) {
                   10126:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   10127:                 my $group = $1;
                   10128:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   10129:                     my $start = $2;
                   10130:                     my $end = $1;
                   10131:                     if ($start == -1) { next; } # deleted from group
                   10132:                     if (($start!=0) && ($start>$now)) { next; }
                   10133:                     if (($end!=0) && ($end<$now)) {
                   10134:                         if ($access_end && $access_end < $now) {
                   10135:                             if ($access_end - $end < 86400) {
                   10136:                                 push(@usersgroups,$group);
1.733     raeburn  10137:                             }
                   10138:                         }
1.817     raeburn  10139:                         next;
1.733     raeburn  10140:                     }
1.817     raeburn  10141:                     push(@usersgroups,$group);
1.683     raeburn  10142:                 }
                   10143:             }
                   10144:         }
1.817     raeburn  10145:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   10146:         $grouplist = join(':',@usersgroups);
                   10147:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  10148:     }
1.733     raeburn  10149:     return @usersgroups;
1.683     raeburn  10150: }
                   10151: 
                   10152: sub devalidate_getgroups_cache {
                   10153:     my ($udom,$uname,$cdom,$cnum)=@_;
                   10154:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 10155: 
1.683     raeburn  10156:     my $hashid="$udom:$uname:$courseid";
                   10157:     &devalidate_cache_new('getgroups',$hashid);
                   10158: }
                   10159: 
1.12      www      10160: # ------------------------------------------------------------------ Plain Text
                   10161: 
                   10162: sub plaintext {
1.988     raeburn  10163:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  10164:     if ($short =~ m{^cr/}) {
1.758     albertel 10165: 	return (split('/',$short))[-1];
                   10166:     }
1.742     raeburn  10167:     if (!defined($cid)) {
                   10168:         $cid = $env{'request.course.id'};
                   10169:     }
                   10170:     my %rolenames = (
1.1008    raeburn  10171:                       Course    => 'std',
                   10172:                       Community => 'alt1',
1.1305    raeburn  10173:                       Placement => 'std',
1.742     raeburn  10174:                     );
1.1037    raeburn  10175:     if ($cid ne '') {
                   10176:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   10177:             unless ($forcedefault) {
                   10178:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   10179:                 &Apache::lonlocal::mt_escape(\$roletext);
                   10180:                 return &Apache::lonlocal::mt($roletext);
                   10181:             }
                   10182:         }
                   10183:     }
                   10184:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   10185:         (defined($rolenames{$type})) && 
                   10186:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  10187:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  10188:     } elsif ($cid ne '') {
                   10189:         my $crstype = $env{'course.'.$cid.'.type'};
                   10190:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   10191:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   10192:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   10193:         }
1.742     raeburn  10194:     }
1.1037    raeburn  10195:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      10196: }
                   10197: 
                   10198: # ----------------------------------------------------------------- Assign Role
                   10199: 
                   10200: sub assignrole {
1.957     raeburn  10201:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   10202:         $context)=@_;
1.21      www      10203:     my $mrole;
                   10204:     if ($role =~ /^cr\//) {
1.393     www      10205:         my $cwosec=$url;
1.811     albertel 10206:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      10207: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  10208:            my $refused = 1;
                   10209:            if ($context eq 'requestcourses') {
                   10210:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   10211:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   10212:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   10213:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10214:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10215:                            if ($crsenv{'internal.courseowner'} eq
                   10216:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   10217:                                $refused = '';
                   10218:                            }
                   10219:                        }
                   10220:                    }
                   10221:                }
                   10222:            }
                   10223:            if ($refused) {
                   10224:                &logthis('Refused custom assignrole: '.
                   10225:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   10226:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   10227:                return 'refused';
                   10228:            }
1.104     www      10229:         }
1.21      www      10230:         $mrole='cr';
1.678     raeburn  10231:     } elsif ($role =~ /^gr\//) {
                   10232:         my $cwogrp=$url;
1.811     albertel 10233:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  10234:         unless (&allowed('mdg',$cwogrp)) {
                   10235:             &logthis('Refused group assignrole: '.
                   10236:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   10237:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   10238:             return 'refused';
                   10239:         }
                   10240:         $mrole='gr';
1.21      www      10241:     } else {
1.82      www      10242:         my $cwosec=$url;
1.811     albertel 10243:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  10244:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   10245:             my $refused;
                   10246:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   10247:                 if (!(&allowed('c'.$role,$url))) {
                   10248:                     $refused = 1;
                   10249:                 }
                   10250:             } else {
                   10251:                 $refused = 1;
                   10252:             }
1.947     raeburn  10253:             if ($refused) {
1.1045    raeburn  10254:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377    raeburn  10255:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  10256:                     my %crsenv;
                   10257:                     if ($role eq 'cc' || $role eq 'co') {
                   10258:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10259:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   10260:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   10261:                                 if ($crsenv{'internal.courseowner'} eq 
                   10262:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10263:                                     $refused = '';
                   10264:                                 }
                   10265:                             }
                   10266:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   10267:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   10268:                                 if ($crsenv{'internal.courseowner'} eq 
                   10269:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10270:                                     $refused = '';
                   10271:                                 }
                   10272:                             }
                   10273:                         }
                   10274:                     }
1.1368    raeburn  10275:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   10276:                     if ($role eq 'st') {
                   10277:                         $refused = '';
1.1377    raeburn  10278:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  10279:                         $refused = '';
                   10280:                     }
1.1017    raeburn  10281:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10282:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10283:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10284:                         my $wrongcc;
                   10285:                         if ($cnum =~ /^$match_community$/) {
                   10286:                             $wrongcc = 1 if ($role eq 'cc');
                   10287:                         } else {
                   10288:                             $wrongcc = 1 if ($role eq 'co');
                   10289:                         }
                   10290:                         unless ($wrongcc) {
                   10291:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10292:                             if ($crsenv{'internal.courseowner'} eq 
                   10293:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10294:                                 $refused = '';
                   10295:                             }
1.1017    raeburn  10296:                         }
                   10297:                     }
1.1183    raeburn  10298:                 } elsif ($context eq 'requestauthor') {
                   10299:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   10300:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10301:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10302:                             $refused = '';
                   10303:                         } else {
                   10304:                             my %domdefaults = &get_domain_defaults($udom);
                   10305:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10306:                                 my $checkbystatus;
                   10307:                                 if ($env{'user.adv'}) { 
                   10308:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10309:                                     if ($disposition eq 'automatic') {
                   10310:                                         $refused = '';
                   10311:                                     } elsif ($disposition eq '') {
                   10312:                                         $checkbystatus = 1;
                   10313:                                     } 
                   10314:                                 } else {
                   10315:                                     $checkbystatus = 1;
                   10316:                                 }
                   10317:                                 if ($checkbystatus) {
                   10318:                                     if ($env{'environment.inststatus'}) {
                   10319:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10320:                                         foreach my $type (@inststatuses) {
                   10321:                                             if (($type ne '') &&
                   10322:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10323:                                                 $refused = '';
                   10324:                                             }
                   10325:                                         }
                   10326:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10327:                                         $refused = '';
                   10328:                                     }
                   10329:                                 }
                   10330:                             }
                   10331:                         }
                   10332:                     }
1.1017    raeburn  10333:                 }
                   10334:                 if ($refused) {
1.947     raeburn  10335:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10336:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10337: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10338:                     return 'refused';
                   10339:                 }
1.932     raeburn  10340:             }
1.1131    raeburn  10341:         } elsif ($role eq 'au') {
                   10342:             if ($url ne '/'.$udom.'/') {
                   10343:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10344:                          ' to assign author role for '.$uname.':'.$udom.
                   10345:                          ' in domain: '.$url.' refused (wrong domain).');
                   10346:                 return 'refused';
                   10347:             }
1.104     www      10348:         }
1.21      www      10349:         $mrole=$role;
                   10350:     }
1.620     albertel 10351:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10352:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10353:     if ($end) { $command.='_'.$end; }
1.21      www      10354:     if ($start) {
                   10355: 	if ($end) { 
1.81      www      10356:            $command.='_'.$start; 
1.21      www      10357:         } else {
1.81      www      10358:            $command.='_0_'.$start;
1.21      www      10359:         }
                   10360:     }
1.739     raeburn  10361:     my $origstart = $start;
                   10362:     my $origend = $end;
1.957     raeburn  10363:     my $delflag;
1.357     www      10364: # actually delete
                   10365:     if ($deleteflag) {
1.373     www      10366: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10367: # modify command to delete the role
1.620     albertel 10368:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10369:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10370: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10371: # set start and finish to negative values for userrolelog
                   10372:            $start=-1;
                   10373:            $end=-1;
1.957     raeburn  10374:            $delflag = 1;
1.357     www      10375:         }
                   10376:     }
                   10377: # send command
1.349     www      10378:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      10379: # log new user role if status is ok
1.349     www      10380:     if ($answer eq 'ok') {
1.663     raeburn  10381: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  10382:         if (($role eq 'cc') || ($role eq 'in') ||
                   10383:             ($role eq 'ep') || ($role eq 'ad') ||
                   10384:             ($role eq 'ta') || ($role eq 'st') ||
                   10385:             ($role=~/^cr/) || ($role eq 'gr') ||
                   10386:             ($role eq 'co')) {
1.1200    raeburn  10387: # for course roles, perform group memberships changes triggered by role change.
                   10388:             unless ($role =~ /^gr/) {
                   10389:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10390:                                                  $origstart,$selfenroll,$context);
                   10391:             }
1.1184    raeburn  10392:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10393:                            $selfenroll,$context);
                   10394:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  10395:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10396:                  ($role eq 'da')) {
1.1184    raeburn  10397:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10398:                            $context);
                   10399:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10400:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10401:                              $context); 
                   10402:         }
1.1053    raeburn  10403:         if ($role eq 'cc') {
                   10404:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10405:         }
1.349     www      10406:     }
                   10407:     return $answer;
1.169     harris41 10408: }
                   10409: 
1.1053    raeburn  10410: sub autoupdate_coowners {
                   10411:     my ($url,$end,$start,$uname,$udom) = @_;
                   10412:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10413:     if (($cdom ne '') && ($cnum ne '')) {
                   10414:         my $now = time;
                   10415:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10416:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10417:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10418:             my $instcode = $coursehash{'internal.coursecode'};
1.1444    raeburn  10419:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  10420:             if ($instcode ne '') {
1.1056    raeburn  10421:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10422:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10423:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10424:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1444    raeburn  10425:                         unless ($result eq 'valid') {
                   10426:                             if ($xlists ne '') {
                   10427:                                 foreach my $xlist (split(',',$xlists)) {
                   10428:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   10429:                                     $result =
1.1446    raeburn  10430:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   10431:                                                                       $inst_crosslist,$uname.':'.$udom);
                   10432:                                     last if ($result eq 'valid');
1.1444    raeburn  10433:                                 }
                   10434:                             }
                   10435:                         }
1.1056    raeburn  10436:                         if ($result eq 'valid') {
                   10437:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10438:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10439:                                     push(@newcoowners,$coowner);
                   10440:                                 }
                   10441:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10442:                                     push(@newcoowners,$uname.':'.$udom);
                   10443:                                 }
                   10444:                                 @newcoowners = sort(@newcoowners);
                   10445:                             } else {
                   10446:                                 push(@newcoowners,$uname.':'.$udom);
                   10447:                             }
1.1444    raeburn  10448:                         } elsif ($coursehash{'internal.co-owners'}) {
                   10449:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10450:                                 unless ($coowner eq $uname.':'.$udom) {
                   10451:                                     push(@newcoowners,$coowner);
1.1053    raeburn  10452:                                 }
1.1444    raeburn  10453:                             }
                   10454:                             unless (@newcoowners > 0) {
                   10455:                                 $delcoowners = 1;
                   10456:                                 $coowners = '';
1.1053    raeburn  10457:                             }
                   10458:                         }
                   10459:                         if (@newcoowners || $delcoowners) {
                   10460:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10461:                                             $delcoowners,@newcoowners);
                   10462:                         }
                   10463:                     }
                   10464:                 }
                   10465:             }
                   10466:         }
                   10467:     }
                   10468: }
                   10469: 
                   10470: sub store_coowners {
                   10471:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10472:     my $cid = $cdom.'_'.$cnum;
                   10473:     my ($coowners,$delresult,$putresult);
                   10474:     if (@newcoowners) {
                   10475:         $coowners = join(',',@newcoowners);
                   10476:         my %coownershash = (
                   10477:                             'internal.co-owners' => $coowners,
                   10478:                            );
                   10479:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10480:         if ($putresult eq 'ok') {
                   10481:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10482:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10483:             }
                   10484:         }
                   10485:     }
                   10486:     if ($delcoowners) {
                   10487:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10488:         if ($delresult eq 'ok') {
                   10489:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10490:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10491:             }
                   10492:         }
                   10493:     }
                   10494:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10495:         my %crsinfo =
                   10496:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10497:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10498:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10499:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10500:         }
                   10501:     }
                   10502: }
                   10503: 
1.169     harris41 10504: # -------------------------------------------------- Modify user authentication
1.197     www      10505: # Overrides without validation
                   10506: 
1.169     harris41 10507: sub modifyuserauth {
                   10508:     my ($udom,$uname,$umode,$upass)=@_;
                   10509:     my $uhome=&homeserver($uname,$udom);
1.1409    raeburn  10510:     my $allowed;
                   10511:     if (&allowed('mau',$udom)) {
                   10512:         $allowed = 1;
                   10513:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10514:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10515:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10516:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10517:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10518:         if (($cdom ne '') && ($cnum ne '')) {
                   10519:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10520:             if ($is_owner) {
                   10521:                 $allowed = 1;
                   10522:             }
                   10523:         }
                   10524:     }
                   10525:     unless ($allowed) { return 'refused'; }
1.197     www      10526:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10527:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10528:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10529:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10530: 		     &escape($upass),$uhome);
1.1434    raeburn  10531:     my $ip = &get_requestor_ip();
1.620     albertel 10532:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10533:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1434    raeburn  10534:          '(Remote '.$ip.'): '.$reply);
1.197     www      10535:     &log($udom,,$uname,$uhome,
1.620     albertel 10536:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10537:                                      $env{'user.name'}.', '.$umode.
1.1435    raeburn  10538:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10539:     unless ($reply eq 'ok') {
1.197     www      10540:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10541: 	return 'error: '.$reply;
                   10542:     }   
1.170     harris41 10543:     return 'ok';
1.80      www      10544: }
                   10545: 
1.81      www      10546: # --------------------------------------------------------------- Modify a user
1.80      www      10547: 
1.81      www      10548: sub modifyuser {
1.206     matthew  10549:     my ($udom,    $uname, $uid,
                   10550:         $umode,   $upass, $first,
                   10551:         $middle,  $last,  $gene,
1.1058    raeburn  10552:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10553:     $udom= &LONCAPA::clean_domain($udom);
                   10554:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10555:     my $showcandelete = 'none';
                   10556:     if (ref($candelete) eq 'ARRAY') {
                   10557:         if (@{$candelete} > 0) {
                   10558:             $showcandelete = join(', ',@{$candelete});
                   10559:         }
                   10560:     }
1.81      www      10561:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10562:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10563: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10564:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10565:                                      ' desiredhome not specified'). 
1.620     albertel 10566:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10567:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10568:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10569:     my $newuser;
                   10570:     if ($uhome eq 'no_host') {
                   10571:         $newuser = 1;
1.1368    raeburn  10572:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   10573:                 ($umode eq 'lti')) {
                   10574:             return 'error: more information needed to create new user';
                   10575:         }
1.1075    raeburn  10576:     }
1.80      www      10577: # ----------------------------------------------------------------- Create User
1.406     albertel 10578:     if (($uhome eq 'no_host') && 
1.1368    raeburn  10579: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      10580:         my $unhome='';
1.844     albertel 10581:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10582:             $unhome = $desiredhome;
1.620     albertel 10583: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10584: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10585:         } else { # load balancing routine for determining $unhome
1.81      www      10586:             my $loadm=10000000;
1.841     albertel 10587: 	    my %servers = &get_servers($udom,'library');
                   10588: 	    foreach my $tryserver (keys(%servers)) {
                   10589: 		my $answer=reply('load',$tryserver);
                   10590: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10591: 		    $loadm=$answer;
                   10592: 		    $unhome=$tryserver;
                   10593: 		}
1.80      www      10594: 	    }
                   10595:         }
                   10596:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10597: 	    return 'error: unable to find a home server for '.$uname.
                   10598:                    ' in domain '.$udom;
1.80      www      10599:         }
                   10600:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10601:                          &escape($upass),$unhome);
                   10602: 	unless ($reply eq 'ok') {
                   10603:             return 'error: '.$reply;
                   10604:         }   
1.230     stredwic 10605:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10606:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10607: 	    return 'error: unable verify users home machine.';
1.80      www      10608:         }
1.209     matthew  10609:     }   # End of creation of new user
1.80      www      10610: # ---------------------------------------------------------------------- Add ID
                   10611:     if ($uid) {
                   10612:        $uid=~tr/A-Z/a-z/;
                   10613:        my %uidhash=&idrget($udom,$uname);
1.196     www      10614:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10615:          && (!$forceid)) {
1.80      www      10616: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10617: 	      return 'error: user id "'.$uid.'" does not match '.
                   10618:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10619:           }
                   10620:        } else {
1.1300    raeburn  10621: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      10622:        }
                   10623:     }
                   10624: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10625:     my @tmp=&get('environment',
1.899     raeburn  10626: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10627:                     'permanentemail','inststatus'],
1.134     albertel 10628: 		   $udom,$uname);
1.1075    raeburn  10629:     my (%names,%oldnames);
1.313     matthew  10630:     if ($tmp[0] =~ m/^error:.*/) { 
                   10631:         %names=(); 
                   10632:     } else {
                   10633:         %names = @tmp;
1.1075    raeburn  10634:         %oldnames = %names;
1.313     matthew  10635:     }
1.388     www      10636: #
1.1058    raeburn  10637: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10638: # of users did not contain them), do not overwrite existing values
                   10639: # unless field is in $candelete array ref.  
                   10640: #
                   10641: 
                   10642:     my @fields = ('firstname','middlename','lastname','generation',
                   10643:                   'permanentemail','id');
                   10644:     my %newvalues;
                   10645:     if (ref($candelete) eq 'ARRAY') {
                   10646:         foreach my $field (@fields) {
                   10647:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10648:                 if ($field eq 'firstname') {
                   10649:                     $names{$field} = $first;
                   10650:                 } elsif ($field eq 'middlename') {
                   10651:                     $names{$field} = $middle;
                   10652:                 } elsif ($field eq 'lastname') {
                   10653:                     $names{$field} = $last;
                   10654:                 } elsif ($field eq 'generation') { 
                   10655:                     $names{$field} = $gene;
                   10656:                 } elsif ($field eq 'permanentemail') {
                   10657:                     $names{$field} = $email;
                   10658:                 } elsif ($field eq 'id') {
                   10659:                     $names{$field}  = $uid;
                   10660:                 }
                   10661:             }
                   10662:         }
                   10663:     }
1.388     www      10664:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10665:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10666:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10667:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10668:     if ($email) {
                   10669:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10670:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10671:     }
1.899     raeburn  10672:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10673:     if (defined($inststatus)) {
                   10674:         $names{'inststatus'} = '';
                   10675:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10676:         if (ref($usertypes) eq 'HASH') {
                   10677:             my @okstatuses; 
                   10678:             foreach my $item (split(/:/,$inststatus)) {
                   10679:                 if (defined($usertypes->{$item})) {
                   10680:                     push(@okstatuses,$item);  
                   10681:                 }
                   10682:             }
                   10683:             if (@okstatuses) {
                   10684:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10685:             }
                   10686:         }
                   10687:     }
1.1075    raeburn  10688:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10689:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10690:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10691:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10692:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10693:     } else {
                   10694:         $logmsg .= ' during self creation';
                   10695:     }
1.1075    raeburn  10696:     my $changed;
                   10697:     if ($newuser) {
                   10698:         $changed = 1;
                   10699:     } else {
                   10700:         foreach my $field (@fields) {
                   10701:             if ($names{$field} ne $oldnames{$field}) {
                   10702:                 $changed = 1;
                   10703:                 last;
                   10704:             }
                   10705:         }
                   10706:     }
                   10707:     unless ($changed) {
                   10708:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10709:         &logthis($logmsg);
                   10710:         return 'ok';
                   10711:     }
                   10712:     my $reply = &put('environment', \%names, $udom,$uname);
                   10713:     if ($reply ne 'ok') { 
                   10714:         return 'error: '.$reply;
                   10715:     }
1.1087    raeburn  10716:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10717:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10718:     }
1.1075    raeburn  10719:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10720:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10721:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10722:     &logthis($logmsg);
1.134     albertel 10723:     return 'ok';
1.80      www      10724: }
                   10725: 
1.81      www      10726: # -------------------------------------------------------------- Modify student
1.80      www      10727: 
1.81      www      10728: sub modifystudent {
                   10729:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10730:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  10731:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10732:     if (!$cid) {
1.620     albertel 10733: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10734: 	    return 'not_in_class';
                   10735: 	}
1.80      www      10736:     }
                   10737: # --------------------------------------------------------------- Make the user
1.81      www      10738:     my $reply=&modifyuser
1.209     matthew  10739: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10740:          $desiredhome,$email,$inststatus);
1.80      www      10741:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10742:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  10743:     # student's environment
1.297     matthew  10744:     $uid = undef if (!$forceid);
1.455     albertel 10745:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  10746:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  10747:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10748:     return $reply;
                   10749: }
                   10750: 
                   10751: sub modify_student_enrollment {
1.1216    raeburn  10752:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  10753:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10754:     my ($cdom,$cnum,$chome);
                   10755:     if (!$cid) {
1.620     albertel 10756: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10757: 	    return 'not_in_class';
                   10758: 	}
1.620     albertel 10759: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10760: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10761:     } else {
                   10762: 	($cdom,$cnum)=split(/_/,$cid);
                   10763:     }
1.620     albertel 10764:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10765:     if (!$chome) {
1.457     raeburn  10766: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10767:     }
1.455     albertel 10768:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10769:     # Make sure the user exists
1.81      www      10770:     my $uhome=&homeserver($uname,$udom);
                   10771:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10772: 	return 'error: no such user';
                   10773:     }
1.297     matthew  10774:     # Get student data if we were not given enough information
                   10775:     if (!defined($first)  || $first  eq '' || 
                   10776:         !defined($last)   || $last   eq '' || 
                   10777:         !defined($uid)    || $uid    eq '' || 
                   10778:         !defined($middle) || $middle eq '' || 
                   10779:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10780:         # They did not supply us with enough data to enroll the student, so
                   10781:         # we need to pick up more information.
1.297     matthew  10782:         my %tmp = &get('environment',
1.294     matthew  10783:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10784:                        ,$udom,$uname);
                   10785: 
1.800     albertel 10786:         #foreach my $key (keys(%tmp)) {
                   10787:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10788:         #}
1.294     matthew  10789:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10790:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10791:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10792:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10793:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10794:     }
1.556     albertel 10795:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10796:     my $user = "$uname:$udom";
                   10797:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10798:     my $reply=cput('classlist',
1.1148    raeburn  10799: 		   {$user => 
1.1314    raeburn  10800: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10801: 		   $cdom,$cnum);
1.1148    raeburn  10802:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10803:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10804:     } else { 
1.81      www      10805: 	return 'error: '.$reply;
                   10806:     }
1.297     matthew  10807:     # Add student role to user
1.83      www      10808:     my $uurl='/'.$cid;
1.81      www      10809:     $uurl=~s/\_/\//g;
                   10810:     if ($usec) {
                   10811: 	$uurl.='/'.$usec;
                   10812:     }
1.1148    raeburn  10813:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10814:                              $selfenroll,$context);
                   10815:     if ($result ne 'ok') {
                   10816:         if ($old_entry{$user} ne '') {
                   10817:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10818:         } else {
                   10819:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10820:         }
                   10821:     }
                   10822:     return $result; 
1.21      www      10823: }
                   10824: 
1.556     albertel 10825: sub format_name {
                   10826:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10827:     my $name;
                   10828:     if ($first ne 'lastname') {
                   10829: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10830:     } else {
                   10831: 	if ($lastname=~/\S/) {
                   10832: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10833: 	    $name=~s/\s+,/,/;
                   10834: 	} else {
                   10835: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10836: 	}
                   10837:     }
                   10838:     $name=~s/^\s+//;
                   10839:     $name=~s/\s+$//;
                   10840:     $name=~s/\s+/ /g;
                   10841:     return $name;
                   10842: }
                   10843: 
1.84      www      10844: # ------------------------------------------------- Write to course preferences
                   10845: 
                   10846: sub writecoursepref {
                   10847:     my ($courseid,%prefs)=@_;
                   10848:     $courseid=~s/^\///;
                   10849:     $courseid=~s/\_/\//g;
                   10850:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10851:     my $chome=homeserver($cnum,$cdomain);
                   10852:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10853: 	return 'error: no such course';
                   10854:     }
                   10855:     my $cstring='';
1.800     albertel 10856:     foreach my $pref (keys(%prefs)) {
                   10857: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10858:     }
1.84      www      10859:     $cstring=~s/\&$//;
                   10860:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10861: }
                   10862: 
                   10863: # ---------------------------------------------------------- Make/modify course
                   10864: 
                   10865: sub createcourse {
1.741     raeburn  10866:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1423    raeburn  10867:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10868:     $url=&declutter($url);
                   10869:     my $cid='';
1.1028    raeburn  10870:     if ($context eq 'requestcourses') {
                   10871:         my $can_create = 0;
                   10872:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10873:         if ($udom eq $ownerdom) {
1.1423    raeburn  10874:             my $reload;
                   10875:             if (($callercontext eq 'auto') &&
                   10876:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10877:                 $reload = 'reload';
                   10878:             }
                   10879:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10880:                                   $context)) {
                   10881:                 $can_create = 1;
                   10882:             }
                   10883:         } else {
                   10884:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10885:                                            $category);
                   10886:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10887:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10888:                 if (@curr > 0) {
                   10889:                     my @options = qw(approval validate autolimit);
                   10890:                     my $optregex = join('|',@options);
                   10891:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10892:                         $can_create = 1;
                   10893:                     }
                   10894:                 }
                   10895:             }
                   10896:         }
                   10897:         if ($can_create) {
                   10898:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10899:                 unless (&allowed('ccc',$udom)) {
                   10900:                     return 'refused'; 
                   10901:                 }
1.1017    raeburn  10902:             }
                   10903:         } else {
                   10904:             return 'refused';
                   10905:         }
1.1028    raeburn  10906:     } elsif (!&allowed('ccc',$udom)) {
                   10907:         return 'refused';
1.84      www      10908:     }
1.1011    raeburn  10909: # --------------------------------------------------------------- Get Unique ID
                   10910:     my $uname;
                   10911:     if ($cnum =~ /^$match_courseid$/) {
                   10912:         my $chome=&homeserver($cnum,$udom,'true');
                   10913:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10914:             $uname = $cnum;
                   10915:         } else {
1.1038    raeburn  10916:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10917:         }
                   10918:     } else {
1.1038    raeburn  10919:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10920:     }
                   10921:     return $uname if ($uname =~ /^error/);
                   10922: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10923:     if (!defined($course_server)) {
                   10924:         if (defined(&domain($udom,'primary'))) {
                   10925:             $course_server = &domain($udom,'primary');
                   10926:         } else {
                   10927:             $course_server = $env{'user.home'}; 
                   10928:         }
                   10929:     }
                   10930:     my %host_servers =
                   10931:         &Apache::lonnet::get_servers($udom,'library');
                   10932:     unless ($host_servers{$course_server}) {
                   10933:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10934:     }
1.84      www      10935: # ------------------------------------------------------------- Make the course
                   10936:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10937:                       $course_server);
1.84      www      10938:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10939:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10940:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10941: 	return 'error: no such course';
                   10942:     }
1.271     www      10943: # ----------------------------------------------------------------- Course made
1.516     raeburn  10944: # log existence
1.1029    raeburn  10945:     my $now = time;
1.918     raeburn  10946:     my $newcourse = {
                   10947:                     $udom.'_'.$uname => {
1.921     raeburn  10948:                                      description => $description,
                   10949:                                      inst_code   => $inst_code,
                   10950:                                      owner       => $course_owner,
                   10951:                                      type        => $crstype,
1.1029    raeburn  10952:                                      creator     => $env{'user.name'}.':'.
                   10953:                                                     $env{'user.domain'},
                   10954:                                      created     => $now,
                   10955:                                      context     => $context,
1.918     raeburn  10956:                                                 },
                   10957:                     };
1.921     raeburn  10958:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10959: # set toplevel url
1.271     www      10960:     my $topurl=$url;
                   10961:     unless ($nonstandard) {
                   10962: # ------------------------------------------ For standard courses, make top url
                   10963:         my $mapurl=&clutter($url);
1.278     www      10964:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10965:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10966: <map>
                   10967: <resource id="1" type="start"></resource>
                   10968: <resource id="2" src="$mapurl"></resource>
                   10969: <resource id="3" type="finish"></resource>
                   10970: <link index="1" from="1" to="2"></link>
                   10971: <link index="2" from="2" to="3"></link>
                   10972: </map>
                   10973: ENDINITMAP
                   10974:         $topurl=&declutter(
1.638     albertel 10975:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10976:                           );
                   10977:     }
                   10978: # ----------------------------------------------------------- Write preferences
1.84      www      10979:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10980:                      ('description'              => $description,
                   10981:                       'url'                      => $topurl,
                   10982:                       'internal.creator'         => $env{'user.name'}.':'.
                   10983:                                                     $env{'user.domain'},
                   10984:                       'internal.created'         => $now,
                   10985:                       'internal.creationcontext' => $context)
                   10986:                     );
1.84      www      10987:     return '/'.$udom.'/'.$uname;
                   10988: }
                   10989: 
1.1011    raeburn  10990: # ------------------------------------------------------------------- Create ID
                   10991: sub generate_coursenum {
1.1038    raeburn  10992:     my ($udom,$crstype) = @_;
1.1011    raeburn  10993:     my $domdesc = &domain($udom);
                   10994:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10995:     my $first;
                   10996:     if ($crstype eq 'Community') {
                   10997:         $first = '0';
                   10998:     } else {
                   10999:         $first = int(1+rand(9)); 
                   11000:     } 
                   11001:     my $uname=$first.
1.1011    raeburn  11002:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11003:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11004:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11005: # ----------------------------------------------- Make sure that does not exist
                   11006:     my $uhome=&homeserver($uname,$udom,'true');
                   11007:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  11008:         if ($crstype eq 'Community') {
                   11009:             $first = '0';
                   11010:         } else {
                   11011:             $first = int(1+rand(9));
                   11012:         }
                   11013:         $uname=$first.
1.1011    raeburn  11014:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11015:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11016:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11017:         $uhome=&homeserver($uname,$udom,'true');
                   11018:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   11019:             return 'error: unable to generate unique course-ID';
                   11020:         }
                   11021:     }
                   11022:     return $uname;
                   11023: }
                   11024: 
1.813     albertel 11025: sub is_course {
1.1167    droeschl 11026:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   11027:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   11028: 
1.1381    raeburn  11029:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   11030:     my $uhome=&homeserver($cnum,$cdom);
                   11031:     my $iscourse;
                   11032:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  11033:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  11034:     } else {
                   11035:         my $hashid = $cdom.':'.$cnum;
                   11036:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   11037:         unless (defined($cached)) {
                   11038:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   11039:                                         $cnum,undef,undef,'.');
                   11040:             $iscourse = 0;
                   11041:             if (exists($courses{$cdom.'_'.$cnum})) {
                   11042:                 $iscourse = 1;
                   11043:             }
                   11044:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   11045:         }
                   11046:     }
                   11047:     return unless ($iscourse);
1.1167    droeschl 11048:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 11049: }
                   11050: 
1.1015    raeburn  11051: sub store_userdata {
                   11052:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  11053:     my $result;
1.1016    raeburn  11054:     if ($datakey ne '') {
1.1013    raeburn  11055:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  11056:             if ($udom eq '' || $uname eq '') {
                   11057:                 $udom = $env{'user.domain'};
                   11058:                 $uname = $env{'user.name'};
                   11059:             }
                   11060:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  11061:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   11062:                 $result = 'error: no_host';
                   11063:             } else {
1.1434    raeburn  11064:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  11065:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   11066: 
                   11067:                 my $namevalue='';
                   11068:                 foreach my $key (keys(%{$storehash})) {
                   11069:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   11070:                 }
                   11071:                 $namevalue=~s/\&$//;
1.1224    raeburn  11072:                 unless ($namespace eq 'courserequests') {
                   11073:                     $datakey = &escape($datakey);
                   11074:                 }
1.1105    raeburn  11075:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   11076:                                   $namevalue,$uhome);
1.1013    raeburn  11077:             }
                   11078:         } else {
                   11079:             $result = 'error: data to store was not a hash reference'; 
                   11080:         }
                   11081:     } else {
                   11082:         $result= 'error: invalid requestkey'; 
                   11083:     }
                   11084:     return $result;
                   11085: }
                   11086: 
1.21      www      11087: # ---------------------------------------------------------- Assign Custom Role
                   11088: 
                   11089: sub assigncustomrole {
1.957     raeburn  11090:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11091:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  11092:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      11093: }
                   11094: 
                   11095: # ----------------------------------------------------------------- Revoke Role
                   11096: 
                   11097: sub revokerole {
1.957     raeburn  11098:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11099:     my $now=time;
1.965     raeburn  11100:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      11101: }
                   11102: 
                   11103: # ---------------------------------------------------------- Revoke Custom Role
                   11104: 
                   11105: sub revokecustomrole {
1.957     raeburn  11106:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11107:     my $now=time;
1.357     www      11108:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  11109:            $deleteflag,$selfenroll,$context);
1.17      www      11110: }
                   11111: 
1.533     banghart 11112: # ------------------------------------------------------------ Disk usage
1.535     albertel 11113: sub diskusage {
1.955     raeburn  11114:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   11115:     $directorypath =~ s/\/$//;
                   11116:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   11117:                        .&escape($getpropath).':'.&escape($uname).':'
                   11118:                        .&escape($udom),homeserver($uname,$udom));
                   11119:     if ($listing eq 'unknown_cmd') {
                   11120:         if ($getpropath) {
                   11121:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   11122:         }
                   11123:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   11124:     }
1.514     albertel 11125:     return $listing;
1.512     banghart 11126: }
                   11127: 
1.566     banghart 11128: sub is_locked {
1.1096    raeburn  11129:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 11130:     my @check;
                   11131:     my $is_locked;
1.1093    raeburn  11132:     push (@check,$file_name);
1.613     albertel 11133:     my %locked = &get('file_permissions',\@check,
1.620     albertel 11134: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 11135:     my ($tmp)=keys(%locked);
                   11136:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  11137:     
1.566     banghart 11138:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  11139:         $is_locked = 'false';
                   11140:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  11141:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  11142:                $is_locked = 'true';
1.1096    raeburn  11143:                if (ref($which) eq 'ARRAY') {
                   11144:                    push(@{$which},$entry);
                   11145:                } else {
                   11146:                    last;
                   11147:                }
1.745     raeburn  11148:            }
                   11149:        }
1.566     banghart 11150:     } else {
                   11151:         $is_locked = 'false';
                   11152:     }
1.1093    raeburn  11153:     return $is_locked;
1.566     banghart 11154: }
                   11155: 
1.759     albertel 11156: sub declutter_portfile {
                   11157:     my ($file) = @_;
1.833     albertel 11158:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 11159:     return $file;
                   11160: }
                   11161: 
1.559     banghart 11162: # ------------------------------------------------------------- Mark as Read Only
                   11163: 
                   11164: sub mark_as_readonly {
                   11165:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 11166:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11167:     my ($tmp)=keys(%current_permissions);
                   11168:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 11169:     foreach my $file (@{$files}) {
1.759     albertel 11170: 	$file = &declutter_portfile($file);
1.561     banghart 11171:         push(@{$current_permissions{$file}},$what);
1.559     banghart 11172:     }
1.613     albertel 11173:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11174:     return;
                   11175: }
                   11176: 
1.572     banghart 11177: # ------------------------------------------------------------Save Selected Files
                   11178: 
                   11179: sub save_selected_files {
                   11180:     my ($user, $path, @files) = @_;
                   11181:     my $filename = $user."savedfiles";
1.573     banghart 11182:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  11183:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 11184:     foreach my $file (@files) {
1.620     albertel 11185:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 11186:     }
                   11187:     foreach my $file (@other_files) {
1.574     banghart 11188:         print (OUT $file."\n");
1.572     banghart 11189:     }
1.574     banghart 11190:     close (OUT);
1.572     banghart 11191:     return 'ok';
                   11192: }
                   11193: 
1.574     banghart 11194: sub clear_selected_files {
                   11195:     my ($user) = @_;
                   11196:     my $filename = $user."savedfiles";
1.1359    raeburn  11197:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 11198:     print (OUT undef);
                   11199:     close (OUT);
                   11200:     return ("ok");    
                   11201: }
                   11202: 
1.572     banghart 11203: sub files_in_path {
                   11204:     my ($user, $path) = @_;
                   11205:     my $filename = $user."savedfiles";
                   11206:     my %return_files;
1.1359    raeburn  11207:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 11208:     while (my $line_in = <IN>) {
1.574     banghart 11209:         chomp ($line_in);
                   11210:         my @paths_and_file = split (m!/!, $line_in);
                   11211:         my $file_part = pop (@paths_and_file);
                   11212:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 11213:         $path_part.='/';
                   11214:         my $path_and_file = $path_part.$file_part;
                   11215:         if ($path_part eq $path) {
                   11216:             $return_files{$file_part}= 'selected';
                   11217:         }
                   11218:     }
1.574     banghart 11219:     close (IN);
                   11220:     return (\%return_files);
1.572     banghart 11221: }
                   11222: 
                   11223: # called in portfolio select mode, to show files selected NOT in current directory
                   11224: sub files_not_in_path {
                   11225:     my ($user, $path) = @_;
                   11226:     my $filename = $user."savedfiles";
                   11227:     my @return_files;
                   11228:     my $path_part;
1.1359    raeburn  11229:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 11230:     while (my $line = <IN>) {
1.572     banghart 11231:         #ok, I know it's clunky, but I want it to work
1.800     albertel 11232:         my @paths_and_file = split(m|/|, $line);
                   11233:         my $file_part = pop(@paths_and_file);
                   11234:         chomp($file_part);
                   11235:         my $path_part = join('/', @paths_and_file);
1.572     banghart 11236:         $path_part .= '/';
                   11237:         my $path_and_file = $path_part.$file_part;
                   11238:         if ($path_part ne $path) {
1.800     albertel 11239:             push(@return_files, ($path_and_file));
1.572     banghart 11240:         }
                   11241:     }
1.800     albertel 11242:     close(OUT);
1.574     banghart 11243:     return (@return_files);
1.572     banghart 11244: }
                   11245: 
1.1273    raeburn  11246: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   11247:  
                   11248: sub portfiles_versioning {
                   11249:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   11250:     my $portfolio_root = '/userfiles/portfolio';
                   11251:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   11252:     foreach my $file (@{$portfiles}) {
                   11253:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   11254:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   11255:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   11256:         my $getpropath = 1;
                   11257:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   11258:                                              $stu_name,$getpropath);
                   11259:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   11260:         my $new_answer = 
                   11261:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   11262:         if ($new_answer ne 'problem getting file') {
                   11263:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   11264:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   11265:                               [$symb,$env{'request.course.id'},'graded']);
                   11266:         }
                   11267:     }
                   11268: }
                   11269: 
                   11270: sub get_next_version {
                   11271:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   11272:     my $version;
                   11273:     if (ref($dir_list) eq 'ARRAY') {
                   11274:         foreach my $row (@{$dir_list}) {
                   11275:             my ($file) = split(/\&/,$row,2);
                   11276:             my ($file_name,$file_version,$file_ext) =
                   11277:                 &file_name_version_ext($file);
                   11278:             if (($file_name eq $answer_name) &&
                   11279:                 ($file_ext eq $answer_ext)) {
                   11280:                      # gets here if filename and extension match,
                   11281:                      # regardless of version
                   11282:                 if ($file_version ne '') {
                   11283:                     # a versioned file is found  so save it for later
                   11284:                     if ($file_version > $version) {
                   11285:                         $version = $file_version;
                   11286:                     }
                   11287:                 }
                   11288:             }
                   11289:         }
                   11290:     }
                   11291:     $version ++;
                   11292:     return($version);
                   11293: }
                   11294: 
                   11295: sub version_selected_portfile {
                   11296:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   11297:     my ($answer_name,$answer_ver,$answer_ext) =
                   11298:         &file_name_version_ext($file_name);
                   11299:     my $new_answer;
                   11300:     $env{'form.copy'} =
                   11301:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   11302:     if($env{'form.copy'} eq '-1') {
                   11303:         $new_answer = 'problem getting file';
                   11304:     } else {
                   11305:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   11306:         my $copy_result = 
                   11307:             &finishuserfileupload($stu_name,$domain,'copy',
                   11308:                                   '/portfolio'.$directory.$new_answer);
                   11309:     }
                   11310:     undef($env{'form.copy'});
                   11311:     return ($new_answer);
                   11312: }
                   11313: 
                   11314: sub file_name_version_ext {
                   11315:     my ($file)=@_;
                   11316:     my @file_parts = split(/\./, $file);
                   11317:     my ($name,$version,$ext);
                   11318:     if (@file_parts > 1) {
                   11319:         $ext=pop(@file_parts);
                   11320:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   11321:             $version=pop(@file_parts);
                   11322:         }
                   11323:         $name=join('.',@file_parts);
                   11324:     } else {
                   11325:         $name=join('.',@file_parts);
                   11326:     }
                   11327:     return($name,$version,$ext);
                   11328: }
                   11329: 
1.745     raeburn  11330: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11331: 
1.745     raeburn  11332: sub get_portfile_permissions {
                   11333:     my ($domain,$user) = @_;
1.613     albertel 11334:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11335:     my ($tmp)=keys(%current_permissions);
                   11336:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11337:     return \%current_permissions;
                   11338: }
                   11339: 
                   11340: #---------------------------------------------Get portfolio file access controls
                   11341: 
1.749     raeburn  11342: sub get_access_controls {
1.745     raeburn  11343:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11344:     my %access;
                   11345:     my $real_file = $file;
                   11346:     $file =~ s/\.meta$//;
1.745     raeburn  11347:     if (defined($file)) {
1.749     raeburn  11348:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11349:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11350:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11351:             }
                   11352:         }
1.745     raeburn  11353:     } else {
1.749     raeburn  11354:         foreach my $key (keys(%{$current_permissions})) {
                   11355:             if ($key =~ /\0accesscontrol$/) {
                   11356:                 if (defined($group)) {
                   11357:                     if ($key !~ m-^\Q$group\E/-) {
                   11358:                         next;
                   11359:                     }
                   11360:                 }
                   11361:                 my ($fullpath) = split(/\0/,$key);
                   11362:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11363:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11364:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11365:                     }
                   11366:                 }
                   11367:             }
                   11368:         }
                   11369:     }
                   11370:     return %access;
                   11371: }
                   11372: 
                   11373: sub modify_access_controls {
                   11374:     my ($file_name,$changes,$domain,$user)=@_;
                   11375:     my ($outcome,$deloutcome);
                   11376:     my %store_permissions;
                   11377:     my %new_values;
                   11378:     my %new_control;
                   11379:     my %translation;
                   11380:     my @deletions = ();
                   11381:     my $now = time;
                   11382:     if (exists($$changes{'activate'})) {
                   11383:         if (ref($$changes{'activate'}) eq 'HASH') {
                   11384:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   11385:             my $numnew = scalar(@newitems);
                   11386:             for (my $i=0; $i<$numnew; $i++) {
                   11387:                 my $newkey = $newitems[$i];
                   11388:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  11389:                 if ($newkey =~ /^\d+:/) { 
                   11390:                     $newkey =~ s/^(\d+)/$newid/;
                   11391:                     $translation{$1} = $newid;
                   11392:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   11393:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   11394:                     $translation{$1} = $newid;
                   11395:                 }
1.749     raeburn  11396:                 $new_values{$file_name."\0".$newkey} = 
                   11397:                                           $$changes{'activate'}{$newitems[$i]};
                   11398:                 $new_control{$newkey} = $now;
                   11399:             }
                   11400:         }
                   11401:     }
                   11402:     my %todelete;
                   11403:     my %changed_items;
                   11404:     foreach my $action ('delete','update') {
                   11405:         if (exists($$changes{$action})) {
                   11406:             if (ref($$changes{$action}) eq 'HASH') {
                   11407:                 foreach my $key (keys(%{$$changes{$action}})) {
                   11408:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   11409:                     if ($action eq 'delete') { 
                   11410:                         $todelete{$itemnum} = 1;
                   11411:                     } else {
                   11412:                         $changed_items{$itemnum} = $key;
                   11413:                     }
                   11414:                 }
1.745     raeburn  11415:             }
                   11416:         }
1.749     raeburn  11417:     }
                   11418:     # get lock on access controls for file.
                   11419:     my $lockhash = {
                   11420:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   11421:                                                        ':'.$env{'user.domain'},
                   11422:                    }; 
                   11423:     my $tries = 0;
                   11424:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11425:    
1.1288    damieng  11426:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  11427:         $tries ++;
1.1289    damieng  11428:         sleep(0.1);
1.749     raeburn  11429:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11430:     }
                   11431:     if ($gotlock eq 'ok') {
                   11432:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   11433:         my ($tmp)=keys(%curr_permissions);
                   11434:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   11435:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   11436:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   11437:             if (ref($curr_controls) eq 'HASH') {
                   11438:                 foreach my $control_item (keys(%{$curr_controls})) {
                   11439:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   11440:                     if (defined($todelete{$itemnum})) {
                   11441:                         push(@deletions,$file_name."\0".$control_item);
                   11442:                     } else {
                   11443:                         if (defined($changed_items{$itemnum})) {
                   11444:                             $new_control{$changed_items{$itemnum}} = $now;
                   11445:                             push(@deletions,$file_name."\0".$control_item);
                   11446:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   11447:                         } else {
                   11448:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   11449:                         }
                   11450:                     }
1.745     raeburn  11451:                 }
                   11452:             }
                   11453:         }
1.970     raeburn  11454:         my ($group);
                   11455:         if (&is_course($domain,$user)) {
                   11456:             ($group,my $file) = split(/\//,$file_name,2);
                   11457:         }
1.749     raeburn  11458:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   11459:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   11460:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   11461:         #  remove lock
                   11462:         my @del_lock = ($file_name."\0".'locked_access_records');
                   11463:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  11464:         my $sqlresult =
1.970     raeburn  11465:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  11466:                                     $group);
1.749     raeburn  11467:     } else {
                   11468:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  11469:     }
1.749     raeburn  11470:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  11471: }
                   11472: 
1.827     raeburn  11473: sub make_public_indefinitely {
1.1271    raeburn  11474:     my (@requrl) = @_;
                   11475:     return &automated_portfile_access('public',\@requrl);
                   11476: }
                   11477: 
                   11478: sub automated_portfile_access {
                   11479:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  11480:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   11481:         return 'invalid';
                   11482:     }
1.1271    raeburn  11483:     my %urls;
                   11484:     if (ref($addsref) eq 'ARRAY') {
                   11485:         foreach my $requrl (@{$addsref}) {
                   11486:             if (&is_portfolio_url($requrl)) {
                   11487:                 unless (exists($urls{$requrl})) {
                   11488:                     $urls{$requrl} = 'add';
                   11489:                 }
                   11490:             }
                   11491:         }
                   11492:     }
                   11493:     if (ref($delsref) eq 'ARRAY') {
                   11494:         foreach my $requrl (@{$delsref}) { 
                   11495:             if (&is_portfolio_url($requrl)) {
                   11496:                 unless (exists($urls{$requrl})) {
                   11497:                     $urls{$requrl} = 'delete'; 
                   11498:                 }
                   11499:             }
                   11500:         }
                   11501:     }
                   11502:     unless (keys(%urls)) {
                   11503:         return 'invalid';
                   11504:     }
                   11505:     my $ip;
                   11506:     if ($accesstype eq 'ip') {
                   11507:         if (ref($info) eq 'HASH') {
                   11508:             if ($info->{'ip'} ne '') {
                   11509:                 $ip = $info->{'ip'};
                   11510:             }
                   11511:         }
                   11512:         if ($ip eq '') {
                   11513:             return 'invalid';
                   11514:         }
                   11515:     }
                   11516:     my $errors;
1.827     raeburn  11517:     my $now = time;
1.1271    raeburn  11518:     my %current_perms;
                   11519:     foreach my $requrl (sort(keys(%urls))) {
                   11520:         my $action;
                   11521:         if ($urls{$requrl} eq 'add') {
                   11522:             $action = 'activate';
                   11523:         } else {
                   11524:             $action = 'none';
                   11525:         }
                   11526:         my $aclnum = 0;
1.827     raeburn  11527:         my (undef,$udom,$unum,$file_name,$group) =
                   11528:             &parse_portfolio_url($requrl);
1.1271    raeburn  11529:         unless (exists($current_perms{$unum.':'.$udom})) {
                   11530:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   11531:         }
                   11532:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  11533:                                                    $group,$file_name);
                   11534:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11535:             my ($num,$scope,$end,$start) = 
                   11536:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  11537:             if ($scope eq $accesstype) {
                   11538:                 if (($start <= $now) && ($end == 0)) {
                   11539:                     if ($accesstype eq 'ip') {
                   11540:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   11541:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   11542:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   11543:                                     if ($urls{$requrl} eq 'add') {
                   11544:                                         $action = 'none';
                   11545:                                         last;
                   11546:                                     } else {
                   11547:                                         $action = 'delete';
                   11548:                                         $aclnum = $num;
                   11549:                                         last;
                   11550:                                     }
                   11551:                                 }
                   11552:                             }
                   11553:                         }
                   11554:                     } elsif ($accesstype eq 'public') {
                   11555:                         if ($urls{$requrl} eq 'add') {
                   11556:                             $action = 'none';
                   11557:                             last;
                   11558:                         } else {
                   11559:                             $action = 'delete';
                   11560:                             $aclnum = $num;
                   11561:                             last;
                   11562:                         }
                   11563:                     }
                   11564:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  11565:                     $action = 'update';
                   11566:                     $aclnum = $num;
1.1271    raeburn  11567:                     last;
1.827     raeburn  11568:                 }
                   11569:             }
                   11570:         }
                   11571:         if ($action eq 'none') {
1.1271    raeburn  11572:             next;
1.827     raeburn  11573:         } else {
                   11574:             my %changes;
                   11575:             my $newend = 0;
                   11576:             my $newstart = $now;
1.1271    raeburn  11577:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  11578:             $changes{$action}{$newkey} = {
1.1271    raeburn  11579:                 type => $accesstype,
1.827     raeburn  11580:                 time => {
                   11581:                     start => $newstart,
                   11582:                     end   => $newend,
                   11583:                 },
                   11584:             };
1.1271    raeburn  11585:             if ($accesstype eq 'ip') {
                   11586:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   11587:             }
1.827     raeburn  11588:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11589:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  11590:             unless ($outcome eq 'ok') {
                   11591:                 $errors .= $outcome.' ';
                   11592:             }
1.827     raeburn  11593:         }
1.1271    raeburn  11594:     }
                   11595:     if ($errors) {
                   11596:         $errors =~ s/\s$//;
                   11597:         return $errors;
1.827     raeburn  11598:     } else {
1.1271    raeburn  11599:         return 'ok';
1.827     raeburn  11600:     }
                   11601: }
                   11602: 
1.745     raeburn  11603: #------------------------------------------------------Get Marked as Read Only
                   11604: 
                   11605: sub get_marked_as_readonly {
                   11606:     my ($domain,$user,$what,$group) = @_;
                   11607:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11608:     my @readonly_files;
1.629     banghart 11609:     my $cmp1=$what;
                   11610:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11611:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11612:         if (defined($group)) {
                   11613:             if ($file_name !~ m-^\Q$group\E/-) {
                   11614:                 next;
                   11615:             }
                   11616:         }
1.561     banghart 11617:         if (ref($value) eq "ARRAY"){
                   11618:             foreach my $stored_what (@{$value}) {
1.629     banghart 11619:                 my $cmp2=$stored_what;
1.759     albertel 11620:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11621:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11622:                 }
1.629     banghart 11623:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11624:                     push(@readonly_files, $file_name);
1.745     raeburn  11625:                     last;
1.563     banghart 11626:                 } elsif (!defined($what)) {
                   11627:                     push(@readonly_files, $file_name);
1.745     raeburn  11628:                     last;
1.561     banghart 11629:                 }
                   11630:             }
1.745     raeburn  11631:         }
1.561     banghart 11632:     }
                   11633:     return @readonly_files;
                   11634: }
1.577     banghart 11635: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11636: 
1.577     banghart 11637: sub get_marked_as_readonly_hash {
1.745     raeburn  11638:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11639:     my %readonly_files;
1.745     raeburn  11640:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11641:         if (defined($group)) {
                   11642:             if ($file_name !~ m-^\Q$group\E/-) {
                   11643:                 next;
                   11644:             }
                   11645:         }
1.577     banghart 11646:         if (ref($value) eq "ARRAY"){
                   11647:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11648:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11649:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11650:                         if ($lock_descriptor eq 'graded') {
                   11651:                             $readonly_files{$file_name} = 'graded';
                   11652:                         } elsif ($lock_descriptor eq 'handback') {
                   11653:                             $readonly_files{$file_name} = 'handback';
                   11654:                         } else {
                   11655:                             if (!exists($readonly_files{$file_name})) {
                   11656:                                 $readonly_files{$file_name} = 'locked';
                   11657:                             }
                   11658:                         }
1.745     raeburn  11659:                     }
1.750     banghart 11660:                 } 
1.577     banghart 11661:             }
                   11662:         } 
                   11663:     }
                   11664:     return %readonly_files;
                   11665: }
1.559     banghart 11666: # ------------------------------------------------------------ Unmark as Read Only
                   11667: 
                   11668: sub unmark_as_readonly {
1.629     banghart 11669:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11670:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11671:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11672:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11673:     my $symb_crs = $what;
                   11674:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11675:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11676:     my ($tmp)=keys(%current_permissions);
                   11677:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11678:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11679:     foreach my $file (@readonly_files) {
1.759     albertel 11680: 	my $clean_file = &declutter_portfile($file);
                   11681: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11682: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11683:         my @new_locks;
                   11684:         my @del_keys;
                   11685:         if (ref($current_locks) eq "ARRAY"){
                   11686:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11687:                 my $compare=$locker;
1.749     raeburn  11688:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11689:                     $compare=join('',@{$locker});
1.746     raeburn  11690:                     if ($compare ne $symb_crs) {
                   11691:                         push(@new_locks, $locker);
                   11692:                     }
1.563     banghart 11693:                 }
                   11694:             }
1.650     albertel 11695:             if (scalar(@new_locks) > 0) {
1.563     banghart 11696:                 $current_permissions{$file} = \@new_locks;
                   11697:             } else {
                   11698:                 push(@del_keys, $file);
1.613     albertel 11699:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11700:                 delete($current_permissions{$file});
1.563     banghart 11701:             }
                   11702:         }
1.561     banghart 11703:     }
1.613     albertel 11704:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11705:     return;
                   11706: }
1.512     banghart 11707: 
1.17      www      11708: # ------------------------------------------------------------ Directory lister
                   11709: 
                   11710: sub dirlist {
1.955     raeburn  11711:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11712:     $uri=~s/^\///;
                   11713:     $uri=~s/\/$//;
1.253     stredwic 11714:     my ($udom, $uname);
1.955     raeburn  11715:     if ($getuserdir) {
1.253     stredwic 11716:         $udom = $userdomain;
                   11717:         $uname = $username;
1.955     raeburn  11718:     } else {
                   11719:         (undef,$udom,$uname)=split(/\//,$uri);
                   11720:         if(defined($userdomain)) {
                   11721:             $udom = $userdomain;
                   11722:         }
                   11723:         if(defined($username)) {
                   11724:             $uname = $username;
                   11725:         }
1.253     stredwic 11726:     }
1.955     raeburn  11727:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11728: 
1.955     raeburn  11729:     $dirRoot = $perlvar{'lonDocRoot'};
                   11730:     if (defined($getpropath)) {
                   11731:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11732:         $dirRoot =~ s/\/$//;
1.955     raeburn  11733:     } elsif (defined($getuserdir)) {
                   11734:         my $subdir=$uname.'__';
                   11735:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11736:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11737:                    ."/$udom/$subdir/$uname";
                   11738:     } elsif (defined($alternateRoot)) {
                   11739:         $dirRoot = $alternateRoot;
1.751     banghart 11740:     }
1.253     stredwic 11741: 
                   11742:     if($udom) {
                   11743:         if($uname) {
1.1135    raeburn  11744:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11745:             if ($uhome eq 'no_host') {
                   11746:                 return ([],'no_host');
                   11747:             }
1.955     raeburn  11748:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11749:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11750:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11751:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11752:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11753:             } else {
                   11754:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11755:             }
1.605     matthew  11756:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11757:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11758:                 @listing_results = split(/:/,$listing);
                   11759:             } else {
                   11760:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11761:             }
1.1135    raeburn  11762:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11763:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11764:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11765:                 return ([],$listing);
                   11766:             } else {
                   11767:                 return (\@listing_results);
1.1135    raeburn  11768:             }
1.955     raeburn  11769:         } elsif(!$alternateRoot) {
1.1136    raeburn  11770:             my (%allusers,%listerror);
1.841     albertel 11771: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11772:  	    foreach my $tryserver (keys(%servers)) {
                   11773:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11774:                                   &escape($udom),$tryserver);
                   11775:                 if ($listing eq 'unknown_cmd') {
                   11776: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11777: 				      $udom, $tryserver);
                   11778:                 } else {
                   11779:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11780:                 }
1.841     albertel 11781: 		if ($listing eq 'unknown_cmd') {
                   11782: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11783: 				      $udom, $tryserver);
                   11784: 		    @listing_results = split(/:/,$listing);
                   11785: 		} else {
                   11786: 		    @listing_results =
                   11787: 			map { &unescape($_); } split(/:/,$listing);
                   11788: 		}
1.1136    raeburn  11789:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11790:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11791:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11792:                     $listerror{$tryserver} = $listing;
                   11793:                 } else {
1.841     albertel 11794: 		    foreach my $line (@listing_results) {
                   11795: 			my ($entry) = split(/&/,$line,2);
                   11796: 			$allusers{$entry} = 1;
                   11797: 		    }
                   11798: 		}
1.253     stredwic 11799:             }
1.1136    raeburn  11800:             my @alluserslist=();
1.800     albertel 11801:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11802:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11803:             }
1.1318    droeschl 11804: 
                   11805:             if (!%listerror) {
                   11806:                 # no errors
                   11807:                 return (\@alluserslist);
                   11808:             } elsif (scalar(keys(%servers)) == 1) {
                   11809:                 # one library server, one error 
                   11810:                 my ($key) = keys(%listerror);
                   11811:                 return (\@alluserslist, $listerror{$key});
                   11812:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11813:                 # con_lost indicates that we might miss data from at least one
                   11814:                 # library server
                   11815:                 return (\@alluserslist, 'con_lost');
                   11816:             } else {
                   11817:                 # multiple library servers and no con_lost -> data should be
                   11818:                 # complete. 
                   11819:                 return (\@alluserslist);
                   11820:             }
                   11821: 
1.253     stredwic 11822:         } else {
1.1136    raeburn  11823:             return ([],'missing username');
1.253     stredwic 11824:         }
1.955     raeburn  11825:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11826:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11827:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11828:         return (\@all_domains);
1.955     raeburn  11829:     } else {
1.1136    raeburn  11830:         return ([],'missing domain');
1.275     stredwic 11831:     }
                   11832: }
                   11833: 
                   11834: # --------------------------------------------- GetFileTimestamp
                   11835: # This function utilizes dirlist and returns the date stamp for
                   11836: # when it was last modified.  It will also return an error of -1
                   11837: # if an error occurs
                   11838: 
                   11839: sub GetFileTimestamp {
1.955     raeburn  11840:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11841:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11842:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11843:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11844:                                     undef,$getuserdir);
                   11845:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11846:         return -1;
                   11847:     }
                   11848:     if (ref($fileref) eq 'ARRAY') {
                   11849:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11850:         # @stats contains first the filename, then the stat output
                   11851:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11852:     } else {
                   11853:         return -1;
1.253     stredwic 11854:     }
1.26      www      11855: }
                   11856: 
1.712     albertel 11857: sub stat_file {
                   11858:     my ($uri) = @_;
1.787     albertel 11859:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11860: 
1.955     raeburn  11861:     my ($udom,$uname,$file);
1.712     albertel 11862:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11863: 	($udom,$uname,$file) =
1.811     albertel 11864: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11865: 	$file = 'userfiles/'.$file;
                   11866:     }
                   11867:     if ($uri =~ m-^/res/-) {
                   11868: 	($udom,$uname) = 
1.807     albertel 11869: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11870: 	$file = $uri;
                   11871:     }
                   11872: 
                   11873:     if (!$udom || !$uname || !$file) {
                   11874: 	# unable to handle the uri
                   11875: 	return ();
                   11876:     }
1.956     raeburn  11877:     my $getpropath;
                   11878:     if ($file =~ /^userfiles\//) {
                   11879:         $getpropath = 1;
                   11880:     }
1.1136    raeburn  11881:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11882:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11883:         return ();
                   11884:     } else {
                   11885:         if (ref($listref) eq 'ARRAY') {
                   11886:             my @stats = split('&',$listref->[0]);
                   11887: 	    shift(@stats); #filename is first
                   11888: 	    return @stats;
                   11889:         }
1.712     albertel 11890:     }
                   11891:     return ();
                   11892: }
                   11893: 
1.1313    raeburn  11894: # --------------------------------------------------------- recursedirs
                   11895: # Recursive function to traverse either a specific user's Authoring Space
                   11896: # or corresponding Published Resource Space, and populate the hash ref:
                   11897: # $dirhashref with URLs of all directories, and if $filehashref hash
                   11898: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   11899: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   11900: # files in Authoring Space.
                   11901: #
                   11902: # Inputs:
                   11903: #
                   11904: # $is_home - true if current server is home server for user's space
                   11905: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   11906: # $docroot - Document root (i.e., /home/httpd/html
                   11907: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   11908: # $relpath - Current path (relative to top level).
                   11909: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   11910: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   11911: #
                   11912: # Returns: nothing
                   11913: #
                   11914: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   11915: #
                   11916: # Currently used by interface/londocs.pm to create linked select boxes for
                   11917: # directory and filename to import a Course "Author" resource into a course, and
                   11918: # also to create linked select boxes for Authoring Space and Directory to choose
                   11919: # save location for creation of a new "standard" problem from the Course Editor.
                   11920: #
                   11921: 
                   11922: sub recursedirs {
                   11923:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   11924:     return unless (ref($dirhashref) eq 'HASH');
                   11925:     my $currpath = $docroot.$toppath;
                   11926:     if ($relpath) {
                   11927:         $currpath .= "/$relpath";
                   11928:     }
                   11929:     my $savefile;
                   11930:     if (ref($filehashref)) {
                   11931:         $savefile = 1;
                   11932:     }
                   11933:     if ($is_home) {
                   11934:         if (opendir(my $dirh,$currpath)) {
                   11935:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   11936:                 next if ($item eq '');
                   11937:                 if (-d "$currpath/$item") {
                   11938:                     my $newpath;
                   11939:                     if ($relpath) {
                   11940:                         $newpath = "$relpath/$item";
                   11941:                     } else {
                   11942:                         $newpath = $item;
                   11943:                     }
                   11944:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11945:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11946:                 } elsif ($savefile) {
                   11947:                     if ($context eq 'priv') {
                   11948:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11949:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11950:                         }
                   11951:                     } else {
                   11952:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   11953:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11954:                         }
                   11955:                     }
                   11956:                 }
                   11957:             }
                   11958:             closedir($dirh);
                   11959:         }
                   11960:     } else {
                   11961:         my ($dirlistref,$listerror) =
                   11962:             &dirlist($toppath.$relpath);
                   11963:         my @dir_lines;
                   11964:         my $dirptr=16384;
                   11965:         if (ref($dirlistref) eq 'ARRAY') {
                   11966:             foreach my $dir_line (sort
                   11967:                               {
                   11968:                                   my ($afile)=split('&',$a,2);
                   11969:                                   my ($bfile)=split('&',$b,2);
                   11970:                                   return (lc($afile) cmp lc($bfile));
                   11971:                               } (@{$dirlistref})) {
                   11972:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   11973:                     split(/\&/,$dir_line,16);
                   11974:                 $item =~ s/\s+$//;
                   11975:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   11976:                 if ($dirptr&$testdir) {
                   11977:                     my $newpath;
                   11978:                     if ($relpath) {
                   11979:                         $newpath = "$relpath/$item";
                   11980:                     } else {
                   11981:                         $relpath = '/';
                   11982:                         $newpath = $item;
                   11983:                     }
                   11984:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11985:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11986:                 } elsif ($savefile) {
                   11987:                     if ($context eq 'priv') {
                   11988:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11989:                             $filehashref->{$relpath}{$item} = 1;
                   11990:                         }
                   11991:                     } else {
                   11992:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   11993:                             $filehashref->{$relpath}{$item} = 1;
                   11994:                         }
                   11995:                     }
                   11996:                 }
                   11997:             }
                   11998:         }
                   11999:     }
                   12000:     return;
                   12001: }
                   12002: 
1.26      www      12003: # -------------------------------------------------------- Value of a Condition
                   12004: 
1.713     albertel 12005: # gets the value of a specific preevaluated condition
                   12006: #    stored in the string  $env{user.state.<cid>}
                   12007: # or looks up a condition reference in the bighash and if if hasn't
                   12008: # already been evaluated recurses into docondval to get the value of
                   12009: # the condition, then memoizing it to 
                   12010: #   $env{user.state.<cid>.<condition>}
1.40      www      12011: sub directcondval {
                   12012:     my $number=shift;
1.620     albertel 12013:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 12014: 	&Apache::lonuserstate::evalstate();
                   12015:     }
1.713     albertel 12016:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   12017: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   12018:     } elsif ($number =~ /^_/) {
                   12019: 	my $sub_condition;
                   12020: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12021: 		&GDBM_READER(),0640)) {
                   12022: 	    $sub_condition=$bighash{'conditions'.$number};
                   12023: 	    untie(%bighash);
                   12024: 	}
                   12025: 	my $value = &docondval($sub_condition);
1.949     raeburn  12026: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 12027: 	return $value;
                   12028:     }
1.620     albertel 12029:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   12030:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      12031:     } else {
                   12032:        return 2;
                   12033:     }
                   12034: }
                   12035: 
1.713     albertel 12036: # get the collection of conditions for this resource
1.26      www      12037: sub condval {
                   12038:     my $condidx=shift;
1.54      www      12039:     my $allpathcond='';
1.713     albertel 12040:     foreach my $cond (split(/\|/,$condidx)) {
                   12041: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   12042: 	    $allpathcond.=
                   12043: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   12044: 	}
1.191     harris41 12045:     }
1.54      www      12046:     $allpathcond=~s/\|$//;
1.713     albertel 12047:     return &docondval($allpathcond);
                   12048: }
                   12049: 
                   12050: #evaluates an expression of conditions
                   12051: sub docondval {
                   12052:     my ($allpathcond) = @_;
                   12053:     my $result=0;
                   12054:     if ($env{'request.course.id'}
                   12055: 	&& defined($allpathcond)) {
                   12056: 	my $operand='|';
                   12057: 	my @stack;
                   12058: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   12059: 	    if ($chunk eq '(') {
                   12060: 		push @stack,($operand,$result);
                   12061: 	    } elsif ($chunk eq ')') {
                   12062: 		my $before=pop @stack;
                   12063: 		if (pop @stack eq '&') {
                   12064: 		    $result=$result>$before?$before:$result;
                   12065: 		} else {
                   12066: 		    $result=$result>$before?$result:$before;
                   12067: 		}
                   12068: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   12069: 		$operand=$chunk;
                   12070: 	    } else {
                   12071: 		my $new=directcondval($chunk);
                   12072: 		if ($operand eq '&') {
                   12073: 		    $result=$result>$new?$new:$result;
                   12074: 		} else {
                   12075: 		    $result=$result>$new?$result:$new;
                   12076: 		}
                   12077: 	    }
                   12078: 	}
1.26      www      12079:     }
                   12080:     return $result;
1.421     albertel 12081: }
                   12082: 
                   12083: # ---------------------------------------------------- Devalidate courseresdata
                   12084: 
                   12085: sub devalidatecourseresdata {
                   12086:     my ($coursenum,$coursedomain)=@_;
                   12087:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 12088:     &devalidate_cache_new('courseres',$hashid);
1.28      www      12089: }
                   12090: 
1.763     www      12091: 
1.200     www      12092: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     12093: #
                   12094: #  Parameters:
                   12095: #      $coursenum    - Number of the course.
                   12096: #      $coursedomain - Domain at which the course was created.
                   12097: #  Returns:
                   12098: #     A hash of the course parameters along (I think) with timestamps
                   12099: #     and version info.
1.877     foxr     12100: 
1.624     albertel 12101: sub get_courseresdata {
                   12102:     my ($coursenum,$coursedomain)=@_;
1.200     www      12103:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   12104:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 12105:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 12106:     my %dumpreply;
1.417     albertel 12107:     unless (defined($cached)) {
1.624     albertel 12108: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 12109: 	$result=\%dumpreply;
1.251     albertel 12110: 	my ($tmp) = keys(%dumpreply);
                   12111: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 12112: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 12113: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   12114: 	    return $tmp;
1.416     albertel 12115: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 12116: 	    $result=undef;
1.599     albertel 12117: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 12118: 	}
                   12119:     }
1.624     albertel 12120:     return $result;
                   12121: }
                   12122: 
1.633     albertel 12123: sub devalidateuserresdata {
                   12124:     my ($uname,$udom)=@_;
                   12125:     my $hashid="$udom:$uname";
                   12126:     &devalidate_cache_new('userres',$hashid);
                   12127: }
                   12128: 
1.624     albertel 12129: sub get_userresdata {
                   12130:     my ($uname,$udom)=@_;
                   12131:     #most student don\'t have any data set, check if there is some data
                   12132:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   12133: 
                   12134:     my $hashid="$udom:$uname";
                   12135:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   12136:     if (!defined($cached)) {
                   12137: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   12138: 	$result=\%resourcedata;
                   12139: 	&do_cache_new('userres',$hashid,$result,600);
                   12140:     }
                   12141:     my ($tmp)=keys(%$result);
                   12142:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   12143: 	return $result;
                   12144:     }
                   12145:     #error 2 occurs when the .db doesn't exist
                   12146:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  12147:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   12148: 	    &logthis("<font color=\"blue\">WARNING:".
                   12149: 		     " Trying to get resource data for ".
                   12150: 		     $uname." at ".$udom.": ".
                   12151: 		     $tmp."</font>");
                   12152:         }
1.624     albertel 12153:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 12154: 	#&EXT_cache_set($udom,$uname);
                   12155: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 12156: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 12157:     }
                   12158:     return $tmp;
                   12159: }
1.879     foxr     12160: #----------------------------------------------- resdata - return resource data
                   12161: #  Purpose:
                   12162: #    Return resource data for either users or for a course.
                   12163: #  Parameters:
                   12164: #     $name      - Course/user name.
                   12165: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  12166: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  12167: #     $mapp      - decluttered URL of enclosing map  
                   12168: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   12169: #     $recurseup - Ref to array of map URLs, starting with map containing
                   12170: #                  $mapp up through hierarchy of nested maps to top level map.  
                   12171: #     $courseid  - CourseID (first part of param identifier).
                   12172: #     $modifier  - Middle part of param identifier.
                   12173: #     $what      - Last part of param identifier.
1.879     foxr     12174: #     @which     - Array of names of resources desired.
                   12175: #  Returns:
                   12176: #     The value of the first reasource in @which that is found in the
                   12177: #     resource hash.
                   12178: #  Exceptional Conditions:
                   12179: #     If the $type passed in is not valid (not the string 'course' or 
                   12180: #     'user', an undefined  reference is returned.
                   12181: #     If none of the resources are found, an undef is returned
1.624     albertel 12182: sub resdata {
1.1301    raeburn  12183:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   12184:         $modifier,$what,@which)=@_;
1.624     albertel 12185:     my $result;
                   12186:     if ($type eq 'course') {
                   12187: 	$result=&get_courseresdata($name,$domain);
                   12188:     } elsif ($type eq 'user') {
                   12189: 	$result=&get_userresdata($name,$domain);
                   12190:     }
                   12191:     if (!ref($result)) { return $result; }    
1.251     albertel 12192:     foreach my $item (@which) {
1.1301    raeburn  12193:         if ($item->[1] eq 'course') {
                   12194:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   12195:                 unless ($$recursed) {
1.1302    raeburn  12196:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  12197:                     $$recursed = 1;
                   12198:                 }
                   12199:                 foreach my $item (@${recurseup}) {
                   12200:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   12201:                     last if (defined($result->{$norecursechk}));
                   12202:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   12203:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   12204:                 }
                   12205:             }
                   12206:         }
                   12207:         if (defined($result->{$item->[0]})) {
1.927     albertel 12208: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 12209: 	}
1.250     albertel 12210:     }
1.291     albertel 12211:     return undef;
1.200     www      12212: }
                   12213: 
1.1360    raeburn  12214: sub get_domain_lti {
                   12215:     my ($cdom,$context) = @_;
                   12216:     my ($name,%lti);
                   12217:     if ($context eq 'consumer') {
                   12218:         $name = 'ltitools';
                   12219:     } elsif ($context eq 'provider') {
                   12220:         $name = 'lti';
                   12221:     } else {
                   12222:         return %lti;
                   12223:     }
                   12224:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  12225:     if (defined($cached)) {
                   12226:         if (ref($result) eq 'HASH') {
1.1360    raeburn  12227:             %lti = %{$result};
1.1298    raeburn  12228:         }
                   12229:     } else {
1.1360    raeburn  12230:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   12231:         if (ref($domconfig{$name}) eq 'HASH') {
                   12232:             %lti = %{$domconfig{$name}};
1.1462    raeburn  12233:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
1.1360    raeburn  12234:             if (ref($encdomconfig{$name}) eq 'HASH') {
                   12235:                 foreach my $id (keys(%lti)) {
                   12236:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  12237:                         foreach my $item ('key','secret') {
1.1360    raeburn  12238:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  12239:                         }
                   12240:                     }
                   12241:                 }
                   12242:             }
1.1298    raeburn  12243:         }
                   12244:         my $cachetime = 24*60*60;
1.1360    raeburn  12245:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  12246:     }
1.1360    raeburn  12247:     return %lti;
1.1298    raeburn  12248: }
                   12249: 
1.1463    raeburn  12250: sub get_course_lti {
                   12251:     my ($cnum,$cdom) = @_;
                   12252:     my $hashid=$cdom.'_'.$cnum;
                   12253:     my %courselti;
                   12254:     my ($result,$cached)=&is_cached_new('courselti',$hashid);
                   12255:     if (defined($cached)) {
                   12256:         if (ref($result) eq 'HASH') {
                   12257:             %courselti = %{$result};
                   12258:         }
                   12259:     } else {
                   12260:         %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
                   12261:         my $cachetime = 24*60*60;
                   12262:         &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
                   12263:     }
                   12264:     return %courselti;
                   12265: }
                   12266: 
1.1236    raeburn  12267: sub get_numsuppfiles {
                   12268:     my ($cnum,$cdom,$ignorecache)=@_;
                   12269:     my $hashid=$cnum.':'.$cdom;
                   12270:     my ($suppcount,$cached);
                   12271:     unless ($ignorecache) {
                   12272:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   12273:     }
                   12274:     unless (defined($cached)) {
                   12275:         my $chome=&homeserver($cnum,$cdom);
                   12276:         unless ($chome eq 'no_host') {
1.1366    raeburn  12277:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  12278:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  12279:             ($suppcount,$supptools,$errors) =
                   12280:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   12281:                                                          $supptools,$errors);
1.1236    raeburn  12282:         }
                   12283:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   12284:     }
                   12285:     return $suppcount;
                   12286: }
                   12287: 
1.379     matthew  12288: #
                   12289: # EXT resource caching routines
                   12290: #
                   12291: 
1.1302    raeburn  12292: {
                   12293: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   12294: #
                   12295: # The course for which we cache
                   12296: my $cachedmapkey='';
                   12297: # The cached recursive maps for this course
                   12298: my %cachedmaps=();
                   12299: # When this was last done
                   12300: my $cachedmaptime='';
                   12301: 
1.379     matthew  12302: sub clear_EXT_cache_status {
1.383     albertel 12303:     &delenv('cache.EXT.');
1.379     matthew  12304: }
                   12305: 
                   12306: sub EXT_cache_status {
                   12307:     my ($target_domain,$target_user) = @_;
1.383     albertel 12308:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 12309:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  12310:         # We know already the user has no data
                   12311:         return 1;
                   12312:     } else {
                   12313:         return 0;
                   12314:     }
                   12315: }
                   12316: 
                   12317: sub EXT_cache_set {
                   12318:     my ($target_domain,$target_user) = @_;
1.383     albertel 12319:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  12320:     #&appenv({$cachename => time});
1.379     matthew  12321: }
                   12322: 
1.28      www      12323: # --------------------------------------------------------- Value of a Variable
1.58      www      12324: sub EXT {
1.715     albertel 12325: 
1.1461    raeburn  12326:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
1.68      www      12327:     unless ($varname) { return ''; }
1.218     albertel 12328:     #get real user name/domain, courseid and symb
                   12329:     my $courseid;
1.359     albertel 12330:     my $publicuser;
1.427     www      12331:     if ($symbparm) {
                   12332: 	$symbparm=&get_symb_from_alias($symbparm);
                   12333:     }
1.218     albertel 12334:     if (!($uname && $udom)) {
1.790     albertel 12335:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 12336:       if (!$symbparm) {	$symbparm=$cursymb; }
                   12337:     } else {
1.620     albertel 12338: 	$courseid=$env{'request.course.id'};
1.218     albertel 12339:     }
1.48      www      12340:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   12341:     my $rest;
1.320     albertel 12342:     if (defined($therest[0])) {
1.48      www      12343:        $rest=join('.',@therest);
                   12344:     } else {
                   12345:        $rest='';
                   12346:     }
1.320     albertel 12347: 
1.57      www      12348:     my $qualifierrest=$qualifier;
                   12349:     if ($rest) { $qualifierrest.='.'.$rest; }
                   12350:     my $spacequalifierrest=$space;
                   12351:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      12352:     if ($realm eq 'user') {
1.48      www      12353: # --------------------------------------------------------------- user.resource
                   12354: 	if ($space eq 'resource') {
1.651     albertel 12355: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   12356: 		  || defined($Apache::lonhomework::parsing_a_task))
                   12357: 		 &&
1.1469    raeburn  12358: 		 ($symbparm eq &symbread()) ) {
1.744     albertel 12359: 		# if we are in the middle of processing the resource the
                   12360: 		# get the value we are planning on committing
                   12361:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   12362:                     return $Apache::lonhomework::results{$qualifierrest};
                   12363:                 } else {
                   12364:                     return $Apache::lonhomework::history{$qualifierrest};
                   12365:                 }
1.335     albertel 12366: 	    } else {
1.359     albertel 12367: 		my %restored;
1.620     albertel 12368: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 12369: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   12370: 		} else {
                   12371: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   12372: 		}
1.335     albertel 12373: 		return $restored{$qualifierrest};
                   12374: 	    }
1.48      www      12375: # ----------------------------------------------------------------- user.access
                   12376:         } elsif ($space eq 'access') {
1.218     albertel 12377: 	    # FIXME - not supporting calls for a specific user
1.48      www      12378:             return &allowed($qualifier,$rest);
                   12379: # ------------------------------------------ user.preferences, user.environment
                   12380:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 12381: 	    if (($uname eq $env{'user.name'}) &&
                   12382: 		($udom eq $env{'user.domain'})) {
                   12383: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 12384: 	    } else {
1.359     albertel 12385: 		my %returnhash;
                   12386: 		if (!$publicuser) {
                   12387: 		    %returnhash=&userenvironment($udom,$uname,
                   12388: 						 $qualifierrest);
                   12389: 		}
1.218     albertel 12390: 		return $returnhash{$qualifierrest};
                   12391: 	    }
1.48      www      12392: # ----------------------------------------------------------------- user.course
                   12393:         } elsif ($space eq 'course') {
1.218     albertel 12394: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12395:             return $env{join('.',('request.course',$qualifier))};
1.48      www      12396: # ------------------------------------------------------------------- user.role
                   12397:         } elsif ($space eq 'role') {
1.218     albertel 12398: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12399:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      12400:             if ($qualifier eq 'value') {
                   12401: 		return $role;
                   12402:             } elsif ($qualifier eq 'extent') {
                   12403:                 return $where;
                   12404:             }
                   12405: # ----------------------------------------------------------------- user.domain
                   12406:         } elsif ($space eq 'domain') {
1.218     albertel 12407:             return $udom;
1.48      www      12408: # ------------------------------------------------------------------- user.name
                   12409:         } elsif ($space eq 'name') {
1.218     albertel 12410:             return $uname;
1.48      www      12411: # ---------------------------------------------------- Any other user namespace
1.29      www      12412:         } else {
1.359     albertel 12413: 	    my %reply;
                   12414: 	    if (!$publicuser) {
                   12415: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   12416: 	    }
                   12417: 	    return $reply{$qualifierrest};
1.48      www      12418:         }
1.236     www      12419:     } elsif ($realm eq 'query') {
                   12420: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 12421:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   12422: 						[$spacequalifierrest]);
1.620     albertel 12423: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      12424:    } elsif ($realm eq 'request') {
1.48      www      12425: # ------------------------------------------------------------- request.browser
                   12426:         if ($space eq 'browser') {
1.1145    bisitz   12427:             return $env{'browser.'.$qualifier};
1.57      www      12428: # ------------------------------------------------------------ request.filename
                   12429:         } else {
1.620     albertel 12430:             return $env{'request.'.$spacequalifierrest};
1.29      www      12431:         }
1.28      www      12432:     } elsif ($realm eq 'course') {
1.48      www      12433: # ---------------------------------------------------------- course.description
1.620     albertel 12434:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      12435:     } elsif ($realm eq 'resource') {
1.165     www      12436: 
1.620     albertel 12437: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 12438: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   12439: 	}
1.693     albertel 12440: 
1.1232    raeburn  12441:         if ($qualifier eq '') {
                   12442: 	    if ($space eq 'title') {
                   12443: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   12444: 	        return &gettitle($symbparm);
                   12445: 	    }
1.693     albertel 12446: 	
1.1232    raeburn  12447: 	    if ($space eq 'map') {
                   12448: 	        my ($map) = &decode_symb($symbparm);
                   12449: 	        return &symbread($map);
                   12450: 	    }
                   12451:             if ($space eq 'maptitle') {
                   12452:                 my ($map) = &decode_symb($symbparm);
                   12453:                 return &gettitle($map);
                   12454:             }
                   12455: 	    if ($space eq 'filename') {
                   12456: 	        if ($symbparm) {
                   12457: 		    return &clutter((&decode_symb($symbparm))[2]);
                   12458: 	        }
                   12459: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 12460: 	    }
1.1232    raeburn  12461: 
1.1233    raeburn  12462:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   12463:                 if ($space eq 'visibleparts') {
                   12464:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   12465:                     my $item;
                   12466:                     if (ref($navmap)) {
                   12467:                         my $res = $navmap->getBySymb($symbparm);
                   12468:                         my $parts = $res->parts();
                   12469:                         if (ref($parts) eq 'ARRAY') {
                   12470:                             $item = join(',',@{$parts});
                   12471:                         }
                   12472:                         undef($navmap);
1.1232    raeburn  12473:                     }
1.1233    raeburn  12474:                     return $item;
1.1232    raeburn  12475:                 }
                   12476:             }
                   12477:         }
1.693     albertel 12478: 
1.1301    raeburn  12479: 	my ($section, $group, @groups, @recurseup, $recursed);
1.1461    raeburn  12480:         if (ref($recurseupref) eq 'ARRAY') {
                   12481:             @recurseup = @{$recurseupref};
                   12482:             $recursed = 1;
                   12483:         }
1.1301    raeburn  12484: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  12485:         if (($courseid eq '') && ($cid)) {
                   12486:             $courseid = $cid;
                   12487:         }
                   12488: 	if (($symbparm && $courseid) && 
                   12489: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      12490: 
1.218     albertel 12491: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      12492: 
1.60      www      12493: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 12494: 	    my $symbp=$symbparm;
1.1301    raeburn  12495: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 12496: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  12497:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 12498: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 12499: 	    if (($env{'user.name'} eq $uname) &&
                   12500: 		($env{'user.domain'} eq $udom)) {
                   12501: 		$section=$env{'request.course.sec'};
1.733     raeburn  12502:                 @groups = split(/:/,$env{'request.course.groups'});  
                   12503:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 12504: 	    } else {
1.539     albertel 12505: 		if (! defined($usection)) {
1.551     albertel 12506: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 12507: 		} else {
                   12508: 		    $section = $usection;
                   12509: 		}
1.733     raeburn  12510:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12511: 	    }
                   12512: 
                   12513: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12514: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  12515:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 12516: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12517: 
1.593     albertel 12518: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12519: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  12520:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 12521: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12522: 
1.60      www      12523: # ----------------------------------------------------------- first, check user
1.624     albertel 12524: 
1.1301    raeburn  12525: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   12526:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 12527: 				       ([$courselevelr,'resource'],
                   12528: 					[$courselevelm,'map'     ],
1.1301    raeburn  12529:                                         [$courseleveli,'map'     ],
1.927     albertel 12530: 					[$courselevel, 'course'  ]));
1.931     albertel 12531: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12532: 
1.594     albertel 12533: # ------------------------------------------------ second, check some of course
1.684     raeburn  12534:             my $coursereply;
1.691     raeburn  12535:             if (@groups > 0) {
                   12536:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  12537:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   12538:                                        $mapp,\$recursed,\@recurseup);
                   12539:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  12540:             }
1.96      www      12541: 
1.684     raeburn  12542: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12543: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12544: 				  'course',$mapp,\$recursed,\@recurseup,
                   12545:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 12546: 				  ([$seclevelr,   'resource'],
                   12547: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  12548:                                    [$secleveli,   'map'     ],
1.927     albertel 12549: 				   [$seclevel,    'course'  ],
                   12550: 				   [$courselevelr,'resource']));
                   12551: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12552: 
1.60      www      12553: # ------------------------------------------------------ third, check map parms
1.218     albertel 12554: 	    my %parmhash=();
                   12555: 	    my $thisparm='';
                   12556: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12557: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12558: 		    &GDBM_READER(),0640)) {
1.218     albertel 12559: 		$thisparm=$parmhash{$symbparm};
                   12560: 		untie(%parmhash);
                   12561: 	    }
1.927     albertel 12562: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12563: 	}
1.594     albertel 12564: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  12565:  
                   12566:         my $what = $spacequalifierrest;
                   12567: 	$what=~s/\./\_/;
1.282     albertel 12568: 	my $filename;
                   12569: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12570: 	if ($symbparm) {
1.409     www      12571: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12572: 	} else {
1.620     albertel 12573: 	    $filename=$env{'request.filename'};
1.282     albertel 12574: 	}
1.1362    raeburn  12575:         my $toolsymb;
                   12576:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   12577:             $toolsymb = $symbparm;
                   12578:         }
                   12579: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 12580: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  12581: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 12582: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12583: 
1.1301    raeburn  12584: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 12585: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12586: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12587: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12588: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12589: 				     'course',$mapp,\$recursed,\@recurseup,
                   12590:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 12591: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  12592:                                       [$courseleveli,'map'   ],
1.927     albertel 12593: 				      [$courselevel, 'course']));
                   12594: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12595: 	}
1.145     www      12596: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12597: 	unless ($space eq '0') {
1.336     albertel 12598: 	    my @parts=split(/_/,$space);
                   12599: 	    my $id=pop(@parts);
                   12600: 	    my $part=join('_',@parts);
                   12601: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12602: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12603: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12604: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12605: 	}
1.395     albertel 12606: 	if ($recurse) { return undef; }
1.1362    raeburn  12607: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 12608: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12609: # ---------------------------------------------------- Any other user namespace
                   12610:     } elsif ($realm eq 'environment') {
                   12611: # ----------------------------------------------------------------- environment
1.620     albertel 12612: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12613: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12614: 	} else {
1.770     albertel 12615: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12616: 		return '';
                   12617: 	    }
1.219     albertel 12618: 	    my %returnhash=&userenvironment($udom,$uname,
                   12619: 					    $spacequalifierrest);
                   12620: 	    return $returnhash{$spacequalifierrest};
                   12621: 	}
1.28      www      12622:     } elsif ($realm eq 'system') {
1.48      www      12623: # ----------------------------------------------------------------- system.time
                   12624: 	if ($space eq 'time') {
                   12625: 	    return time;
                   12626:         }
1.696     albertel 12627:     } elsif ($realm eq 'server') {
                   12628: # ----------------------------------------------------------------- system.time
                   12629: 	if ($space eq 'name') {
                   12630: 	    return $ENV{'SERVER_NAME'};
                   12631:         }
1.1415    raeburn  12632:     } elsif ($realm eq 'client') {
                   12633:         if ($space eq 'remote_addr') {
1.1441    raeburn  12634:             return &get_requestor_ip();
1.1415    raeburn  12635:         }
1.28      www      12636:     }
1.48      www      12637:     return '';
1.61      www      12638: }
                   12639: 
1.927     albertel 12640: sub get_reply {
                   12641:     my ($reply_value) = @_;
1.940     raeburn  12642:     if (ref($reply_value) eq 'ARRAY') {
                   12643:         if (wantarray) {
                   12644: 	    return @$reply_value;
                   12645:         }
                   12646:         return $reply_value->[0];
                   12647:     } else {
                   12648:         return $reply_value;
1.927     albertel 12649:     }
                   12650: }
                   12651: 
1.691     raeburn  12652: sub check_group_parms {
1.1301    raeburn  12653:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   12654:         $recursed,$recurseupref) = @_;
                   12655:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   12656:                   [$what,'course']);
                   12657:     my $coursereply;
1.691     raeburn  12658:     foreach my $group (@{$groups}) {
1.1301    raeburn  12659:         my @groupitems = ();
1.691     raeburn  12660:         foreach my $level (@levels) {
1.927     albertel 12661:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12662:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12663:         }
1.1301    raeburn  12664:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12665:                                    $env{'course.'.$courseid.'.domain'},
                   12666:                                    'course',$mapp,$recursed,$recurseupref,
                   12667:                                    $courseid,'.['.$group.'].',$what,
                   12668:                                    @groupitems);
                   12669:         last if (defined($coursereply));
1.691     raeburn  12670:     }
                   12671:     return $coursereply;
                   12672: }
                   12673: 
1.1301    raeburn  12674: sub get_map_hierarchy {
1.1302    raeburn  12675:     my ($mapname,$courseid) = @_;
                   12676:     my @recurseup = ();
1.1301    raeburn  12677:     if ($mapname) {
1.1302    raeburn  12678:         if (($cachedmapkey eq $courseid) &&
                   12679:             (abs($cachedmaptime-time)<5)) {
                   12680:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12681:                 return @{$cachedmaps{$mapname}};
                   12682:             }
                   12683:         }
1.1301    raeburn  12684:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12685:         if (ref($navmap)) {
                   12686:             @recurseup = $navmap->recurseup_maps($mapname);
                   12687:             undef($navmap);
1.1302    raeburn  12688:             $cachedmaps{$mapname} = \@recurseup;
                   12689:             $cachedmaptime=time;
                   12690:             $cachedmapkey=$courseid;
1.1301    raeburn  12691:         }
                   12692:     }
                   12693:     return @recurseup;
                   12694: }
                   12695: 
1.1302    raeburn  12696: }
                   12697: 
1.691     raeburn  12698: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12699:     my ($courseid,@groups) = @_;
                   12700:     @groups = sort(@groups);
1.691     raeburn  12701:     return @groups;
                   12702: }
                   12703: 
1.395     albertel 12704: sub packages_tab_default {
1.1362    raeburn  12705:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 12706:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12707: 
                   12708:     my (@extension,@specifics,$do_default);
1.1362    raeburn  12709:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 12710: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12711: 	if ($pack_type eq 'default') {
                   12712: 	    $do_default=1;
                   12713: 	} elsif ($pack_type eq 'extension') {
                   12714: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12715: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12716: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12717: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12718: 	}
                   12719:     }
                   12720:     # first look for a package that matches the requested part id
                   12721:     foreach my $package (@specifics) {
                   12722: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12723: 	next if ($pack_part ne $part);
                   12724: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12725: 	    return $packagetab{"$pack_type&$name&default"};
                   12726: 	}
                   12727:     }
                   12728:     # look for any possible matching non extension_ package
                   12729:     foreach my $package (@specifics) {
                   12730: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12731: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12732: 	    return $packagetab{"$pack_type&$name&default"};
                   12733: 	}
1.585     albertel 12734: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12735: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12736: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12737: 	}
                   12738:     }
1.738     albertel 12739:     # look for any posible extension_ match
                   12740:     foreach my $package (@extension) {
                   12741: 	my ($package,$pack_type)=@{$package};
                   12742: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12743: 	    return $packagetab{"$pack_type&$name&default"};
                   12744: 	}
                   12745: 	if (defined($packagetab{$package."&$name&default"})) {
                   12746: 	    return $packagetab{$package."&$name&default"};
                   12747: 	}
                   12748:     }
                   12749:     # look for a global default setting
                   12750:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12751: 	return $packagetab{"default&$name&default"};
                   12752:     }
1.395     albertel 12753:     return undef;
                   12754: }
                   12755: 
1.334     albertel 12756: sub add_prefix_and_part {
                   12757:     my ($prefix,$part)=@_;
                   12758:     my $keyroot;
                   12759:     if (defined($prefix) && $prefix !~ /^__/) {
                   12760: 	# prefix that has a part already
                   12761: 	$keyroot=$prefix;
                   12762:     } elsif (defined($prefix)) {
                   12763: 	# prefix that is missing a part
                   12764: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12765:     } else {
                   12766: 	# no prefix at all
                   12767: 	if (defined($part)) { $keyroot='_'.$part; }
                   12768:     }
                   12769:     return $keyroot;
                   12770: }
                   12771: 
1.71      www      12772: # ---------------------------------------------------------------- Get metadata
                   12773: 
1.599     albertel 12774: my %metaentry;
1.1070    www      12775: my %importedpartids;
1.1369    raeburn  12776: my %importedrespids;
1.71      www      12777: sub metadata {
1.1362    raeburn  12778:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      12779:     $uri=&declutter($uri);
1.288     albertel 12780:     # if it is a non metadata possible uri return quickly
1.529     albertel 12781:     if (($uri eq '') || 
                   12782: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  12783: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12784:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12785: 	return undef;
                   12786:     }
1.1261    raeburn  12787:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12788: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12789: 	return undef;
1.288     albertel 12790:     }
1.73      www      12791:     my $filename=$uri;
                   12792:     $uri=~s/\.meta$//;
1.172     www      12793: #
                   12794: # Is the metadata already cached?
1.177     www      12795: # Look at timestamp of caching
1.172     www      12796: # Everything is cached by the main uri, libraries are never directly cached
                   12797: #
1.428     albertel 12798:     if (!defined($liburi)) {
1.599     albertel 12799: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12800: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12801:     }
1.1362    raeburn  12802: 
                   12803: #
                   12804: # If the uri is for an external tool the file from
                   12805: # which metadata should be retrieved depends on whether
                   12806: # the tool had been configured to be gradable (set in the Course
                   12807: # Editor or Resource Editor).
                   12808: #
                   12809: # If a valid symb has been included as the third arg in the call
                   12810: # to &metadata() that can be used to retrieve the value of
                   12811: # parameter_0_gradable set for the resource, and included in the
                   12812: # uploaded map containing the tool. The value is retrieved via
                   12813: # &EXT(), if a valid symb is available.  Otherwise the value of
                   12814: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  12815: # is retrieved via &get().
                   12816: #
                   12817: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   12818: # hiddenresource and encrypturl (during course initialization)
                   12819: # the map-level parameter for resource.0.gradable included in the 
                   12820: # uploaded map containing the tool will not yet have been stored
                   12821: # in the user_course_parms.db file for the user's session, so in 
                   12822: # this case fall back to retrieving gradable status from the
                   12823: # exttool_$marker.db file.
1.1362    raeburn  12824: #
                   12825: # In order to avoid an infinite loop, &metadata() will return
                   12826: # before a call to &EXT(), if the uri is for an external tool
                   12827: # and the $what for which metadata is being requested is
                   12828: # parameter_0_gradable or 0_gradable.
                   12829: #
                   12830: 
                   12831:     if ($uri =~ /ext\.tool$/) {
                   12832:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   12833:             return;
                   12834:         } else {
                   12835:             my ($checked,$use_passback);
                   12836:             if ($toolsymb ne '') {
                   12837:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  12838:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  12839:                     $checked = 1;
                   12840:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   12841:                         $use_passback = 1;
                   12842:                     }
                   12843:                 }
                   12844:             }
                   12845:             unless ($checked) {
                   12846:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   12847:                 $marker=~s/\D//g;
1.1363    raeburn  12848:                 if ($marker) {
1.1362    raeburn  12849:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   12850:                     $use_passback = $toolsettings{'gradable'};
                   12851:                 }
                   12852:             }
                   12853:             if ($use_passback) {
                   12854:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   12855:             } else {
                   12856:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   12857:             }
                   12858:         }
                   12859:     }
                   12860: 
1.428     albertel 12861:     {
1.1069    www      12862: # Imported parts would go here
1.1369    raeburn  12863:         my @origfiletagids=();
1.1069    www      12864:         my $importedparts=0;
1.1369    raeburn  12865: 
                   12866: # Imported responseids would go here
                   12867:         my $importedresponses=0;
1.172     www      12868: #
                   12869: # Is this a recursive call for a library?
                   12870: #
1.599     albertel 12871: #	if (! exists($metacache{$uri})) {
                   12872: #	    $metacache{$uri}={};
                   12873: #	}
1.924     albertel 12874: 	my $cachetime = 60*60;
1.171     www      12875:         if ($liburi) {
                   12876: 	    $liburi=&declutter($liburi);
                   12877:             $filename=$liburi;
1.401     bowersj2 12878:         } else {
1.599     albertel 12879: 	    &devalidate_cache_new('meta',$uri);
                   12880: 	    undef(%metaentry);
1.401     bowersj2 12881: 	}
1.140     www      12882:         my %metathesekeys=();
1.73      www      12883:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12884: 	my $metastring;
1.1140    www      12885: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12886: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12887: 	    $metastring = 
1.929     albertel 12888: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12889: 					  ('grade_target' => 'meta'));
                   12890: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12891: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12892:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12893: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12894: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12895: 	    $metastring=&getfile($file);
1.489     albertel 12896: 	}
1.208     albertel 12897:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12898:         my $token;
1.140     www      12899:         undef %metathesekeys;
1.71      www      12900:         while ($token=$parser->get_token) {
1.339     albertel 12901: 	    if ($token->[0] eq 'S') {
                   12902: 		if (defined($token->[2]->{'package'})) {
1.172     www      12903: #
                   12904: # This is a package - get package info
                   12905: #
1.339     albertel 12906: 		    my $package=$token->[2]->{'package'};
                   12907: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12908: 		    if (defined($token->[2]->{'id'})) { 
                   12909: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12910: 		    }
1.599     albertel 12911: 		    if ($metaentry{':packages'}) {
                   12912: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12913: 		    } else {
1.599     albertel 12914: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12915: 		    }
1.736     albertel 12916: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12917: 			my $part=$keyroot;
                   12918: 			$part=~s/^\_//;
1.736     albertel 12919: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12920: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12921: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12922: 			    # ignore package.tab specified default values
                   12923:                             # here &package_tab_default() will fetch those
                   12924: 			    if ($subp eq 'default') { next; }
1.736     albertel 12925: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12926: 			    my $unikey;
                   12927: 			    if ($pack =~ /_0$/) {
                   12928: 				$unikey='parameter_0_'.$name;
                   12929: 				$part=0;
                   12930: 			    } else {
                   12931: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12932: 			    }
1.339     albertel 12933: 			    if ($subp eq 'display') {
                   12934: 				$value.=' [Part: '.$part.']';
                   12935: 			    }
1.599     albertel 12936: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12937: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12938: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12939: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12940: 			    }
1.599     albertel 12941: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12942: 				$metaentry{':'.$unikey}=
                   12943: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12944: 			    }
1.339     albertel 12945: 			}
                   12946: 		    }
                   12947: 		} else {
1.172     www      12948: #
                   12949: # This is not a package - some other kind of start tag
1.339     albertel 12950: #
                   12951: 		    my $entry=$token->[1];
1.1068    www      12952: 		    my $unikey='';
1.175     www      12953: 
1.339     albertel 12954: 		    if ($entry eq 'import') {
1.175     www      12955: #
                   12956: # Importing a library here
1.339     albertel 12957: #
1.1067    www      12958:                         my $location=$parser->get_text('/import');
                   12959:                         my $dir=$filename;
                   12960:                         $dir=~s|[^/]*$||;
                   12961:                         $location=&filelocation($dir,$location);
1.1369    raeburn  12962: 
                   12963:                         my $importid=$token->[2]->{'id'};
1.1068    www      12964:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  12965: #
                   12966: # Check metadata for imported file to
                   12967: # see if it contained response items
                   12968: #
1.1372    raeburn  12969:                         my ($origfile,@libfilekeys);
1.1370    raeburn  12970:                         my %currmetaentry = %metaentry;
1.1372    raeburn  12971:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   12972:                                                            $depthcount+1));
                   12973:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   12974:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   12975:                                                              undef,$depthcount+1);
                   12976:                             if ($libresponseorder ne '') {
                   12977:                                 if ($#origfiletagids<0) {
                   12978:                                     undef(%importedrespids);
                   12979:                                     undef(%importedpartids);
                   12980:                                 }
1.1373    raeburn  12981:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   12982:                                 if (@respids) {
                   12983:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   12984:                                 }
                   12985:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  12986:                                     $importedresponses = 1;
1.1369    raeburn  12987: # We need to get the original file and the imported file to get the response order correct
                   12988: # Load and inspect original file
1.1372    raeburn  12989:                                     if ($#origfiletagids<0) {
                   12990:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12991:                                         $origfile=&getfile($origfilelocation);
                   12992:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12993:                                     }
1.1369    raeburn  12994:                                 }
                   12995:                             }
                   12996:                         }
1.1370    raeburn  12997: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12998: # hash populated for imported library file
                   12999:                         %metaentry = %currmetaentry;
                   13000:                         undef(%currmetaentry);
1.1374    raeburn  13001:                         if ($importmode eq 'part') {
1.1068    www      13002: # Import as part(s)
1.1069    www      13003:                            $importedparts=1;
                   13004: # We need to get the original file and the imported file to get the part order correct
                   13005: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  13006: # Load and inspect original file if we didn't do that already
                   13007:                            if ($#origfiletagids<0) {
                   13008:                                undef(%importedrespids);
                   13009:                                undef(%importedpartids);
                   13010:                                if ($origfile eq '') {
                   13011:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   13012:                                    $origfile=&getfile($origfilelocation);
                   13013:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13014:                                }
1.1070    www      13015:                            }
1.1372    raeburn  13016:                            my @impfilepartids;
                   13017: # If <partorder> tag is included in metadata for the imported file
                   13018: # get the parts in the imported file from that.
                   13019:                            if (grep(/^partorder$/,@libfilekeys)) {
                   13020:                                %currmetaentry = %metaentry;
                   13021:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   13022:                                                             $depthcount+1);
                   13023:                                %metaentry = %currmetaentry;
                   13024:                                undef(%currmetaentry);
                   13025:                                if ($libpartorder ne '') {
                   13026:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   13027:                                }
                   13028:                            } else {
                   13029: # If no <partorder> tag available, load and inspect imported file
                   13030:                                my $impfile=&getfile($location);
                   13031:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13032:                            }
1.1069    www      13033:                            if ($#impfilepartids>=0) {
                   13034: # This problem had parts
1.1070    www      13035:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      13036:                            } else {
                   13037: # Importing by turning a single problem into a problem part
                   13038: # It gets the import-tags ID as part-ID
                   13039:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      13040:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      13041:                            }
1.1068    www      13042:                         } else {
1.1374    raeburn  13043: # Import as problem or as normal import
                   13044:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13045:                             unless ($importmode eq 'problem') {
1.1068    www      13046: # Normal import
1.1374    raeburn  13047:                                 if (defined($token->[2]->{'id'})) {
                   13048:                                     $unikey.='_'.$token->[2]->{'id'};
                   13049:                                 }
                   13050:                             }
                   13051: # Check metadata for imported file to
                   13052: # see if it contained parts
                   13053:                             if (grep(/^partorder$/,@libfilekeys)) {
                   13054:                                 %currmetaentry = %metaentry;
                   13055:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   13056:                                                              $depthcount+1);
                   13057:                                 %metaentry = %currmetaentry;
                   13058:                                 undef(%currmetaentry);
                   13059:                                 if ($libpartorder ne '') {
                   13060:                                     $importedparts = 1;
                   13061:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   13062:                                 }
                   13063:                             }
1.1067    www      13064:                         }
1.339     albertel 13065: 			if ($depthcount<20) {
1.736     albertel 13066: 			    my $metadata = 
1.1362    raeburn  13067: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 13068: 					  $depthcount+1);
                   13069: 			    foreach my $meta (split(',',$metadata)) {
                   13070: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   13071: 				$metathesekeys{$meta}=1;
1.339     albertel 13072: 			    }
1.1068    www      13073:                         }
1.1067    www      13074: 		    } else {
                   13075: #
                   13076: # Not importing, some other kind of non-package, non-library start tag
                   13077: # 
                   13078:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13079:                         if (defined($token->[2]->{'id'})) {
                   13080:                             $unikey.='_'.$token->[2]->{'id'};
                   13081:                         }
1.339     albertel 13082: 			if (defined($token->[2]->{'name'})) { 
                   13083: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   13084: 			}
                   13085: 			$metathesekeys{$unikey}=1;
1.736     albertel 13086: 			foreach my $param (@{$token->[3]}) {
                   13087: 			    $metaentry{':'.$unikey.'.'.$param} =
                   13088: 				$token->[2]->{$param};
1.339     albertel 13089: 			}
                   13090: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 13091: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 13092: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   13093: 		 # only ws inside the tag, and not in default, so use default
                   13094: 		 # as value
1.599     albertel 13095: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 13096: 			} elsif ( $internaltext =~ /\S/ ) {
                   13097: 		  # something interesting inside the tag
                   13098: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 13099: 			} else {
1.908     albertel 13100: 		  # no interesting values, don't set a default
1.339     albertel 13101: 			}
1.172     www      13102: # end of not-a-package not-a-library import
1.339     albertel 13103: 		    }
1.172     www      13104: # end of not-a-package start tag
1.339     albertel 13105: 		}
1.172     www      13106: # the next is the end of "start tag"
1.339     albertel 13107: 	    }
                   13108: 	}
1.483     albertel 13109: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 13110: 	$extension = lc($extension);
                   13111: 	if ($extension eq 'htm') { $extension='html'; }
                   13112: 
1.737     albertel 13113: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 13114: 	    #no specific packages #how's our extension
                   13115: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 13116: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 13117: 					 \%metathesekeys);
                   13118: 	}
1.883     albertel 13119: 
                   13120: 	if (!exists($metaentry{':packages'})
                   13121: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 13122: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 13123: 		#no specific packages well let's get default then
                   13124: 		if ($key!~/^default&/) { next; }
1.488     albertel 13125: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 13126: 					     \%metathesekeys);
                   13127: 	    }
                   13128: 	}
1.338     www      13129: # are there custom rights to evaluate
1.599     albertel 13130: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 13131: 
1.338     www      13132:     #
                   13133:     # Importing a rights file here
1.339     albertel 13134:     #
                   13135: 	    unless ($depthcount) {
1.599     albertel 13136: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 13137: 		my $dir=$filename;
                   13138: 		$dir=~s|[^/]*$||;
                   13139: 		$location=&filelocation($dir,$location);
1.736     albertel 13140: 		my $rights_metadata =
1.1362    raeburn  13141: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 13142: 			      $depthcount+1);
                   13143: 		foreach my $rights (split(',',$rights_metadata)) {
                   13144: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   13145: 		    $metathesekeys{$rights}=1;
1.339     albertel 13146: 		}
                   13147: 	    }
                   13148: 	}
1.737     albertel 13149: 	# uniqifiy package listing
                   13150: 	my %seen;
                   13151: 	my @uniq_packages =
                   13152: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   13153: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   13154: 
1.1369    raeburn  13155:         if (($importedresponses) || ($importedparts)) {
                   13156:             if ($importedparts) {
1.1070    www      13157: # We had imported parts and need to rebuild partorder
1.1369    raeburn  13158:                 $metaentry{':partorder'}='';
                   13159:                 $metathesekeys{'partorder'}=1;
                   13160:             }
                   13161:             if ($importedresponses) {
                   13162: # We had imported responses and need to rebuil responseorder
                   13163:                 $metaentry{':responseorder'}='';
                   13164:                 $metathesekeys{'responseorder'}=1;
                   13165:             }
                   13166:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   13167:                 my $origid = $origfiletagids[$index+1];
                   13168:                 if ($origfiletagids[$index] eq 'part') {
                   13169: # Original part, part of the problem
                   13170:                     if ($importedparts) {
                   13171:                         $metaentry{':partorder'}.=','.$origid;
                   13172:                     }
                   13173:                 } elsif ($origfiletagids[$index] eq 'import') {
                   13174:                     if ($importedparts) {
                   13175: # We have imported parts at this position
1.1373    raeburn  13176:                         if ($importedpartids{$origid} ne '') {
                   13177:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   13178:                         }
1.1369    raeburn  13179:                     }
                   13180:                     if ($importedresponses) {
                   13181: # We have imported responses at this position
1.1373    raeburn  13182:                         if ($importedrespids{$origid} ne '') {
                   13183:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  13184:                         }
                   13185:                     }
                   13186:                 } else {
                   13187: # Original response item, part of the problem
                   13188:                     if ($importedresponses) {
                   13189:                         $metaentry{':responseorder'}.=','.$origid;
                   13190:                     }
                   13191:                 }
                   13192:             }
                   13193:             if ($importedparts) {
                   13194:                 $metaentry{':partorder'}=~s/^\,//;
                   13195:             }
                   13196:             if ($importedresponses) {
                   13197:                 $metaentry{':responseorder'}=~s/^\,//;
                   13198:             }
1.1070    www      13199:         }
1.737     albertel 13200: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 13201: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  13202: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  13203:         unless ($liburi) {
                   13204: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   13205:         }
1.177     www      13206: # this is the end of "was not already recently cached
1.71      www      13207:     }
1.599     albertel 13208:     return $metaentry{':'.$what};
1.261     albertel 13209: }
                   13210: 
1.488     albertel 13211: sub metadata_create_package_def {
1.483     albertel 13212:     my ($uri,$key,$package,$metathesekeys)=@_;
                   13213:     my ($pack,$name,$subp)=split(/\&/,$key);
                   13214:     if ($subp eq 'default') { next; }
                   13215:     
1.599     albertel 13216:     if (defined($metaentry{':packages'})) {
                   13217: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 13218:     } else {
1.599     albertel 13219: 	$metaentry{':packages'}=$package;
1.483     albertel 13220:     }
                   13221:     my $value=$packagetab{$key};
                   13222:     my $unikey;
                   13223:     $unikey='parameter_0_'.$name;
1.599     albertel 13224:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 13225:     $$metathesekeys{$unikey}=1;
1.599     albertel 13226:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   13227: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 13228:     }
1.599     albertel 13229:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   13230: 	$metaentry{':'.$unikey}=
                   13231: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 13232:     }
                   13233: }
                   13234: 
1.261     albertel 13235: sub metadata_generate_part0 {
                   13236:     my ($metadata,$metacache,$uri) = @_;
                   13237:     my %allnames;
1.737     albertel 13238:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 13239: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 13240: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   13241: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 13242: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 13243: 	    $allnames{$name}=$part;
                   13244: 	  }
                   13245: 	}
                   13246:     }
                   13247:     foreach my $name (keys(%allnames)) {
                   13248:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 13249:       my $key=":parameter_0_$name";
1.261     albertel 13250:       $$metacache{"$key.part"}='0';
                   13251:       $$metacache{"$key.name"}=$name;
1.428     albertel 13252:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 13253: 					   $allnames{$name}.'_'.$name.
                   13254: 					   '.type'};
1.428     albertel 13255:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 13256: 			     '.display'};
1.644     www      13257:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 13258:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 13259:       $$metacache{"$key.display"}=$olddis;
                   13260:     }
1.71      www      13261: }
                   13262: 
1.764     albertel 13263: # ------------------------------------------------------ Devalidate title cache
                   13264: 
                   13265: sub devalidate_title_cache {
                   13266:     my ($url)=@_;
                   13267:     if (!$env{'request.course.id'}) { return; }
                   13268:     my $symb=&symbread($url);
                   13269:     if (!$symb) { return; }
                   13270:     my $key=$env{'request.course.id'}."\0".$symb;
                   13271:     &devalidate_cache_new('title',$key);
                   13272: }
                   13273: 
1.1014    droeschl 13274: # ------------------------------------------------- Get the title of a course
                   13275: 
                   13276: sub current_course_title {
                   13277:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   13278: }
1.301     www      13279: # ------------------------------------------------- Get the title of a resource
                   13280: 
                   13281: sub gettitle {
                   13282:     my $urlsymb=shift;
                   13283:     my $symb=&symbread($urlsymb);
1.534     albertel 13284:     if ($symb) {
1.620     albertel 13285: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 13286: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 13287: 	if (defined($cached)) { 
                   13288: 	    return $result;
                   13289: 	}
1.534     albertel 13290: 	my ($map,$resid,$url)=&decode_symb($symb);
                   13291: 	my $title='';
1.907     albertel 13292: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   13293: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   13294: 	} else {
                   13295: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   13296: 		    &GDBM_READER(),0640)) {
                   13297: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   13298: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   13299: 		untie(%bighash);
                   13300: 	    }
1.534     albertel 13301: 	}
                   13302: 	$title=~s/\&colon\;/\:/gs;
                   13303: 	if ($title) {
1.1159    www      13304: # Remember both $symb and $title for dynamic metadata
                   13305:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      13306:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      13307: # Cache this title and then return it
1.599     albertel 13308: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 13309: 	}
                   13310: 	$urlsymb=$url;
                   13311:     }
                   13312:     my $title=&metadata($urlsymb,'title');
                   13313:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   13314:     return $title;
1.301     www      13315: }
1.613     albertel 13316: 
1.614     albertel 13317: sub get_slot {
                   13318:     my ($which,$cnum,$cdom)=@_;
                   13319:     if (!$cnum || !$cdom) {
1.790     albertel 13320: 	(undef,my $courseid)=&whichuser();
1.620     albertel 13321: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   13322: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 13323:     }
1.703     albertel 13324:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   13325:     my %slotinfo;
                   13326:     if (exists($remembered{$key})) {
                   13327: 	$slotinfo{$which} = $remembered{$key};
                   13328:     } else {
                   13329: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   13330: 	&Apache::lonhomework::showhash(%slotinfo);
                   13331: 	my ($tmp)=keys(%slotinfo);
                   13332: 	if ($tmp=~/^error:/) { return (); }
                   13333: 	$remembered{$key} = $slotinfo{$which};
                   13334:     }
1.616     albertel 13335:     if (ref($slotinfo{$which}) eq 'HASH') {
                   13336: 	return %{$slotinfo{$which}};
                   13337:     }
                   13338:     return $slotinfo{$which};
1.614     albertel 13339: }
1.1150    raeburn  13340: 
                   13341: sub get_reservable_slots {
                   13342:     my ($cnum,$cdom,$uname,$udom) = @_;
                   13343:     my $now = time;
                   13344:     my $reservable_info;
                   13345:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   13346:     if (exists($remembered{$key})) {
                   13347:         $reservable_info = $remembered{$key};
                   13348:     } else {
                   13349:         my %resv;
                   13350:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   13351:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   13352:         $reservable_info = \%resv;
                   13353:         $remembered{$key} = $reservable_info;
                   13354:     }
                   13355:     return $reservable_info;
                   13356: }
                   13357: 
                   13358: sub get_course_slots {
                   13359:     my ($cnum,$cdom) = @_;
                   13360:     my $hashid=$cnum.':'.$cdom;
                   13361:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   13362:     if (defined($cached)) {
                   13363:         if (ref($result) eq 'HASH') {
                   13364:             return %{$result};
                   13365:         }
                   13366:     } else {
                   13367:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   13368:         my ($tmp) = keys(%slots);
                   13369:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  13370:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  13371:             return %slots;
                   13372:         }
                   13373:     }
                   13374:     return;
                   13375: }
                   13376: 
                   13377: sub devalidate_slots_cache {
                   13378:     my ($cnum,$cdom)=@_;
                   13379:     my $hashid=$cnum.':'.$cdom;
                   13380:     &devalidate_cache_new('allslots',$hashid);
                   13381: }
                   13382: 
1.1181    raeburn  13383: sub get_coursechange {
                   13384:     my ($cdom,$cnum) = @_;
                   13385:     if ($cdom eq '' || $cnum eq '') {
                   13386:         return unless ($env{'request.course.id'});
                   13387:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   13388:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   13389:     }
                   13390:     my $hashid=$cdom.'_'.$cnum;
                   13391:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   13392:     if ((defined($cached)) && ($change ne '')) {
                   13393:         return $change;
                   13394:     } else {
                   13395:         my %crshash;
                   13396:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   13397:         if ($crshash{'internal.contentchange'} eq '') {
                   13398:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13399:             if ($change eq '') {
                   13400:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13401:                 $change = $crshash{'internal.created'};
                   13402:             }
                   13403:         } else {
                   13404:             $change = $crshash{'internal.contentchange'};
                   13405:         }
                   13406:         my $cachetime = 600;
                   13407:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   13408:     }
                   13409:     return $change;
                   13410: }
                   13411: 
                   13412: sub devalidate_coursechange_cache {
                   13413:     my ($cnum,$cdom)=@_;
                   13414:     my $hashid=$cnum.':'.$cdom;
                   13415:     &devalidate_cache_new('crschange',$hashid);
                   13416: }
                   13417: 
1.31      www      13418: # ------------------------------------------------- Update symbolic store links
                   13419: 
                   13420: sub symblist {
                   13421:     my ($mapname,%newhash)=@_;
1.438     www      13422:     $mapname=&deversion(&declutter($mapname));
1.31      www      13423:     my %hash;
1.620     albertel 13424:     if (($env{'request.course.fn'}) && (%newhash)) {
                   13425:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 13426:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  13427: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 13428: 		next if ($url eq 'last_known'
                   13429: 			 && $env{'form.no_update_last_known'});
                   13430: 		$hash{declutter($url)}=&encode_symb($mapname,
                   13431: 						    $newhash{$url}->[1],
                   13432: 						    $newhash{$url}->[0]);
1.191     harris41 13433:             }
1.31      www      13434:             if (untie(%hash)) {
                   13435: 		return 'ok';
                   13436:             }
                   13437:         }
                   13438:     }
                   13439:     return 'error';
1.212     www      13440: }
                   13441: 
                   13442: # --------------------------------------------------------------- Verify a symb
                   13443: 
                   13444: sub symbverify {
1.1190    raeburn  13445:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      13446:     my $thisfn=$thisurl;
1.439     www      13447:     $thisfn=&declutter($thisfn);
1.215     www      13448: # direct jump to resource in page or to a sequence - will construct own symbs
                   13449:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   13450: # check URL part
1.409     www      13451:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      13452: 
1.431     www      13453:     unless ($url eq $thisfn) { return 0; }
1.213     www      13454: 
1.216     www      13455:     $symb=&symbclean($symb);
1.510     www      13456:     $thisurl=&deversion($thisurl);
1.439     www      13457:     $thisfn=&deversion($thisfn);
1.213     www      13458: 
                   13459:     my %bighash;
                   13460:     my $okay=0;
1.431     www      13461: 
1.620     albertel 13462:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13463:                             &GDBM_READER(),0640)) {
1.1032    raeburn  13464:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   13465:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  13466:             if ($map =~ m{^uploaded/.+\.page$}) {
                   13467:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   13468:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   13469:             }
                   13470:         }
                   13471:         my $ids;
1.1419    raeburn  13472:         if ($map =~ m{^uploaded/.+\.page$}) {
                   13473:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1204    raeburn  13474:         } else {
                   13475:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  13476:         }
1.1102    raeburn  13477:         unless ($ids) {
                   13478:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   13479:             $ids=$bighash{$idkey};
1.216     www      13480:         }
                   13481:         if ($ids) {
                   13482: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  13483:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  13484:                 $symb =~ s/\?.+$//;
1.1202    raeburn  13485:             }
1.800     albertel 13486: 	    foreach my $id (split(/\,/,$ids)) {
                   13487: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      13488:                if (
                   13489:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  13490:    eq $symb) {
                   13491:                    if (ref($encstate)) {
                   13492:                        $$encstate = $bighash{'encrypted_'.$id};
                   13493:                    }
1.620     albertel 13494: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  13495: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   13496:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  13497: 		       $okay=1;
1.1202    raeburn  13498:                        last;
1.582     albertel 13499: 		   }
                   13500: 	       }
1.216     www      13501: 	   }
                   13502:         }
1.213     www      13503: 	untie(%bighash);
                   13504:     }
                   13505:     return $okay;
1.31      www      13506: }
                   13507: 
1.210     www      13508: # --------------------------------------------------------------- Clean-up symb
                   13509: 
                   13510: sub symbclean {
                   13511:     my $symb=shift;
1.568     albertel 13512:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      13513: # remove version from map
                   13514:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      13515: 
1.210     www      13516: # remove version from URL
                   13517:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      13518: 
1.507     www      13519: # remove wrapper
                   13520: 
1.510     www      13521:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 13522:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      13523:     return $symb;
1.409     www      13524: }
                   13525: 
                   13526: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 13527: 
                   13528: sub encode_symb {
                   13529:     my ($map,$resid,$url)=@_;
                   13530:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   13531: }
1.409     www      13532: 
                   13533: sub decode_symb {
1.568     albertel 13534:     my $symb=shift;
                   13535:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   13536:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      13537:     return (&fixversion($map),$resid,&fixversion($url));
                   13538: }
                   13539: 
                   13540: sub fixversion {
                   13541:     my $fn=shift;
1.609     banghart 13542:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      13543:     my %bighash;
                   13544:     my $uri=&clutter($fn);
1.620     albertel 13545:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      13546: # is this cached?
1.599     albertel 13547:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      13548:     if (defined($cached)) { return $result; }
                   13549: # unfortunately not cached, or expired
1.620     albertel 13550:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      13551: 	    &GDBM_READER(),0640)) {
                   13552:  	if ($bighash{'version_'.$uri}) {
                   13553:  	    my $version=$bighash{'version_'.$uri};
1.444     www      13554:  	    unless (($version eq 'mostrecent') || 
                   13555: 		    ($version==&getversion($uri))) {
1.440     www      13556:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   13557:  	    }
                   13558:  	}
                   13559:  	untie %bighash;
1.413     www      13560:     }
1.599     albertel 13561:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      13562: }
                   13563: 
                   13564: sub deversion {
                   13565:     my $url=shift;
                   13566:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   13567:     return $url;
1.210     www      13568: }
                   13569: 
1.31      www      13570: # ------------------------------------------------------ Return symb list entry
                   13571: 
                   13572: sub symbread {
1.1424    raeburn  13573:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1427    raeburn  13574:         $ignoresymbdb,$noenccheck)=@_;
1.1265    raeburn  13575:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1427    raeburn  13576:     if (defined($env{$cache_str})) {
1.1424    raeburn  13577:         unless (ref($possibles) eq 'HASH') {
                   13578:             if ($ignorecachednull) {
                   13579:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   13580:             } else {
                   13581:                 return $env{$cache_str};
                   13582:             }
1.1282    raeburn  13583:         }
                   13584:     }
1.242     www      13585: # no filename provided? try from environment
1.1265    raeburn  13586:     unless ($thisfn) {
1.620     albertel 13587:         if ($env{'request.symb'}) {
1.1427    raeburn  13588:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 13589: 	}
1.620     albertel 13590: 	$thisfn=$env{'request.filename'};
1.44      www      13591:     }
1.569     albertel 13592:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13593: # is that filename actually a symb? Verify, clean, and return
                   13594:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13595: 	if (&symbverify($thisfn,$1)) {
1.1427    raeburn  13596: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13597: 	}
1.242     www      13598:     }
1.44      www      13599:     $thisfn=declutter($thisfn);
1.31      www      13600:     my %hash;
1.37      www      13601:     my %bighash;
                   13602:     my $syval='';
1.620     albertel 13603:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  13604:         my $targetfn = $thisfn;
1.609     banghart 13605:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  13606:             $targetfn = 'adm/wrapper/'.$thisfn;
                   13607:         }
1.687     albertel 13608: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   13609: 	    $targetfn=$1;
                   13610: 	}
1.1427    raeburn  13611:         unless ($ignoresymbdb) {
1.1424    raeburn  13612:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   13613:                           &GDBM_READER(),0640)) {
                   13614: 	        $syval=$hash{$targetfn};
                   13615:                 untie(%hash);
                   13616:             }
1.1427    raeburn  13617:             if ($syval && $checkforblock) {
                   13618:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1424    raeburn  13619:                 if (@blockers) {
                   13620:                     $syval='';
                   13621:                 }
                   13622:             }
1.37      www      13623:         }
                   13624: # ---------------------------------------------------------- There was an entry
                   13625:         if ($syval) {
1.601     albertel 13626: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13627: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13628: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13629: 		    #return $env{$cache_str}='';
1.601     albertel 13630: 		#}    
                   13631: 		#$syval.=$1;
                   13632: 	    #}
1.37      www      13633:         } else {
                   13634: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13635:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13636:                             &GDBM_READER(),0640)) {
1.37      www      13637: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13638:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13639:               unless ($ids) { 
                   13640:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13641:               }
                   13642:               unless ($ids) {
                   13643: # alias?
                   13644: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13645:               }
1.37      www      13646:               if ($ids) {
                   13647: # ------------------------------------------------------------------- Has ID(s)
                   13648:                  my @possibilities=split(/\,/,$ids);
1.39      www      13649:                  if ($#possibilities==0) {
                   13650: # ----------------------------------------------- There is only one possibility
1.37      www      13651: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13652: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13653: 						    $resid,$thisfn);
1.1282    raeburn  13654:                      if (ref($possibles) eq 'HASH') {
1.1424    raeburn  13655:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   13656:                              $possibles->{$syval} = 1;
                   13657:                          }
1.1282    raeburn  13658:                      }
                   13659:                      if ($checkforblock) {
1.1424    raeburn  13660:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1426    raeburn  13661:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1424    raeburn  13662:                              if (@blockers) {
                   13663:                                  $syval = '';
1.1425    raeburn  13664:                                  untie(%bighash);
                   13665:                                  return $env{$cache_str}='';
1.1424    raeburn  13666:                              }
1.1282    raeburn  13667:                          }
                   13668:                      }
                   13669:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      13670: # ------------------------------------------ There is more than one possibility
                   13671:                      my $realpossible=0;
1.800     albertel 13672:                      foreach my $id (@possibilities) {
                   13673: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  13674:                          my $canaccess;
                   13675:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13676:                              $canaccess = 1;
                   13677:                          } else { 
                   13678:                              $canaccess = &allowed('bre',$file);
                   13679:                          }
                   13680:                          if ($canaccess) {
                   13681:          		     my ($mapid,$resid)=split(/\./,$id);
                   13682:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13683:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13684: 						             $resid,$thisfn);
1.1424    raeburn  13685:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1426    raeburn  13686:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1282    raeburn  13687:                                  if ($checkforblock) {
1.1426    raeburn  13688:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1424    raeburn  13689:                                      if (@blockers > 0) {
                   13690:                                          $syval = '';
                   13691:                                      } else {
1.1282    raeburn  13692:                                          $syval = $poss_syval;
                   13693:                                          $realpossible++;
                   13694:                                      }
                   13695:                                  } else {
                   13696:                                      $syval = $poss_syval;
                   13697:                                      $realpossible++;
                   13698:                                  }
1.1424    raeburn  13699:                                  if ($syval) {
                   13700:                                      if (ref($possibles) eq 'HASH') {
                   13701:                                          $possibles->{$syval} = 1;
                   13702:                                      }
                   13703:                                  }
1.1282    raeburn  13704:                              }
1.39      www      13705: 			 }
1.191     harris41 13706:                      }
1.39      www      13707: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13708:                  } else {
                   13709:                      $syval='';
1.37      www      13710:                  }
                   13711: 	      }
1.1282    raeburn  13712:               untie(%bighash);
1.481     raeburn  13713:            }
1.31      www      13714:         }
1.62      www      13715:         if ($syval) {
1.1427    raeburn  13716: 	    return $env{$cache_str}=$syval;
1.62      www      13717:         }
1.31      www      13718:     }
1.949     raeburn  13719:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13720:     return $env{$cache_str}='';
1.31      www      13721: }
                   13722: 
                   13723: # ---------------------------------------------------------- Return random seed
                   13724: 
1.32      www      13725: sub numval {
                   13726:     my $txt=shift;
                   13727:     $txt=~tr/A-J/0-9/;
                   13728:     $txt=~tr/a-j/0-9/;
                   13729:     $txt=~tr/K-T/0-9/;
                   13730:     $txt=~tr/k-t/0-9/;
                   13731:     $txt=~tr/U-Z/0-5/;
                   13732:     $txt=~tr/u-z/0-5/;
                   13733:     $txt=~s/\D//g;
1.564     albertel 13734:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13735:     return int($txt);
1.368     albertel 13736: }
                   13737: 
1.484     albertel 13738: sub numval2 {
                   13739:     my $txt=shift;
                   13740:     $txt=~tr/A-J/0-9/;
                   13741:     $txt=~tr/a-j/0-9/;
                   13742:     $txt=~tr/K-T/0-9/;
                   13743:     $txt=~tr/k-t/0-9/;
                   13744:     $txt=~tr/U-Z/0-5/;
                   13745:     $txt=~tr/u-z/0-5/;
                   13746:     $txt=~s/\D//g;
                   13747:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13748:     my $total;
                   13749:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13750:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13751:     return int($total);
                   13752: }
                   13753: 
1.575     albertel 13754: sub numval3 {
                   13755:     use integer;
                   13756:     my $txt=shift;
                   13757:     $txt=~tr/A-J/0-9/;
                   13758:     $txt=~tr/a-j/0-9/;
                   13759:     $txt=~tr/K-T/0-9/;
                   13760:     $txt=~tr/k-t/0-9/;
                   13761:     $txt=~tr/U-Z/0-5/;
                   13762:     $txt=~tr/u-z/0-5/;
                   13763:     $txt=~s/\D//g;
                   13764:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13765:     my $total;
                   13766:     foreach my $val (@txts) { $total+=$val; }
                   13767:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13768:     return $total;
                   13769: }
                   13770: 
1.675     albertel 13771: sub digest {
                   13772:     my ($data)=@_;
                   13773:     my $digest=&Digest::MD5::md5($data);
                   13774:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13775:     my ($e,$f);
                   13776:     {
                   13777:         use integer;
                   13778:         $e=($a+$b);
                   13779:         $f=($c+$d);
                   13780:         if ($_64bit) {
                   13781:             $e=(($e<<32)>>32);
                   13782:             $f=(($f<<32)>>32);
                   13783:         }
                   13784:     }
                   13785:     if (wantarray) {
                   13786: 	return ($e,$f);
                   13787:     } else {
                   13788: 	my $g;
                   13789: 	{
                   13790: 	    use integer;
                   13791: 	    $g=($e+$f);
                   13792: 	    if ($_64bit) {
                   13793: 		$g=(($g<<32)>>32);
                   13794: 	    }
                   13795: 	}
                   13796: 	return $g;
                   13797:     }
                   13798: }
                   13799: 
1.368     albertel 13800: sub latest_rnd_algorithm_id {
1.675     albertel 13801:     return '64bit5';
1.366     albertel 13802: }
1.32      www      13803: 
1.503     albertel 13804: sub get_rand_alg {
                   13805:     my ($courseid)=@_;
1.790     albertel 13806:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13807:     if ($courseid) {
1.620     albertel 13808: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13809:     }
                   13810:     return &latest_rnd_algorithm_id();
                   13811: }
                   13812: 
1.562     albertel 13813: sub validCODE {
                   13814:     my ($CODE)=@_;
                   13815:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13816:     return 0;
                   13817: }
                   13818: 
1.491     albertel 13819: sub getCODE {
1.620     albertel 13820:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13821:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13822: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13823: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13824: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13825:     }
                   13826:     return undef;
                   13827: }
1.1133    foxr     13828: #
                   13829: #  Determines the random seed for a specific context:
                   13830: #
                   13831: # parameters:
                   13832: #   symb      - in course context the symb for the seed.
                   13833: #   course_id - The course id of the form domain_coursenum.
                   13834: #   domain    - Domain for the user.
                   13835: #   course    - Course for the user.
                   13836: #   cenv      - environment of the course.
                   13837: #
                   13838: # NOTE:
                   13839: #   All parameters are picked out of the environment if missing
                   13840: #   or not defined.
                   13841: #   If a symb cannot be determined the current time is used instead.
                   13842: #
                   13843: #  For a given well defined symb, courside, domain, username,
                   13844: #  and course environment, the seed is reproducible.
                   13845: #
1.31      www      13846: sub rndseed {
1.1133    foxr     13847:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13848:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13849:     if (!defined($symb)) {
1.366     albertel 13850: 	unless ($symb=$wsymb) { return time; }
                   13851:     }
1.1146    foxr     13852:     if (!defined $courseid) { 
                   13853: 	$courseid=$wcourseid; 
                   13854:     }
                   13855:     if (!defined $domain) { $domain=$wdomain; }
                   13856:     if (!defined $username) { $username=$wusername }
1.1133    foxr     13857: 
                   13858:     my $which;
                   13859:     if (defined($cenv->{'rndseed'})) {
                   13860: 	$which = $cenv->{'rndseed'};
                   13861:     } else {
                   13862: 	$which =&get_rand_alg($courseid);
                   13863:     }
1.491     albertel 13864:     if (defined(&getCODE())) {
1.1133    foxr     13865: 
1.675     albertel 13866: 	if ($which eq '64bit5') {
                   13867: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   13868: 	} elsif ($which eq '64bit4') {
1.575     albertel 13869: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   13870: 	} else {
                   13871: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   13872: 	}
1.675     albertel 13873:     } elsif ($which eq '64bit5') {
                   13874: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 13875:     } elsif ($which eq '64bit4') {
                   13876: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 13877:     } elsif ($which eq '64bit3') {
                   13878: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 13879:     } elsif ($which eq '64bit2') {
                   13880: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13881:     } elsif ($which eq '64bit') {
                   13882: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13883:     }
                   13884:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13885: }
                   13886: 
                   13887: sub rndseed_32bit {
                   13888:     my ($symb,$courseid,$domain,$username)=@_;
                   13889:     {
                   13890: 	use integer;
                   13891: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13892: 	my $symbseed=numval($symb) << 22;
                   13893: 	my $namechck=unpack("%32C*",$username) << 17;
                   13894: 	my $nameseed=numval($username) << 12;
                   13895: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13896: 	my $courseseed=unpack("%32C*",$courseid);
                   13897: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13898: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13899: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13900: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13901: 	return $num;
                   13902:     }
                   13903: }
                   13904: 
                   13905: sub rndseed_64bit {
                   13906:     my ($symb,$courseid,$domain,$username)=@_;
                   13907:     {
                   13908: 	use integer;
                   13909: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13910: 	my $symbseed=numval($symb) << 10;
                   13911: 	my $namechck=unpack("%32S*",$username);
                   13912: 	
                   13913: 	my $nameseed=numval($username) << 21;
                   13914: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13915: 	my $courseseed=unpack("%32S*",$courseid);
                   13916: 	
                   13917: 	my $num1=$symbchck+$symbseed+$namechck;
                   13918: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13919: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13920: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13921: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13922: 	return "$num1,$num2";
1.155     albertel 13923:     }
1.366     albertel 13924: }
                   13925: 
1.443     albertel 13926: sub rndseed_64bit2 {
                   13927:     my ($symb,$courseid,$domain,$username)=@_;
                   13928:     {
                   13929: 	use integer;
                   13930: 	# strings need to be an even # of cahracters long, it it is odd the
                   13931:         # last characters gets thrown away
                   13932: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13933: 	my $symbseed=numval($symb) << 10;
                   13934: 	my $namechck=unpack("%32S*",$username.' ');
                   13935: 	
                   13936: 	my $nameseed=numval($username) << 21;
1.501     albertel 13937: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13938: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13939: 	
                   13940: 	my $num1=$symbchck+$symbseed+$namechck;
                   13941: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13942: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13943: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13944: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13945: 	return "$num1,$num2";
                   13946:     }
                   13947: }
                   13948: 
                   13949: sub rndseed_64bit3 {
                   13950:     my ($symb,$courseid,$domain,$username)=@_;
                   13951:     {
                   13952: 	use integer;
                   13953: 	# strings need to be an even # of cahracters long, it it is odd the
                   13954:         # last characters gets thrown away
                   13955: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13956: 	my $symbseed=numval2($symb) << 10;
                   13957: 	my $namechck=unpack("%32S*",$username.' ');
                   13958: 	
                   13959: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13960: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13961: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13962: 	
                   13963: 	my $num1=$symbchck+$symbseed+$namechck;
                   13964: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13965: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13966: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13967: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13968: 	
1.503     albertel 13969: 	return "$num1:$num2";
1.443     albertel 13970:     }
                   13971: }
                   13972: 
1.575     albertel 13973: sub rndseed_64bit4 {
                   13974:     my ($symb,$courseid,$domain,$username)=@_;
                   13975:     {
                   13976: 	use integer;
                   13977: 	# strings need to be an even # of cahracters long, it it is odd the
                   13978:         # last characters gets thrown away
                   13979: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13980: 	my $symbseed=numval3($symb) << 10;
                   13981: 	my $namechck=unpack("%32S*",$username.' ');
                   13982: 	
                   13983: 	my $nameseed=numval3($username) << 21;
                   13984: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13985: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13986: 	
                   13987: 	my $num1=$symbchck+$symbseed+$namechck;
                   13988: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13989: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13990: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13991: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13992: 	
1.575     albertel 13993: 	return "$num1:$num2";
                   13994:     }
                   13995: }
                   13996: 
1.675     albertel 13997: sub rndseed_64bit5 {
                   13998:     my ($symb,$courseid,$domain,$username)=@_;
                   13999:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   14000:     return "$num1:$num2";
                   14001: }
                   14002: 
1.366     albertel 14003: sub rndseed_CODE_64bit {
                   14004:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 14005:     {
1.366     albertel 14006: 	use integer;
1.443     albertel 14007: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 14008: 	my $symbseed=numval2($symb);
1.491     albertel 14009: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   14010: 	my $CODEseed=numval(&getCODE());
1.443     albertel 14011: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 14012: 	my $num1=$symbseed+$CODEchck;
                   14013: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 14014: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   14015: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 14016: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   14017: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 14018: 	return "$num1:$num2";
1.366     albertel 14019:     }
                   14020: }
                   14021: 
1.575     albertel 14022: sub rndseed_CODE_64bit4 {
                   14023:     my ($symb,$courseid,$domain,$username)=@_;
                   14024:     {
                   14025: 	use integer;
                   14026: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   14027: 	my $symbseed=numval3($symb);
                   14028: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   14029: 	my $CODEseed=numval3(&getCODE());
                   14030: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14031: 	my $num1=$symbseed+$CODEchck;
                   14032: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 14033: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   14034: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 14035: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   14036: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   14037: 	return "$num1:$num2";
                   14038:     }
                   14039: }
                   14040: 
1.675     albertel 14041: sub rndseed_CODE_64bit5 {
                   14042:     my ($symb,$courseid,$domain,$username)=@_;
                   14043:     my $code = &getCODE();
                   14044:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   14045:     return "$num1:$num2";
                   14046: }
                   14047: 
1.366     albertel 14048: sub setup_random_from_rndseed {
                   14049:     my ($rndseed)=@_;
1.503     albertel 14050:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  14051:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   14052:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   14053:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   14054:         } else {
                   14055:             &Math::Random::random_set_seed($num1,$num2);
                   14056:         }
1.366     albertel 14057:     } else {
                   14058: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 14059:     }
1.36      albertel 14060: }
                   14061: 
1.474     albertel 14062: sub latest_receipt_algorithm_id {
1.835     albertel 14063:     return 'receipt3';
1.474     albertel 14064: }
                   14065: 
1.480     www      14066: sub recunique {
                   14067:     my $fucourseid=shift;
                   14068:     my $unique;
1.835     albertel 14069:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   14070: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 14071: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      14072:     } else {
                   14073: 	$unique=$perlvar{'lonReceipt'};
                   14074:     }
                   14075:     return unpack("%32C*",$unique);
                   14076: }
                   14077: 
                   14078: sub recprefix {
                   14079:     my $fucourseid=shift;
                   14080:     my $prefix;
1.835     albertel 14081:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   14082: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 14083: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      14084:     } else {
                   14085: 	$prefix=$perlvar{'lonHostID'};
                   14086:     }
                   14087:     return unpack("%32C*",$prefix);
                   14088: }
                   14089: 
1.76      www      14090: sub ireceipt {
1.474     albertel 14091:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 14092: 
                   14093:     my $return =&recprefix($fucourseid).'-';
                   14094: 
                   14095:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   14096: 	$env{'request.state'} eq 'construct') {
                   14097: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   14098: 	return $return;
                   14099:     }
                   14100: 
1.76      www      14101:     my $cuname=unpack("%32C*",$funame);
                   14102:     my $cudom=unpack("%32C*",$fudom);
                   14103:     my $cucourseid=unpack("%32C*",$fucourseid);
                   14104:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      14105:     my $cunique=&recunique($fucourseid);
1.474     albertel 14106:     my $cpart=unpack("%32S*",$part);
1.835     albertel 14107:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   14108: 
1.790     albertel 14109: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 14110: 			       
                   14111: 	$return.= ($cunique%$cuname+
                   14112: 		   $cunique%$cudom+
                   14113: 		   $cusymb%$cuname+
                   14114: 		   $cusymb%$cudom+
                   14115: 		   $cucourseid%$cuname+
                   14116: 		   $cucourseid%$cudom+
                   14117: 		   $cpart%$cuname+
                   14118: 		   $cpart%$cudom);
                   14119:     } else {
                   14120: 	$return.= ($cunique%$cuname+
                   14121: 		   $cunique%$cudom+
                   14122: 		   $cusymb%$cuname+
                   14123: 		   $cusymb%$cudom+
                   14124: 		   $cucourseid%$cuname+
                   14125: 		   $cucourseid%$cudom);
                   14126:     }
                   14127:     return $return;
1.76      www      14128: }
                   14129: 
                   14130: sub receipt {
1.474     albertel 14131:     my ($part)=@_;
1.790     albertel 14132:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 14133:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      14134: }
1.260     ng       14135: 
1.790     albertel 14136: sub whichuser {
                   14137:     my ($passedsymb)=@_;
                   14138:     my ($symb,$courseid,$domain,$name,$publicuser);
                   14139:     if (defined($env{'form.grade_symb'})) {
                   14140: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   14141: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   14142: 	if (!$allowed &&
                   14143: 	    exists($env{'request.course.sec'}) &&
                   14144: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   14145: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   14146: 			      '/'.$env{'request.course.sec'});
                   14147: 	}
                   14148: 	if ($allowed) {
                   14149: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   14150: 	    $courseid=$tmp_courseid;
                   14151: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   14152: 	    ($name)=&get_env_multiple('form.grade_username');
                   14153: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   14154: 	}
                   14155:     }
                   14156:     if (!$passedsymb) {
                   14157: 	$symb=&symbread();
                   14158:     } else {
                   14159: 	$symb=$passedsymb;
                   14160:     }
                   14161:     $courseid=$env{'request.course.id'};
                   14162:     $domain=$env{'user.domain'};
                   14163:     $name=$env{'user.name'};
                   14164:     if ($name eq 'public' && $domain eq 'public') {
                   14165: 	if (!defined($env{'form.username'})) {
                   14166: 	    $env{'form.username'}.=time.rand(10000000);
                   14167: 	}
                   14168: 	$name.=$env{'form.username'};
                   14169:     }
                   14170:     return ($symb,$courseid,$domain,$name,$publicuser);
                   14171: 
                   14172: }
                   14173: 
1.36      albertel 14174: # ------------------------------------------------------------ Serves up a file
1.472     albertel 14175: # returns either the contents of the file or 
                   14176: # -1 if the file doesn't exist
1.481     raeburn  14177: #
                   14178: # if the target is a file that was uploaded via DOCS, 
                   14179: # a check will be made to see if a current copy exists on the local server,
                   14180: # if it does this will be served, otherwise a copy will be retrieved from
                   14181: # the home server for the course and stored in /home/httpd/html/userfiles on
                   14182: # the local server.   
1.472     albertel 14183: 
1.36      albertel 14184: sub getfile {
1.538     albertel 14185:     my ($file) = @_;
1.609     banghart 14186:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 14187:     &repcopy($file);
                   14188:     return &readfile($file);
                   14189: }
                   14190: 
                   14191: sub repcopy_userfile {
                   14192:     my ($file)=@_;
1.1142    raeburn  14193:     my $londocroot = $perlvar{'lonDocRoot'};
                   14194:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  14195:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 14196:     my ($cdom,$cnum,$filename) = 
1.811     albertel 14197: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 14198:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   14199:     if (-e "$file") {
1.828     www      14200: # we already have a local copy, check it out
1.538     albertel 14201: 	my @fileinfo = stat($file);
1.828     www      14202: 	my $rtncode;
                   14203: 	my $info;
1.538     albertel 14204: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 14205: 	if ($lwpresp ne 'ok') {
1.828     www      14206: # there is no such file anymore, even though we had a local copy
1.482     albertel 14207: 	    if ($rtncode eq '404') {
1.538     albertel 14208: 		unlink($file);
1.482     albertel 14209: 	    }
                   14210: 	    return -1;
                   14211: 	}
                   14212: 	if ($info < $fileinfo[9]) {
1.828     www      14213: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  14214: 	    return 'ok';
1.828     www      14215: 	} else {
                   14216: # the file is outdated, get rid of it
                   14217: 	    unlink($file);
1.482     albertel 14218: 	}
1.828     www      14219:     }
                   14220: # one way or the other, at this point, we don't have the file
                   14221: # construct the correct path for the file
                   14222:     my @parts = ($cdom,$cnum); 
                   14223:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   14224: 	push @parts, split(/\//,$1);
                   14225:     }
                   14226:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   14227:     foreach my $part (@parts) {
                   14228: 	$path .= '/'.$part;
                   14229: 	if (!-e $path) {
                   14230: 	    mkdir($path,0770);
1.482     albertel 14231: 	}
                   14232:     }
1.828     www      14233: # now the path exists for sure
                   14234: # get a user agent
                   14235:     my $transferfile=$file.'.in.transfer';
                   14236: # FIXME: this should flock
                   14237:     if (-e $transferfile) { return 'ok'; }
                   14238:     my $request;
                   14239:     $uri=~s/^\///;
1.980     raeburn  14240:     my $homeserver = &homeserver($cnum,$cdom);
1.1398    raeburn  14241:     my $hostname = &hostname($homeserver);
1.980     raeburn  14242:     my $protocol = $protocol{$homeserver};
                   14243:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  14244:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345    raeburn  14245:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      14246: # did it work?
                   14247:     if ($response->is_error()) {
                   14248: 	unlink($transferfile);
                   14249: 	&logthis("Userfile repcopy failed for $uri");
                   14250: 	return -1;
                   14251:     }
                   14252: # worked, rename the transfer file
                   14253:     rename($transferfile,$file);
1.607     raeburn  14254:     return 'ok';
1.481     raeburn  14255: }
                   14256: 
1.517     albertel 14257: sub tokenwrapper {
                   14258:     my $uri=shift;
1.980     raeburn  14259:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 14260:     $uri=~s|^/||;
1.620     albertel 14261:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 14262:     my $token=$1;
1.552     albertel 14263:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   14264:     if ($udom && $uname && $file) {
                   14265: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  14266:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  14267:         my $homeserver = &homeserver($uname,$udom);
1.1397    raeburn  14268:         my $hostname = &hostname($homeserver);
1.980     raeburn  14269:         my $protocol = $protocol{$homeserver};
                   14270:         $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  14271:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 14272:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   14273:                                '&tokenissued='.$perlvar{'lonHostID'};
                   14274:     } else {
                   14275:         return '/adm/notfound.html';
                   14276:     }
                   14277: }
                   14278: 
1.828     www      14279: # call with reqtype HEAD: get last modification time
                   14280: # call with reqtype GET: get the file contents
                   14281: # Do not call this with reqtype GET for large files! It loads everything into memory
                   14282: #
1.481     raeburn  14283: sub getuploaded {
                   14284:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   14285:     $uri=~s/^\///;
1.980     raeburn  14286:     my $homeserver = &homeserver($cnum,$cdom);
1.1397    raeburn  14287:     my $hostname = &hostname($homeserver);
1.980     raeburn  14288:     my $protocol = $protocol{$homeserver};
                   14289:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  14290:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  14291:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  14292:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  14293:     $$rtncode = $response->code;
1.482     albertel 14294:     if (! $response->is_success()) {
                   14295: 	return 'failed';
                   14296:     }      
                   14297:     if ($reqtype eq 'HEAD') {
1.486     www      14298: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 14299:     } elsif ($reqtype eq 'GET') {
                   14300: 	$$info = $response->content;
1.472     albertel 14301:     }
1.482     albertel 14302:     return 'ok';
1.36      albertel 14303: }
                   14304: 
1.481     raeburn  14305: sub readfile {
                   14306:     my $file = shift;
                   14307:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   14308:     my $fh;
1.1359    raeburn  14309:     open($fh,"<",$file);
1.481     raeburn  14310:     my $a='';
1.800     albertel 14311:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  14312:     return $a;
                   14313: }
                   14314: 
1.36      albertel 14315: sub filelocation {
1.590     banghart 14316:     my ($dir,$file) = @_;
                   14317:     my $location;
                   14318:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 14319: 
                   14320:     if ($file =~ m-^/adm/-) {
                   14321: 	$file=~s-^/adm/wrapper/-/-;
                   14322: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   14323:     }
1.882     albertel 14324: 
1.1139    www      14325:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  14326:         $location = $file;
1.609     banghart 14327:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 14328:         my ($udom,$uname,$filename)=
1.811     albertel 14329:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 14330:         my $home=&homeserver($uname,$udom);
                   14331:         my $is_me=0;
                   14332:         my @ids=&current_machine_ids();
                   14333:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   14334:         if ($is_me) {
1.1117    foxr     14335:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 14336:         } else {
                   14337:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   14338:   	      $udom.'/'.$uname.'/'.$filename;
                   14339:         }
1.882     albertel 14340:     } elsif ($file =~ m-^/adm/-) {
                   14341: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 14342:     } else {
                   14343:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      14344:         $file=~s:^/(res|priv)/:/:;
                   14345:         my $space=$1;
1.590     banghart 14346:         if ( !( $file =~ m:^/:) ) {
                   14347:             $location = $dir. '/'.$file;
                   14348:         } else {
1.1142    raeburn  14349:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 14350:         }
1.59      albertel 14351:     }
1.590     banghart 14352:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 14353:     while ($location=~m{/\.\./}) {
                   14354: 	if ($location =~ m{/[^/]+/\.\./}) {
                   14355: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   14356: 	} else {
                   14357: 	    $location=~ s{/\.\./}{/}g;
                   14358: 	}
                   14359:     } #remove dir/..
1.590     banghart 14360:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   14361:     return $location;
1.46      www      14362: }
1.36      albertel 14363: 
1.46      www      14364: sub hreflocation {
                   14365:     my ($dir,$file)=@_;
1.980     raeburn  14366:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 14367: 	$file=filelocation($dir,$file);
1.700     albertel 14368:     } elsif ($file=~m-^/adm/-) {
                   14369: 	$file=~s-^/adm/wrapper/-/-;
                   14370: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 14371:     }
                   14372:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   14373: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   14374:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  14375: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   14376: 	        {/uploaded/$1/$2/}x;
1.46      www      14377:     }
1.913     albertel 14378:     if ($file=~ m{^/userfiles/}) {
                   14379: 	$file =~ s{^/userfiles/}{/uploaded/};
                   14380:     }
1.462     albertel 14381:     return $file;
1.465     albertel 14382: }
                   14383: 
1.1139    www      14384: 
                   14385: 
                   14386: 
                   14387: 
1.465     albertel 14388: sub current_machine_domains {
1.853     albertel 14389:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   14390: }
                   14391: 
                   14392: sub machine_domains {
                   14393:     my ($hostname) = @_;
1.465     albertel 14394:     my @domains;
1.838     albertel 14395:     my %hostname = &all_hostnames();
1.465     albertel 14396:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  14397: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 14398: 	if ($hostname eq $name) {
1.844     albertel 14399: 	    push(@domains,&host_domain($id));
1.465     albertel 14400: 	}
                   14401:     }
                   14402:     return @domains;
                   14403: }
                   14404: 
                   14405: sub current_machine_ids {
1.853     albertel 14406:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   14407: }
                   14408: 
                   14409: sub machine_ids {
                   14410:     my ($hostname) = @_;
                   14411:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 14412:     my @ids;
1.888     albertel 14413:     my %name_to_host = &all_names();
1.889     albertel 14414:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   14415: 	return @{ $name_to_host{$hostname} };
                   14416:     }
                   14417:     return;
1.31      www      14418: }
                   14419: 
1.824     raeburn  14420: sub additional_machine_domains {
                   14421:     my @domains;
1.1466    raeburn  14422:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
                   14423:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
                   14424:             while (my $line = <$fh>) {
                   14425:                 chomp($line);           
                   14426:                 $line =~ s/\s//g;
                   14427:                 push(@domains,$line);
                   14428:             }
                   14429:             close($fh);
                   14430:         }
1.824     raeburn  14431:     }
                   14432:     return @domains;
                   14433: }
                   14434: 
                   14435: sub default_login_domain {
                   14436:     my $domain = $perlvar{'lonDefDomain'};
                   14437:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   14438:     foreach my $posdom (&current_machine_domains(),
                   14439:                         &additional_machine_domains()) {
                   14440:         if (lc($posdom) eq lc($testdomain)) {
                   14441:             $domain=$posdom;
                   14442:             last;
                   14443:         }
                   14444:     }
                   14445:     return $domain;
                   14446: }
                   14447: 
1.1414    raeburn  14448: sub shared_institution {
1.1439    raeburn  14449:     my ($dom,$lonhost) = @_;
                   14450:     if ($lonhost eq '') {
                   14451:         $lonhost = $perlvar{'lonHostID'};
                   14452:     }
1.1414    raeburn  14453:     my $same_intdom;
1.1439    raeburn  14454:     my $hostintdom = &internet_dom($lonhost);
1.1414    raeburn  14455:     if ($hostintdom ne '') {
                   14456:         my %iphost = &get_iphost();
                   14457:         my $primary_id = &domain($dom,'primary');
                   14458:         my $primary_ip = &get_host_ip($primary_id);
                   14459:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   14460:             foreach my $id (@{$iphost{$primary_ip}}) {
                   14461:                 my $intdom = &internet_dom($id);
                   14462:                 if ($intdom eq $hostintdom) {
                   14463:                     $same_intdom = 1;
                   14464:                     last;
                   14465:                 }
                   14466:             }
                   14467:         }
                   14468:     }
                   14469:     return $same_intdom;
                   14470: }
                   14471: 
1.1398    raeburn  14472: sub uses_sts {
                   14473:     my ($ignore_cache) = @_;
                   14474:     my $lonhost = $perlvar{'lonHostID'};
                   14475:     my $hostname = &hostname($lonhost);
                   14476:     my $sts_on;
                   14477:     if ($protocol{$lonhost} eq 'https') {
                   14478:         my $cachetime = 12*3600;
                   14479:         if (!$ignore_cache) {
                   14480:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   14481:             if (defined($cached)) {
                   14482:                 return $sts_on;
                   14483:             }
                   14484:         }
                   14485:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   14486:         my $request=new HTTP::Request('HEAD',$url);
                   14487:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
                   14488:         if ($response->is_success) {
                   14489:             my $has_sts = $response->header('Strict-Transport-Security');
                   14490:             if ($has_sts eq '') {
                   14491:                 $sts_on = 0;
                   14492:             } else {
                   14493:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   14494:                     my $maxage = $1;
                   14495:                     if ($maxage) {
                   14496:                         $sts_on = 1;
                   14497:                     } else {
                   14498:                         $sts_on = 0;
                   14499:                     }
                   14500:                 } else {
                   14501:                     $sts_on = 0;
                   14502:                 }
                   14503:             }
                   14504:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   14505:         }
                   14506:     }
                   14507:     return;
                   14508: }
                   14509: 
1.1449    raeburn  14510: sub waf_allssl {
                   14511:     my ($host_name) = @_;
                   14512:     my $alias = &get_proxy_alias();
                   14513:     if ($host_name eq '') {
                   14514:         $host_name = $ENV{'SERVER_NAME'};
                   14515:     }
                   14516:     if (($host_name ne '') && ($alias eq $host_name)) {
                   14517:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   14518:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   14519:         if ($defdomdefaults{'waf_sslopt'}) {
                   14520:             return $defdomdefaults{'waf_sslopt'};
                   14521:         }
                   14522:     }
                   14523:     return;
                   14524: }
                   14525: 
1.1434    raeburn  14526: sub get_requestor_ip {
                   14527:     my ($r,$nolookup,$noproxy) = @_;
                   14528:     my $from_ip;
                   14529:     if (ref($r)) {
1.1447    raeburn  14530:         if ($r->can('useragent_ip')) {
                   14531:             if ($noproxy && $r->can('client_ip')) {
                   14532:                 $from_ip = $r->client_ip();
                   14533:             } else {
                   14534:                 $from_ip = $r->useragent_ip();
                   14535:             }
                   14536:         } elsif ($r->connection->can('remote_ip')) {
                   14537:             $from_ip = $r->connection->remote_ip();
                   14538:         } else {
                   14539:             $from_ip = $r->get_remote_host($nolookup);
                   14540:         }
1.1434    raeburn  14541:     } else {
                   14542:         $from_ip = $ENV{'REMOTE_ADDR'};
                   14543:     }
                   14544:     return $from_ip if ($noproxy); 
                   14545:     # Who controls proxy settings for server
                   14546:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14547:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   14548:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
1.1437    raeburn  14549:         if ($proxyinfo->{'vpnint'}) {
                   14550:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
1.1434    raeburn  14551:                 return $from_ip;
                   14552:             }
                   14553:         }
                   14554:         if ($proxyinfo->{'trusted'}) {
                   14555:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   14556:                 my $ipheader = $proxyinfo->{'ipheader'};
                   14557:                 my ($ip,$xfor);
                   14558:                 if (ref($r)) {
                   14559:                     if ($ipheader) {
                   14560:                         $ip = $r->headers_in->{$ipheader};
                   14561:                     }
                   14562:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   14563:                 } else {
                   14564:                     if ($ipheader) {
                   14565:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   14566:                     }
                   14567:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   14568:                 }
                   14569:                 if (($ip eq '') && ($xfor ne '')) {
                   14570:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   14571:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   14572:                             $ip = $poss_ip;
1.1435    raeburn  14573:                             last;
1.1434    raeburn  14574:                         }
                   14575:                     }
                   14576:                 }
                   14577:                 if ($ip ne '') {
                   14578:                     return $ip;
                   14579:                 }
                   14580:             }
                   14581:         }
                   14582:     }
                   14583:     return $from_ip;
                   14584: }
                   14585: 
                   14586: sub get_proxy_settings {
                   14587:     my ($dom_in_use) = @_;
                   14588:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   14589:     my $proxyinfo = {
                   14590:                        ipheader => $domdefaults{'waf_ipheader'},
                   14591:                        trusted  => $domdefaults{'waf_trusted'},
1.1437    raeburn  14592:                        vpnint   => $domdefaults{'waf_vpnint'},
1.1438    raeburn  14593:                        vpnext   => $domdefaults{'waf_vpnext'},
1.1449    raeburn  14594:                        sslopt   => $domdefaults{'waf_sslopt'},
1.1434    raeburn  14595:                     };
                   14596:     return $proxyinfo;
                   14597: }
                   14598: 
                   14599: sub ip_match {
                   14600:     my ($ip,$pattern_str) = @_;
                   14601:     $ip=Net::CIDR::cidrvalidate($ip);
                   14602:     if ($ip) {
                   14603:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   14604:     }
                   14605:     return;
                   14606: }
                   14607: 
                   14608: sub get_proxy_alias {
1.1450    raeburn  14609:     my ($lonid) = @_;
                   14610:     if ($lonid eq '') {
                   14611:         $lonid = $perlvar{'lonHostID'};
                   14612:     }
                   14613:     if (!defined(&hostname($lonid))) {
                   14614:         return;
                   14615:     }
                   14616:     if ($lonid ne '') {
                   14617:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
1.1434    raeburn  14618:         if ($cached) {
                   14619:             return $alias;
                   14620:         }
1.1450    raeburn  14621:         my $dom = &Apache::lonnet::host_domain($lonid);
1.1434    raeburn  14622:         if ($dom ne '') {
                   14623:             my $cachetime = 60*60*24;
                   14624:             my %domconfig =
1.1437    raeburn  14625:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14626:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14627:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
1.1450    raeburn  14628:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   14629:                 }
                   14630:             }
                   14631:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   14632:         }
                   14633:     }
                   14634:     return;
                   14635: }
                   14636: 
                   14637: sub use_proxy_alias {
                   14638:     my ($r,$lonid) = @_;
                   14639:     my $alias = &get_proxy_alias($lonid);
                   14640:     if ($alias) {
                   14641:         my $dom = &host_domain($lonid);
                   14642:         if ($dom ne '') {
1.1467    raeburn  14643:             my $proxyinfo = &get_proxy_settings($dom);
1.1450    raeburn  14644:             my ($vpnint,$remote_ip);
                   14645:             if (ref($proxyinfo) eq 'HASH') {
                   14646:                 $vpnint = $proxyinfo->{'vpnint'};
                   14647:                 if ($vpnint) {
                   14648:                     $remote_ip = &get_requestor_ip($r,1,1);
1.1434    raeburn  14649:                 }
                   14650:             }
1.1450    raeburn  14651:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   14652:                 return $alias;
                   14653:             }
1.1434    raeburn  14654:         }
                   14655:     }
                   14656:     return;
                   14657: }
                   14658: 
1.1467    raeburn  14659: sub alias_shibboleth {
                   14660:     my ($lonid) = @_;
                   14661:     if ($lonid eq '') {
                   14662:         $lonid = $perlvar{'lonHostID'};
                   14663:     }
                   14664:     if (!defined(&hostname($lonid))) {
                   14665:         return;
                   14666:     }
                   14667:     if ($lonid ne '') {
                   14668:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
                   14669:         if ($cached) {
                   14670:             return $use_alias;
                   14671:         }
                   14672:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14673:         if ($dom ne '') {
                   14674:             my $cachetime = 60*60*24;
                   14675:             my %domconfig =
                   14676:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14677:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14678:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
                   14679:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
                   14680:                 }
                   14681:             }
                   14682:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
                   14683:         }
                   14684:     }
                   14685:     return;
                   14686: }
                   14687: 
1.1465    raeburn  14688: sub get_saml_landing {
                   14689:     my ($lonid) = @_;
                   14690:     if ($lonid eq '') {
                   14691:         my $defdom = &default_login_domain();
                   14692:         my @hosts = &current_machine_ids();
                   14693:         if (@hosts > 1) {
                   14694:             foreach my $hostid (@hosts) {
                   14695:                 if (&host_domain($hostid) eq $defdom) {
                   14696:                     $lonid = $hostid;
                   14697:                     last;
                   14698:                 }
                   14699:             }
                   14700:         } else {
                   14701:             $lonid = $perlvar{'lonHostID'};
                   14702:         }
                   14703:         if ($lonid) {
                   14704:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
                   14705:                 return;
                   14706:             }
                   14707:         } else {
                   14708:             return;
                   14709:         }
                   14710:     } elsif (!defined(&hostname($lonid))) {
                   14711:         return;
                   14712:     }
                   14713:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   14714:     if ($cached) {
                   14715:         return $landing;
                   14716:     }
                   14717:     my $dom = &Apache::lonnet::host_domain($lonid);
                   14718:     if ($dom ne '') {
                   14719:         my $cachetime = 60*60*24;
                   14720:         my %domconfig =
                   14721:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
                   14722:         if (ref($domconfig{'login'}) eq 'HASH') {
                   14723:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   14724:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   14725:                     $landing = 1;
                   14726:                 }
                   14727:             }
                   14728:         }
                   14729:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   14730:     }
                   14731:     return;
                   14732: }
                   14733: 
1.31      www      14734: # ------------------------------------------------------------- Declutters URLs
                   14735: 
                   14736: sub declutter {
                   14737:     my $thisfn=shift;
1.569     albertel 14738:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  14739:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   14740:         $thisfn=~s{^/home/httpd/html}{};
                   14741:     }
1.31      www      14742:     $thisfn=~s/^\///;
1.697     albertel 14743:     $thisfn=~s|^adm/wrapper/||;
                   14744:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      14745:     $thisfn=~s/^res\///;
1.1172    bisitz   14746:     $thisfn=~s/^priv\///;
1.1032    raeburn  14747:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   14748:         $thisfn=~s/\?.+$//;
                   14749:     }
1.268     www      14750:     return $thisfn;
                   14751: }
                   14752: 
                   14753: # ------------------------------------------------------------- Clutter up URLs
                   14754: 
                   14755: sub clutter {
                   14756:     my $thisfn='/'.&declutter(shift);
1.887     albertel 14757:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 14758: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      14759:        $thisfn='/res'.$thisfn; 
                   14760:     }
1.1031    raeburn  14761:     if ($thisfn !~m|^/adm|) {
                   14762: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 14763: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 14764: 	} else {
                   14765: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   14766: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 14767: 	    if ($embstyle eq 'ssi'
                   14768: 		|| ($embstyle eq 'hdn')
                   14769: 		|| ($embstyle eq 'rat')
                   14770: 		|| ($embstyle eq 'prv')
                   14771: 		|| ($embstyle eq 'ign')) {
                   14772: 		#do nothing with these
                   14773: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 14774: 		|| ($embstyle eq 'emb')
                   14775: 		|| ($embstyle eq 'wrp')) {
                   14776: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 14777: 	    } elsif ($embstyle eq 'unk'
                   14778: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 14779: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 14780: 	    } else {
1.718     www      14781: #		&logthis("Got a blank emb style");
1.695     albertel 14782: 	    }
1.694     albertel 14783: 	}
1.1343    raeburn  14784:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  14785:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 14786:     }
1.31      www      14787:     return $thisfn;
1.12      www      14788: }
                   14789: 
1.787     albertel 14790: sub clutter_with_no_wrapper {
                   14791:     my $uri = &clutter(shift);
                   14792:     if ($uri =~ m-^/adm/-) {
                   14793: 	$uri =~ s-^/adm/wrapper/-/-;
                   14794: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14795:     }
                   14796:     return $uri;
                   14797: }
                   14798: 
1.557     albertel 14799: sub freeze_escape {
                   14800:     my ($value)=@_;
                   14801:     if (ref($value)) {
                   14802: 	$value=&nfreeze($value);
                   14803: 	return '__FROZEN__'.&escape($value);
                   14804:     }
                   14805:     return &escape($value);
                   14806: }
                   14807: 
1.11      www      14808: 
1.557     albertel 14809: sub thaw_unescape {
                   14810:     my ($value)=@_;
                   14811:     if ($value =~ /^__FROZEN__/) {
                   14812: 	substr($value,0,10,undef);
                   14813: 	$value=&unescape($value);
                   14814: 	return &thaw($value);
                   14815:     }
                   14816:     return &unescape($value);
                   14817: }
                   14818: 
1.436     albertel 14819: sub correct_line_ends {
                   14820:     my ($result)=@_;
                   14821:     $$result =~s/\r\n/\n/mg;
                   14822:     $$result =~s/\r/\n/mg;
1.415     albertel 14823: }
1.1       albertel 14824: # ================================================================ Main Program
                   14825: 
1.184     www      14826: sub goodbye {
1.204     albertel 14827:    &logthis("Starting Shut down");
1.443     albertel 14828: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14829:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14830: #converted
1.599     albertel 14831: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14832:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14833: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   14834: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 14835: #1.1 only
1.870     albertel 14836: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   14837: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   14838: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   14839: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   14840:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 14841:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   14842:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      14843:    &flushcourselogs();
                   14844:    &logthis("Shutting down");
                   14845: }
                   14846: 
1.852     albertel 14847: sub get_dns {
1.1210    raeburn  14848:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 14849:     if (!$ignore_cache) {
                   14850: 	my ($content,$cached)=
                   14851: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   14852: 	if ($cached) {
1.1210    raeburn  14853: 	    &$func($content,$hashref);
1.869     albertel 14854: 	    return;
                   14855: 	}
                   14856:     }
                   14857: 
                   14858:     my %alldns;
1.1379    raeburn  14859:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   14860:         foreach my $dns (<$config>) {
                   14861: 	    next if ($dns !~ /^\^(\S*)/x);
                   14862:             my $line = $1;
                   14863:             my ($host,$protocol) = split(/:/,$line);
                   14864:             if ($protocol ne 'https') {
                   14865:                 $protocol = 'http';
                   14866:             }
                   14867: 	    $alldns{$host} = $protocol;
1.979     raeburn  14868:         }
1.1379    raeburn  14869:         close($config);
1.869     albertel 14870:     }
                   14871:     while (%alldns) {
1.1263    raeburn  14872: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1456    raeburn  14873:         my ($contents,@content);
                   14874:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   14875:             my $command = (split('/',$url))[3];
                   14876:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   14877:             delete($alldns{$dns});
                   14878:             next if (($dir eq '') || ($file eq ''));
                   14879:             if (open(my $config,'<',"$dir/$file")) {
1.1457    raeburn  14880:                 @content = <$config>;
1.1456    raeburn  14881:                 close($config);
                   14882:             }
                   14883:             if ($url eq '/adm/dns/loncapaCRL') {
                   14884:                 $contents = join('',@content);
                   14885:             }
                   14886:         } else {
                   14887: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   14888:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
                   14889:             delete($alldns{$dns});
                   14890: 	    next if ($response->is_error());
                   14891:             if ($url eq '/adm/dns/loncapaCRL') {
                   14892:                 $contents = $response->content;
                   14893:             } else {
                   14894:                 @content = split("\n",$response->content);
                   14895:             }
                   14896:         }
1.1379    raeburn  14897:         if ($url eq '/adm/dns/loncapaCRL') {
1.1456    raeburn  14898:             return &$func($contents);
1.1379    raeburn  14899:         } else {
                   14900: 	    unless ($nocache) {
                   14901: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   14902: 	    }
                   14903: 	    &$func(\@content,$hashref);
                   14904:             return;
                   14905:         }
                   14906:     }
                   14907:     my $which = (split('/',$url,4))[3];
                   14908:     if ($which eq 'loncapaCRL') {
                   14909:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   14910:         if (-e $diskfile) {
                   14911:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   14912:         } else {
                   14913:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   14914:         }
                   14915:     } else {
                   14916:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   14917:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   14918:             my @content = <$config>;
                   14919:             close($config);
                   14920:             &$func(\@content,$hashref);
                   14921:         }
1.852     albertel 14922:     }
1.1210    raeburn  14923:     return;
                   14924: }
                   14925: 
                   14926: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  14927: sub parse_dns_checksums_tab {
1.1210    raeburn  14928:     my ($lines,$hashref) = @_;
1.1264    raeburn  14929:     my $lonhost = $perlvar{'lonHostID'};
                   14930:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  14931:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  14932:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14933:     my $webconfdir = '/etc/httpd/conf';
                   14934:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14935:         $webconfdir = '/etc/apache2';
                   14936:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14937:         if ($1 >= 10) {
                   14938:             $webconfdir = '/etc/apache2';
                   14939:         }
                   14940:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14941:         if ($1 >= 10.0) {
                   14942:             $webconfdir = '/etc/apache2';
                   14943:         }
                   14944:     }
1.1210    raeburn  14945:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14946:     my (%chksum,%revnum);
                   14947:     if (ref($lines) eq 'ARRAY') {
                   14948:         chomp(@{$lines});
1.1238    raeburn  14949:         my $version = shift(@{$lines});
                   14950:         if ($version eq $release) {  
1.1210    raeburn  14951:             foreach my $line (@{$lines}) {
1.1238    raeburn  14952:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  14953:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14954:                     if ($webconfdir eq '/etc/apache2') {
                   14955:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14956:                     }
                   14957:                 }
1.1238    raeburn  14958:                 $chksum{$file} = $shasum;
                   14959:                 $revnum{$file} = $version;
1.1210    raeburn  14960:             }
                   14961:             if (ref($hashref) eq 'HASH') {
                   14962:                 %{$hashref} = (
                   14963:                                 sums     => \%chksum,
                   14964:                                 versions => \%revnum,
                   14965:                               );
                   14966:             }
                   14967:         }
                   14968:     }
1.869     albertel 14969:     return;
1.852     albertel 14970: }
1.1210    raeburn  14971: 
                   14972: sub fetch_dns_checksums {
1.1238    raeburn  14973:     my %checksums;
                   14974:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  14975:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  14976:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14977:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  14978:              \%checksums);
1.1210    raeburn  14979:     return \%checksums;
                   14980: }
                   14981: 
1.1379    raeburn  14982: sub fetch_crl_pemfile {
                   14983:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   14984: }
                   14985: 
                   14986: sub save_crl_pem {
1.1456    raeburn  14987:     my ($content) = @_;
1.1380    raeburn  14988:     my ($msg,$hadchanges);
1.1456    raeburn  14989:     if ($content ne '') {
1.1379    raeburn  14990:         my $now = time;
                   14991:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   14992:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   14993:         if (open(my $fh,'>',"$tmpcrl")) {
1.1456    raeburn  14994:             print $fh $content;
1.1379    raeburn  14995:             close($fh);
                   14996:             if (-e $lonca) {
                   14997:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   14998:                     my $check = <PIPE>;
                   14999:                     close(PIPE);
                   15000:                     chomp($check);
                   15001:                     if ($check eq 'verify OK') {
                   15002:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  15003:                         my $backup;
1.1379    raeburn  15004:                         if (-e $dest) {
1.1380    raeburn  15005:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   15006:                                 $backup = 'ok';
                   15007:                             }
1.1379    raeburn  15008:                         }
                   15009:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   15010:                             $msg = 'ok';
1.1380    raeburn  15011:                             if ($backup) {
                   15012:                                 my (%oldnums,%newnums);
                   15013:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   15014:                                     while (<PIPE>) {
                   15015:                                         $oldnums{(split(/:/))[1]} = 1;
                   15016:                                     }
                   15017:                                     close(PIPE);
                   15018:                                 }
                   15019:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   15020:                                     while(<PIPE>) {
                   15021:                                         $newnums{(split(/:/))[1]} = 1;
                   15022:                                     }
                   15023:                                     close(PIPE);
                   15024:                                 }
                   15025:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   15026:                                     unless (exists($oldnums{$key})) {
                   15027:                                         $hadchanges = 1;
                   15028:                                         last;
                   15029:                                     }
                   15030:                                 }
                   15031:                                 unless ($hadchanges) {
                   15032:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   15033:                                         unless (exists($newnums{$key})) {
                   15034:                                             $hadchanges = 1;
                   15035:                                             last;
                   15036:                                         }
                   15037:                                     }
                   15038:                                 }
                   15039:                             }
1.1379    raeburn  15040:                         }
                   15041:                     } else {
                   15042:                         unlink($tmpcrl);
                   15043:                     }
                   15044:                 } else {
                   15045:                     unlink($tmpcrl);
                   15046:                 }
                   15047:             } else {
                   15048:                 unlink($tmpcrl);
                   15049:             }
                   15050:         }
                   15051:     }
1.1380    raeburn  15052:     return ($msg,$hadchanges);
1.1379    raeburn  15053: }
                   15054: 
1.1456    raeburn  15055: sub parse_getdns_url {
                   15056:     my ($command,$url) = @_;
                   15057:     my $dir = $perlvar{'lonTabDir'};
                   15058:     my $file;
                   15059:     if ($command eq 'hosts') {
                   15060:         $file = 'dns_hosts.tab';
                   15061:     } elsif ($command eq 'domain') {
                   15062:         $file = 'dns_domain.tab';
                   15063:     } elsif ($command eq 'checksums') {
                   15064:         my $version = (split('/',$url))[4];
                   15065:         $file = "dns_checksums/$version.tab",
                   15066:     } elsif ($command eq 'loncapaCRL') {
                   15067:         $dir = $perlvar{'lonCertificateDirectory'};
                   15068:         $file = $perlvar{'lonnetCertRevocationList'};
                   15069:     }
                   15070:     return ($dir,$file);
                   15071: }
                   15072: 
1.327     albertel 15073: # ------------------------------------------------------------ Read domain file
                   15074: {
1.852     albertel 15075:     my $loaded;
1.846     albertel 15076:     my %domain;
                   15077: 
1.852     albertel 15078:     sub parse_domain_tab {
                   15079: 	my ($lines) = @_;
                   15080: 	foreach my $line (@$lines) {
                   15081: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      15082: 
1.846     albertel 15083: 	    chomp($line);
1.852     albertel 15084: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 15085: 	    my %this_domain;
                   15086: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   15087: 			       'lang_def', 'city', 'longi', 'lati',
                   15088: 			       'primary') {
                   15089: 		$this_domain{$field} = shift(@elements);
                   15090: 	    }
                   15091: 	    $domain{$name} = \%this_domain;
1.852     albertel 15092: 	}
                   15093:     }
1.864     albertel 15094: 
                   15095:     sub reset_domain_info {
                   15096: 	undef($loaded);
                   15097: 	undef(%domain);
                   15098:     }
                   15099: 
1.852     albertel 15100:     sub load_domain_tab {
1.1293    raeburn  15101: 	my ($ignore_cache,$nocache) = @_;
                   15102: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 15103: 	my $fh;
1.1359    raeburn  15104: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 15105: 	    my @lines = <$fh>;
                   15106: 	    &parse_domain_tab(\@lines);
1.448     albertel 15107: 	}
1.852     albertel 15108: 	close($fh);
                   15109: 	$loaded = 1;
1.327     albertel 15110:     }
1.846     albertel 15111: 
                   15112:     sub domain {
1.852     albertel 15113: 	&load_domain_tab() if (!$loaded);
                   15114: 
1.846     albertel 15115: 	my ($name,$what) = @_;
                   15116: 	return if ( !exists($domain{$name}) );
                   15117: 
                   15118: 	if (!$what) {
                   15119: 	    return $domain{$name}{'description'};
                   15120: 	}
                   15121: 	return $domain{$name}{$what};
                   15122:     }
1.974     raeburn  15123: 
                   15124:     sub domain_info {
                   15125:         &load_domain_tab() if (!$loaded);
                   15126:         return %domain;
                   15127:     }
                   15128: 
1.327     albertel 15129: }
                   15130: 
                   15131: 
1.1       albertel 15132: # ------------------------------------------------------------- Read hosts file
                   15133: {
1.838     albertel 15134:     my %hostname;
1.844     albertel 15135:     my %hostdom;
1.845     albertel 15136:     my %libserv;
1.852     albertel 15137:     my $loaded;
1.888     albertel 15138:     my %name_to_host;
1.1074    raeburn  15139:     my %internetdom;
1.1107    raeburn  15140:     my %LC_dns_serv;
1.852     albertel 15141: 
                   15142:     sub parse_hosts_tab {
                   15143: 	my ($file) = @_;
                   15144: 	foreach my $configline (@$file) {
                   15145: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  15146:             chomp($configline);
                   15147: 	    if ($configline =~ /^\^/) {
                   15148:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   15149:                     $LC_dns_serv{$1} = 1;
                   15150:                 }
                   15151:                 next;
                   15152:             }
1.1074    raeburn  15153: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 15154: 	    $name=~s/\s//g;
                   15155: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  15156:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   15157:                     my $curr = $hostname{$id};
                   15158:                     my $skip;
                   15159:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   15160:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   15161:                             $skip = 1;
                   15162:                         } else {
                   15163:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   15164:                         }
                   15165:                     }
                   15166:                     unless ($skip) {
                   15167:                         push(@{$name_to_host{$name}},$id);
                   15168:                     }
                   15169:                 } else {
                   15170:                     push(@{$name_to_host{$name}},$id);
                   15171:                 }
1.852     albertel 15172: 		$hostname{$id}=$name;
                   15173: 		$hostdom{$id}=$domain;
                   15174: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  15175:                 if (defined($protocol)) {
                   15176:                     if ($protocol eq 'https') {
                   15177:                         $protocol{$id} = $protocol;
                   15178:                     } else {
                   15179:                         $protocol{$id} = 'http'; 
                   15180:                     }
1.968     raeburn  15181:                 } else {
1.969     raeburn  15182:                     $protocol{$id} = 'http';
1.968     raeburn  15183:                 }
1.1074    raeburn  15184:                 if (defined($intdom)) {
                   15185:                     $internetdom{$id} = $intdom;
                   15186:                 }
1.852     albertel 15187: 	    }
                   15188: 	}
                   15189:     }
1.864     albertel 15190:     
                   15191:     sub reset_hosts_info {
1.897     albertel 15192: 	&purge_remembered();
1.864     albertel 15193: 	&reset_domain_info();
                   15194: 	&reset_hosts_ip_info();
1.1339    raeburn  15195:         undef(%internetdom);
1.892     albertel 15196: 	undef(%name_to_host);
1.864     albertel 15197: 	undef(%hostname);
                   15198: 	undef(%hostdom);
                   15199: 	undef(%libserv);
                   15200: 	undef($loaded);
                   15201:     }
1.1       albertel 15202: 
1.852     albertel 15203:     sub load_hosts_tab {
1.1293    raeburn  15204: 	my ($ignore_cache,$nocache) = @_;
                   15205: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  15206: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 15207: 	my @config = <$config>;
                   15208: 	&parse_hosts_tab(\@config);
                   15209: 	close($config);
                   15210: 	$loaded=1;
1.1       albertel 15211:     }
1.852     albertel 15212: 
1.838     albertel 15213:     sub hostname {
1.852     albertel 15214: 	&load_hosts_tab() if (!$loaded);
                   15215: 
1.838     albertel 15216: 	my ($lonid) = @_;
                   15217: 	return $hostname{$lonid};
                   15218:     }
1.845     albertel 15219: 
1.838     albertel 15220:     sub all_hostnames {
1.852     albertel 15221: 	&load_hosts_tab() if (!$loaded);
                   15222: 
1.838     albertel 15223: 	return %hostname;
                   15224:     }
1.845     albertel 15225: 
1.888     albertel 15226:     sub all_names {
1.1293    raeburn  15227:         my ($ignore_cache,$nocache) = @_;
                   15228: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 15229: 
                   15230: 	return %name_to_host;
                   15231:     }
                   15232: 
1.974     raeburn  15233:     sub all_host_domain {
                   15234:         &load_hosts_tab() if (!$loaded);
                   15235:         return %hostdom;
                   15236:     }
                   15237: 
1.1339    raeburn  15238:     sub all_host_intdom {
                   15239:         &load_hosts_tab() if (!$loaded);
                   15240:         return %internetdom;
                   15241:     }
                   15242: 
1.845     albertel 15243:     sub is_library {
1.852     albertel 15244: 	&load_hosts_tab() if (!$loaded);
                   15245: 
1.845     albertel 15246: 	return exists($libserv{$_[0]});
                   15247:     }
                   15248: 
                   15249:     sub all_library {
1.852     albertel 15250: 	&load_hosts_tab() if (!$loaded);
                   15251: 
1.845     albertel 15252: 	return %libserv;
                   15253:     }
                   15254: 
1.1062    droeschl 15255:     sub unique_library {
                   15256: 	#2x reverse removes all hostnames that appear more than once
                   15257:         my %unique = reverse &all_library();
                   15258:         return reverse %unique;
                   15259:     }
                   15260: 
1.841     albertel 15261:     sub get_servers {
1.852     albertel 15262: 	&load_hosts_tab() if (!$loaded);
                   15263: 
1.841     albertel 15264: 	my ($domain,$type) = @_;
                   15265: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   15266: 	                                          : %hostname;
                   15267: 	my %result;
1.842     albertel 15268: 	if (ref($domain) eq 'ARRAY') {
                   15269: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 15270: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 15271: 		    $result{$host} = $hostname;
                   15272: 		}
                   15273: 	    }
                   15274: 	} else {
                   15275: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   15276: 		if ($hostdom{$host} eq $domain) {
                   15277: 		    $result{$host} = $hostname;
                   15278: 		}
1.841     albertel 15279: 	    }
                   15280: 	}
                   15281: 	return %result;
                   15282:     }
1.845     albertel 15283: 
1.1062    droeschl 15284:     sub get_unique_servers {
                   15285:         my %unique = reverse &get_servers(@_);
                   15286: 	return reverse %unique;
                   15287:     }
                   15288: 
1.844     albertel 15289:     sub host_domain {
1.852     albertel 15290: 	&load_hosts_tab() if (!$loaded);
                   15291: 
1.844     albertel 15292: 	my ($lonid) = @_;
                   15293: 	return $hostdom{$lonid};
                   15294:     }
                   15295: 
1.841     albertel 15296:     sub all_domains {
1.852     albertel 15297: 	&load_hosts_tab() if (!$loaded);
                   15298: 
1.841     albertel 15299: 	my %seen;
                   15300: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   15301: 	return @uniq;
                   15302:     }
1.1074    raeburn  15303: 
                   15304:     sub internet_dom {
                   15305:         &load_hosts_tab() if (!$loaded);
                   15306: 
                   15307:         my ($lonid) = @_;
                   15308:         return $internetdom{$lonid};
                   15309:     }
1.1107    raeburn  15310: 
                   15311:     sub is_LC_dns {
                   15312:         &load_hosts_tab() if (!$loaded);
                   15313: 
                   15314:         my ($hostname) = @_;
                   15315:         return exists($LC_dns_serv{$hostname});
                   15316:     }
                   15317: 
1.1       albertel 15318: }
                   15319: 
1.847     albertel 15320: { 
                   15321:     my %iphost;
1.856     albertel 15322:     my %name_to_ip;
                   15323:     my %lonid_to_ip;
1.869     albertel 15324: 
1.847     albertel 15325:     sub get_hosts_from_ip {
                   15326: 	my ($ip) = @_;
                   15327: 	my %iphosts = &get_iphost();
                   15328: 	if (ref($iphosts{$ip})) {
                   15329: 	    return @{$iphosts{$ip}};
                   15330: 	}
                   15331: 	return;
1.839     albertel 15332:     }
1.864     albertel 15333:     
                   15334:     sub reset_hosts_ip_info {
                   15335: 	undef(%iphost);
                   15336: 	undef(%name_to_ip);
                   15337: 	undef(%lonid_to_ip);
                   15338:     }
1.856     albertel 15339: 
                   15340:     sub get_host_ip {
                   15341: 	my ($lonid) = @_;
                   15342: 	if (exists($lonid_to_ip{$lonid})) {
                   15343: 	    return $lonid_to_ip{$lonid};
                   15344: 	}
                   15345: 	my $name=&hostname($lonid);
                   15346:    	my $ip = gethostbyname($name);
                   15347: 	return if (!$ip || length($ip) ne 4);
                   15348: 	$ip=inet_ntoa($ip);
                   15349: 	$name_to_ip{$name}   = $ip;
                   15350: 	$lonid_to_ip{$lonid} = $ip;
                   15351: 	return $ip;
                   15352:     }
1.847     albertel 15353:     
                   15354:     sub get_iphost {
1.1293    raeburn  15355: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 15356: 
1.869     albertel 15357: 	if (!$ignore_cache) {
                   15358: 	    if (%iphost) {
                   15359: 		return %iphost;
                   15360: 	    }
                   15361: 	    my ($ip_info,$cached)=
                   15362: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   15363: 	    if ($cached) {
                   15364: 		%iphost      = %{$ip_info->[0]};
                   15365: 		%name_to_ip  = %{$ip_info->[1]};
                   15366: 		%lonid_to_ip = %{$ip_info->[2]};
                   15367: 		return %iphost;
                   15368: 	    }
                   15369: 	}
1.894     albertel 15370: 
                   15371: 	# get yesterday's info for fallback
                   15372: 	my %old_name_to_ip;
                   15373: 	my ($ip_info,$cached)=
                   15374: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   15375: 	if ($cached) {
                   15376: 	    %old_name_to_ip = %{$ip_info->[1]};
                   15377: 	}
                   15378: 
1.1293    raeburn  15379: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 15380: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 15381: 	    my $ip;
                   15382: 	    if (!exists($name_to_ip{$name})) {
                   15383: 		$ip = gethostbyname($name);
                   15384: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 15385: 		    if (defined($old_name_to_ip{$name})) {
                   15386: 			$ip = $old_name_to_ip{$name};
                   15387: 			&logthis("Can't find $name defaulting to old $ip");
                   15388: 		    } else {
                   15389: 			&logthis("Name $name no IP found");
                   15390: 			next;
                   15391: 		    }
                   15392: 		} else {
                   15393: 		    $ip=inet_ntoa($ip);
1.847     albertel 15394: 		}
                   15395: 		$name_to_ip{$name} = $ip;
                   15396: 	    } else {
                   15397: 		$ip = $name_to_ip{$name};
1.653     albertel 15398: 	    }
1.888     albertel 15399: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   15400: 		$lonid_to_ip{$id} = $ip;
                   15401: 	    }
                   15402: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 15403: 	}
1.1293    raeburn  15404:         unless ($nocache) {
                   15405: 	    &do_cache_new('iphost','iphost',
                   15406: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   15407: 		          48*60*60);
                   15408:         }
1.869     albertel 15409: 
1.847     albertel 15410: 	return %iphost;
1.598     albertel 15411:     }
                   15412: 
1.992     raeburn  15413:     #
                   15414:     #  Given a DNS returns the loncapa host name for that DNS 
                   15415:     # 
                   15416:     sub host_from_dns {
                   15417:         my ($dns) = @_;
                   15418:         my @hosts;
                   15419:         my $ip;
                   15420: 
1.993     raeburn  15421:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  15422:             $ip = $name_to_ip{$dns};
                   15423:         }
                   15424:         if (!$ip) {
                   15425:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   15426:             if (length($ip) == 4) { 
                   15427: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   15428:             }
                   15429:         }
                   15430:         if ($ip) {
                   15431: 	    @hosts = get_hosts_from_ip($ip);
                   15432: 	    return $hosts[0];
                   15433:         }
                   15434:         return undef;
1.986     foxr     15435:     }
1.992     raeburn  15436: 
1.1074    raeburn  15437:     sub get_internet_names {
                   15438:         my ($lonid) = @_;
                   15439:         return if ($lonid eq '');
                   15440:         my ($idnref,$cached)=
                   15441:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   15442:         if ($cached) {
                   15443:             return $idnref;
                   15444:         }
                   15445:         my $ip = &get_host_ip($lonid);
                   15446:         my @hosts = &get_hosts_from_ip($ip);
                   15447:         my %iphost = &get_iphost();
                   15448:         my (@idns,%seen);
                   15449:         foreach my $id (@hosts) {
                   15450:             my $dom = &host_domain($id);
                   15451:             my $prim_id = &domain($dom,'primary');
                   15452:             my $prim_ip = &get_host_ip($prim_id);
                   15453:             next if ($seen{$prim_ip});
                   15454:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   15455:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   15456:                     my $intdom = &internet_dom($id);
                   15457:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   15458:                         push(@idns,$intdom);
                   15459:                     }
                   15460:                 }
                   15461:             }
                   15462:             $seen{$prim_ip} = 1;
                   15463:         }
1.1219    raeburn  15464:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  15465:     }
                   15466: 
1.986     foxr     15467: }
                   15468: 
1.1079    raeburn  15469: sub all_loncaparevs {
1.1249    raeburn  15470:     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  15471: }
                   15472: 
1.1227    raeburn  15473: # ---------------------------------------------------------- Read loncaparev table
                   15474: {
                   15475:     sub load_loncaparevs { 
                   15476:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  15477:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  15478:                 while (my $configline=<$config>) {
                   15479:                     chomp($configline);
                   15480:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   15481:                     $loncaparevs{$hostid}=$loncaparev;
                   15482:                 }
                   15483:                 close($config);
                   15484:             }
                   15485:         }
                   15486:     }
                   15487: }
                   15488: 
                   15489: # ---------------------------------------------------------- Read serverhostID table
                   15490: {
                   15491:     sub load_serverhomeIDs {
                   15492:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  15493:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  15494:                 while (my $configline=<$config>) {
                   15495:                     chomp($configline);
                   15496:                     my ($name,$id)=split(/:/,$configline);
                   15497:                     $serverhomeIDs{$name}=$id;
                   15498:                 }
                   15499:                 close($config);
                   15500:             }
                   15501:         }
                   15502:     }
                   15503: }
                   15504: 
                   15505: 
1.862     albertel 15506: BEGIN {
                   15507: 
                   15508: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   15509:     unless ($readit) {
                   15510: {
                   15511:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   15512:     %perlvar = (%perlvar,%{$configvars});
                   15513: }
                   15514: 
                   15515: 
1.1       albertel 15516: # ------------------------------------------------------ Read spare server file
                   15517: {
1.1359    raeburn  15518:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 15519: 
                   15520:     while (my $configline=<$config>) {
                   15521:        chomp($configline);
1.284     matthew  15522:        if ($configline) {
1.784     albertel 15523: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 15524: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 15525: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 15526:        }
                   15527:     }
1.448     albertel 15528:     close($config);
1.1       albertel 15529: }
1.11      www      15530: # ------------------------------------------------------------ Read permissions
                   15531: {
1.1359    raeburn  15532:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      15533: 
                   15534:     while (my $configline=<$config>) {
1.448     albertel 15535: 	chomp($configline);
                   15536: 	if ($configline) {
                   15537: 	    my ($role,$perm)=split(/ /,$configline);
                   15538: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   15539: 	}
1.11      www      15540:     }
1.448     albertel 15541:     close($config);
1.11      www      15542: }
                   15543: 
                   15544: # -------------------------------------------- Read plain texts for permissions
                   15545: {
1.1359    raeburn  15546:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      15547: 
                   15548:     while (my $configline=<$config>) {
1.448     albertel 15549: 	chomp($configline);
                   15550: 	if ($configline) {
1.742     raeburn  15551: 	    my ($short,@plain)=split(/:/,$configline);
                   15552:             %{$prp{$short}} = ();
                   15553: 	    if (@plain > 0) {
                   15554:                 $prp{$short}{'std'} = $plain[0];
                   15555:                 for (my $i=1; $i<@plain; $i++) {
                   15556:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   15557:                 }
                   15558:             }
1.448     albertel 15559: 	}
1.135     www      15560:     }
1.448     albertel 15561:     close($config);
1.135     www      15562: }
                   15563: 
                   15564: # ---------------------------------------------------------- Read package table
                   15565: {
1.1359    raeburn  15566:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      15567: 
                   15568:     while (my $configline=<$config>) {
1.483     albertel 15569: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 15570: 	chomp($configline);
                   15571: 	my ($short,$plain)=split(/:/,$configline);
                   15572: 	my ($pack,$name)=split(/\&/,$short);
                   15573: 	if ($plain ne '') {
                   15574: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   15575: 	    $packagetab{$short}=$plain; 
                   15576: 	}
1.11      www      15577:     }
1.448     albertel 15578:     close($config);
1.329     matthew  15579: }
                   15580: 
1.1073    raeburn  15581: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  15582: 
                   15583: &load_loncaparevs();
1.1073    raeburn  15584: 
1.1074    raeburn  15585: # ---------------------------------------------------------- Read serverhostID table
                   15586: 
1.1227    raeburn  15587: &load_serverhomeIDs();
                   15588: 
                   15589: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  15590: {
                   15591:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   15592:     if (-e $file) {
                   15593:         my $parser = HTML::LCParser->new($file);
                   15594:         while (my $token = $parser->get_token()) {
                   15595:             if ($token->[0] eq 'S') {
                   15596:                 my $item = $token->[1];
                   15597:                 my $name = $token->[2]{'name'};
                   15598:                 my $value = $token->[2]{'value'};
1.1285    raeburn  15599:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  15600:                 my $namematch = $token->[2]{'namematch'};
                   15601:                 if ($item eq 'parameter') {
                   15602:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   15603:                         my $release = $parser->get_text();
                   15604:                         $release =~ s/(^\s*|\s*$ )//gx;
                   15605:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   15606:                     }
                   15607:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  15608:                     my $release = $parser->get_text();
                   15609:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  15610:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  15611:                 }
                   15612:             }
                   15613:         }
                   15614:     }
1.1073    raeburn  15615: }
                   15616: 
1.1138    raeburn  15617: # ---------------------------------------------------------- Read managers table
                   15618: {
                   15619:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  15620:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  15621:             while (my $configline=<$config>) {
                   15622:                 chomp($configline);
                   15623:                 next if ($configline =~ /^\#/);
                   15624:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   15625:                     $managerstab{$configline} = 1;
                   15626:                 }
                   15627:             }
                   15628:             close($config);
                   15629:         }
                   15630:     }
                   15631: }
                   15632: 
1.329     matthew  15633: # ------------- set up temporary directory
                   15634: {
1.1117    foxr     15635:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  15636: 
1.11      www      15637: }
                   15638: 
1.1405    raeburn  15639: # ------------- set default texengine (domain default overrides this)
                   15640: {
                   15641:     $deftex = LONCAPA::texengine();
                   15642: }
                   15643: 
1.1416    raeburn  15644: # ------------- set default minimum length for passwords for internal auth users
                   15645: {
                   15646:     $passwdmin = LONCAPA::passwd_min();
                   15647: }
                   15648: 
1.794     albertel 15649: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   15650: 				'compress_threshold'=> 20_000,
                   15651:  			        });
1.185     www      15652: 
1.281     www      15653: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      15654: $dumpcount=0;
1.958     www      15655: $locknum=0;
1.22      www      15656: 
1.163     harris41 15657: &logtouch();
1.672     albertel 15658: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      15659: $readit=1;
1.564     albertel 15660:     {
                   15661: 	use integer;
                   15662: 	my $test=(2**32)+1;
1.568     albertel 15663: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 15664: 	&logthis(" Detected 64bit platform ($_64bit)");
                   15665:     }
1.195     www      15666: }
1.1       albertel 15667: }
1.179     www      15668: 
1.1       albertel 15669: 1;
1.191     harris41 15670: __END__
                   15671: 
1.243     albertel 15672: =pod
                   15673: 
1.191     harris41 15674: =head1 NAME
                   15675: 
1.243     albertel 15676: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 15677: 
                   15678: =head1 SYNOPSIS
                   15679: 
1.243     albertel 15680: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 15681: 
                   15682:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   15683: 
1.243     albertel 15684: Common parameters:
                   15685: 
                   15686: =over 4
                   15687: 
                   15688: =item *
                   15689: 
                   15690: $uname : an internal username (if $cname expecting a course Id specifically)
                   15691: 
                   15692: =item *
                   15693: 
                   15694: $udom : a domain (if $cdom expecting a course's domain specifically)
                   15695: 
                   15696: =item *
                   15697: 
                   15698: $symb : a resource instance identifier
                   15699: 
                   15700: =item *
                   15701: 
                   15702: $namespace : the name of a .db file that contains the data needed or
                   15703: being set.
                   15704: 
                   15705: =back
                   15706: 
1.394     bowersj2 15707: =head1 OVERVIEW
1.191     harris41 15708: 
1.394     bowersj2 15709: lonnet provides subroutines which interact with the
                   15710: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   15711: about classes, users, and resources.
1.243     albertel 15712: 
                   15713: For many of these objects you can also use this to store data about
                   15714: them or modify them in various ways.
1.191     harris41 15715: 
1.394     bowersj2 15716: =head2 Symbs
1.191     harris41 15717: 
1.394     bowersj2 15718: To identify a specific instance of a resource, LON-CAPA uses symbols
                   15719: or "symbs"X<symb>. These identifiers are built from the URL of the
                   15720: map, the resource number of the resource in the map, and the URL of
                   15721: the resource itself. The latter is somewhat redundant, but might help
                   15722: if maps change.
                   15723: 
                   15724: An example is
                   15725: 
                   15726:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   15727: 
                   15728: The respective map entry is
                   15729: 
                   15730:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   15731:   title="Problem 2">
                   15732:  </resource>
                   15733: 
                   15734: Symbs are used by the random number generator, as well as to store and
                   15735: restore data specific to a certain instance of for example a problem.
                   15736: 
                   15737: =head2 Storing And Retrieving Data
                   15738: 
                   15739: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   15740: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   15741: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   15742: is is the non-critical message twin of cstore. These functions are for
                   15743: handlers to store a perl hash to a user's permanent data space in an
                   15744: easy manner, and to retrieve it again on another call. It is expected
                   15745: that a handler would use this once at the beginning to retrieve data,
                   15746: and then again once at the end to send only the new data back.
                   15747: 
                   15748: The data is stored in the user's data directory on the user's
                   15749: homeserver under the ID of the course.
                   15750: 
                   15751: The hash that is returned by restore will have all of the previous
                   15752: value for all of the elements of the hash.
                   15753: 
                   15754: Example:
                   15755: 
                   15756:  #creating a hash
                   15757:  my %hash;
                   15758:  $hash{'foo'}='bar';
                   15759: 
                   15760:  #storing it
                   15761:  &Apache::lonnet::cstore(\%hash);
                   15762: 
                   15763:  #changing a value
                   15764:  $hash{'foo'}='notbar';
                   15765: 
                   15766:  #adding a new value
                   15767:  $hash{'bar'}='foo';
                   15768:  &Apache::lonnet::cstore(\%hash);
                   15769: 
                   15770:  #retrieving the hash
                   15771:  my %history=&Apache::lonnet::restore();
                   15772: 
                   15773:  #print the hash
                   15774:  foreach my $key (sort(keys(%history))) {
                   15775:    print("\%history{$key} = $history{$key}");
                   15776:  }
                   15777: 
                   15778: Will print out:
1.191     harris41 15779: 
1.394     bowersj2 15780:  %history{1:foo} = bar
                   15781:  %history{1:keys} = foo:timestamp
                   15782:  %history{1:timestamp} = 990455579
                   15783:  %history{2:bar} = foo
                   15784:  %history{2:foo} = notbar
                   15785:  %history{2:keys} = foo:bar:timestamp
                   15786:  %history{2:timestamp} = 990455580
                   15787:  %history{bar} = foo
                   15788:  %history{foo} = notbar
                   15789:  %history{timestamp} = 990455580
                   15790:  %history{version} = 2
                   15791: 
                   15792: Note that the special hash entries C<keys>, C<version> and
                   15793: C<timestamp> were added to the hash. C<version> will be equal to the
                   15794: total number of versions of the data that have been stored. The
                   15795: C<timestamp> attribute will be the UNIX time the hash was
                   15796: stored. C<keys> is available in every historical section to list which
                   15797: keys were added or changed at a specific historical revision of a
                   15798: hash.
                   15799: 
                   15800: B<Warning>: do not store the hash that restore returns directly. This
                   15801: will cause a mess since it will restore the historical keys as if the
                   15802: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 15803: 
1.394     bowersj2 15804: Calling convention:
1.191     harris41 15805: 
1.1225    raeburn  15806:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  15807:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 15808: 
1.394     bowersj2 15809: For more detailed information, see lonnet specific documentation.
1.191     harris41 15810: 
1.394     bowersj2 15811: =head1 RETURN MESSAGES
1.191     harris41 15812: 
1.394     bowersj2 15813: =over 4
1.191     harris41 15814: 
1.394     bowersj2 15815: =item * B<con_lost>: unable to contact remote host
1.191     harris41 15816: 
1.394     bowersj2 15817: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   15818: when the connection is brought back up
1.191     harris41 15819: 
1.394     bowersj2 15820: =item * B<con_failed>: unable to contact remote host and unable to save message
                   15821: for later delivery
1.191     harris41 15822: 
1.967     bisitz   15823: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 15824: 
1.394     bowersj2 15825: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 15826: that was requested
1.191     harris41 15827: 
1.243     albertel 15828: =back
1.191     harris41 15829: 
1.243     albertel 15830: =head1 PUBLIC SUBROUTINES
1.191     harris41 15831: 
1.243     albertel 15832: =head2 Session Environment Functions
1.191     harris41 15833: 
1.243     albertel 15834: =over 4
1.191     harris41 15835: 
1.394     bowersj2 15836: =item * 
                   15837: X<appenv()>
1.949     raeburn  15838: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 15839: the user envirnoment file, and will be restored for each access this
1.620     albertel 15840: user makes during this session, also modifies the %env for the current
1.949     raeburn  15841: process. Optional rolesarrayref - if defined contains a reference to an array
                   15842: of roles which are exempt from the restriction on modifying user.role entries 
                   15843: in the user's environment.db and in %env.    
1.191     harris41 15844: 
                   15845: =item *
1.394     bowersj2 15846: X<delenv()>
1.987     raeburn  15847: B<delenv($delthis,$regexp)>: removes all items from the session
                   15848: environment file that begin with $delthis. If the 
                   15849: optional second arg - $regexp - is true, $delthis is treated as a 
                   15850: regular expression, otherwise \Q$delthis\E is used. 
                   15851: The values are also deleted from the current processes %env.
1.191     harris41 15852: 
1.795     albertel 15853: =item * get_env_multiple($name) 
                   15854: 
                   15855: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   15856: values may be defined and end up as an array ref.
                   15857: 
                   15858: returns an array of values
                   15859: 
1.243     albertel 15860: =back
                   15861: 
                   15862: =head2 User Information
1.191     harris41 15863: 
1.243     albertel 15864: =over 4
1.191     harris41 15865: 
                   15866: =item *
1.394     bowersj2 15867: X<queryauthenticate()>
                   15868: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 15869: authentication scheme
                   15870: 
                   15871: =item *
1.394     bowersj2 15872: X<authenticate()>
1.1073    raeburn  15873: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 15874: authenticate user from domain's lib servers (first use the current
                   15875: one). C<$upass> should be the users password.
1.1073    raeburn  15876: $checkdefauth is optional (value is 1 if a check should be made to
                   15877:    authenticate user using default authentication method, and allow
                   15878:    account creation if username does not have account in the domain).
                   15879: $clientcancheckhost is optional (value is 1 if checking whether the
                   15880:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 15881: 
                   15882: =item *
1.394     bowersj2 15883: X<homeserver()>
                   15884: B<homeserver($uname,$udom)>: find the server which has
                   15885: the user's directory and files (there must be only one), this caches
                   15886: the answer, and also caches if there is a borken connection.
1.191     harris41 15887: 
                   15888: =item *
1.394     bowersj2 15889: X<idget()>
1.1300    raeburn  15890: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   15891: a list of student/employee IDs or clicker IDs
                   15892: (student/employee IDs are a unique resource in a domain, there must be 
                   15893: only 1 ID per username, and only 1 username per ID in a specific domain).
                   15894: clickerIDs are not necessarily unique, as students might share clickers.
                   15895: (returns hash: id=>name,id=>name)
1.191     harris41 15896: 
                   15897: =item *
1.394     bowersj2 15898: X<idrget()>
                   15899: B<idrget($udom,@unames)>: find the IDs behind a list of
                   15900: usernames (returns hash: name=>id,name=>id)
1.191     harris41 15901: 
                   15902: =item *
1.394     bowersj2 15903: X<idput()>
1.1300    raeburn  15904: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   15905: names and associated student/employee IDs or clicker IDs.
                   15906: 
                   15907: =item *
                   15908: X<iddel()>
                   15909: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   15910: student/employee ID or clicker ID username look-ups from domain.
                   15911: The homeserver ($uhome) and namespace ($namespace) are optional.
                   15912: If no $uhome is provided, it will be determined usig &homeserver()
                   15913: for each user.  If no $namespace is provided, the default is ids.
                   15914: 
                   15915: =item *
                   15916: X<updateclickers()>
                   15917: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   15918: clicker ID-to-username look-ups in clickers.db on library server.
                   15919: Permitted actions are add or del (i.e., add or delete). The 
                   15920: clickers.db contains clickerID as keys (escaped), and each corresponding
                   15921: value is an escaped comma-separated list of usernames (for whom the
                   15922: library server is the homeserver), who registered that particular ID.
                   15923: If $critical is true, the update will be sent via &critical, otherwise
                   15924: &reply() will be used.
1.191     harris41 15925: 
                   15926: =item *
1.394     bowersj2 15927: X<rolesinit()>
1.1169    droeschl 15928: B<rolesinit($udom,$username)>: get user privileges.
                   15929: returns user role, first access and timer interval hashes
1.243     albertel 15930: 
                   15931: =item *
1.1171    droeschl 15932: X<privileged()>
                   15933: B<privileged($username,$domain)>: returns a true if user has a
                   15934: privileged and active role (i.e. su or dc), false otherwise.
                   15935: 
                   15936: =item *
1.551     albertel 15937: X<getsection()>
                   15938: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 15939: course $cname, return section name/number or '' for "not in course"
                   15940: and '-1' for "no section"
                   15941: 
                   15942: =item *
1.394     bowersj2 15943: X<userenvironment()>
                   15944: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 15945: passed in @what from the requested user's environment, returns a hash
                   15946: 
1.858     raeburn  15947: =item * 
                   15948: X<userlog_query()>
1.859     albertel 15949: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   15950: activity.log file. %filters defines filters applied when parsing the
                   15951: log file. These can be start or end timestamps, or the type of action
                   15952: - log to look for Login or Logout events, check for Checkin or
                   15953: Checkout, role for role selection. The response is in the form
                   15954: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   15955: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  15956: 
1.243     albertel 15957: =back
                   15958: 
                   15959: =head2 User Roles
                   15960: 
                   15961: =over 4
                   15962: 
                   15963: =item *
                   15964: 
1.1284    raeburn  15965: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   15966: returns codes for allowed actions.
                   15967: 
                   15968: The first argument is required, all others are optional.
                   15969: 
                   15970: $priv is the privilege being checked.
                   15971: $uri contains additional information about what is being checked for access (e.g.,
                   15972: URL, course ID etc.). 
                   15973: $symb is the unique resource instance identifier in a course; if needed,
                   15974: but not provided, it will be retrieved via a call to &symbread(). 
                   15975: $role is the role for which a priv is being checked (only used if priv is evb). 
                   15976: $clientip is the user's IP address (only used when checking for access to portfolio 
                   15977: files).
                   15978: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   15979: prevents recursive calls to &allowed.
                   15980: 
1.243     albertel 15981:  F: full access
                   15982:  U,I,K: authentication modes (cxx only)
                   15983:  '': forbidden
                   15984:  1: user needs to choose course
                   15985:  2: browse allowed
1.766     albertel 15986:  A: passphrase authentication needed
1.1284    raeburn  15987:  B: access temporarily blocked because of a blocking event in a course.
1.1402    raeburn  15988:  D: access blocked because access is required via session initiated via deep-link 
1.243     albertel 15989: 
                   15990: =item *
                   15991: 
1.1192    raeburn  15992: constructaccess($url,$setpriv) : check for access to construction space URL
                   15993: 
                   15994: See if the owner domain and name in the URL match those in the
                   15995: expected environment.  If so, return three element list
                   15996: ($ownername,$ownerdomain,$ownerhome).
                   15997: 
                   15998: Otherwise return the null string.
                   15999: 
                   16000: If second argument 'setpriv' is true, it assigns the privileges,
                   16001: and returns the same three element list, unless the owner has
                   16002: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   16003: in which case the null string is returned.
                   16004: 
                   16005: =item *
                   16006: 
1.1326    raeburn  16007: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   16008: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   16009: for system, domain, and course level. $uname and $udom are optional (current
                   16010: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 16011: 
                   16012: =item *
                   16013: 
1.988     raeburn  16014: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   16015: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  16016: $type is Course (default) or Community.
1.988     raeburn  16017: If $forcedefault evaluates to true, text returned will be default 
                   16018: text for $type. Otherwise, if this is a course, the text returned 
                   16019: will be a custom name for the role (if defined in the course's 
                   16020: environment).  If no custom name is defined the default is returned.
                   16021:    
1.832     raeburn  16022: =item *
                   16023: 
1.1219    raeburn  16024: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  16025: All arguments are optional. Returns a hash of a roles, either for
                   16026: co-author/assistant author roles for a user's Construction Space
1.906     albertel 16027: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  16028: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   16029: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   16030: For each key, value is set to colon-separated start and end times for
                   16031: the role.  If no username and domain are specified, will default to
1.934     raeburn  16032: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  16033: of role statuses (active, future or previous), roles 
                   16034: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   16035: to restrict the list of roles reported. If no array ref is 
                   16036: provided for types, will default to return only active roles.
1.834     albertel 16037: 
1.1195    raeburn  16038: =item *
                   16039: 
                   16040: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  16041: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   16042: 
                   16043: Additional optional arguments are: $type (if role checking is to be restricted 
                   16044: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  16045: available roles) or future (roles available in the future), and
                   16046: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  16047: have active Domain Coordinator role in course's domain or in additional
                   16048: domains (specified in 'Domains to check for privileged users' in course
                   16049: environment -- set via:  Course Settings -> Classlists and staff listing).
                   16050: 
                   16051: =item *
                   16052: 
                   16053: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   16054: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   16055: $possdomains and $possroles are optional array refs -- to domains to check and
                   16056: roles to check.  If $possdomains is not specified, a dump will be done of the
                   16057: users' roles.db to check for a dc or su role in any domain. This can be
                   16058: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   16059: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   16060: this then allows &privileged_by_domain() to be used, which caches the identity
                   16061: of privileged users, eliminating the need for repeated calls to &dump().
                   16062: 
                   16063: =item *
                   16064: 
                   16065: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   16066: where the outer hash keys are domains specified in the $possdomains array ref,
                   16067: next inner hash keys are privileged roles specified in the $roles array ref,
                   16068: and the innermost hash contains key = value pairs for username:domain = end:start
                   16069: for active or future "privileged" users with that role in that domain. To avoid
                   16070: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   16071: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  16072: 
1.243     albertel 16073: =back
                   16074: 
                   16075: =head2 User Modification
                   16076: 
                   16077: =over 4
                   16078: 
                   16079: =item *
                   16080: 
1.957     raeburn  16081: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 16082: user for the level given by URL.  Optional start and end dates (leave empty
                   16083: string or zero for "no date")
1.191     harris41 16084: 
                   16085: =item *
                   16086: 
1.243     albertel 16087: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   16088: change a users, password, possible return values are: ok,
                   16089: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   16090: refused
1.191     harris41 16091: 
                   16092: =item *
                   16093: 
1.243     albertel 16094: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 16095: 
                   16096: =item *
                   16097: 
1.1058    raeburn  16098: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   16099:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   16100: 
                   16101: will update user information (firstname,middlename,lastname,generation,
                   16102: permanentemail), and if forceid is true, student/employee ID also.
                   16103: A user's institutional affiliation(s) can also be updated.
                   16104: User information fields will not be overwritten with empty entries 
                   16105: unless the field is included in the $candelete array reference.
                   16106: This array is included when a single user is modified via "Manage Users",
                   16107: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 16108: 
                   16109: =item *
                   16110: 
1.286     matthew  16111: modifystudent
                   16112: 
1.957     raeburn  16113: modify a student's enrollment and identification information.
1.1235    raeburn  16114: The course id is resolved based on the current user's environment.  
                   16115: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  16116: associated with a course.
                   16117: 
1.297     matthew  16118: This call is essentially a wrapper for lonnet::modifyuser and
                   16119: lonnet::modify_student_enrollment
1.286     matthew  16120: 
                   16121: Inputs: 
                   16122: 
                   16123: =over 4
                   16124: 
1.957     raeburn  16125: =item B<$udom> Student's loncapa domain
1.286     matthew  16126: 
1.957     raeburn  16127: =item B<$uname> Student's loncapa login name
1.286     matthew  16128: 
1.964     bisitz   16129: =item B<$uid> Student/Employee ID
1.286     matthew  16130: 
1.957     raeburn  16131: =item B<$umode> Student's authentication mode
1.286     matthew  16132: 
1.957     raeburn  16133: =item B<$upass> Student's password
1.286     matthew  16134: 
1.957     raeburn  16135: =item B<$first> Student's first name
1.286     matthew  16136: 
1.957     raeburn  16137: =item B<$middle> Student's middle name
1.286     matthew  16138: 
1.957     raeburn  16139: =item B<$last> Student's last name
1.286     matthew  16140: 
1.957     raeburn  16141: =item B<$gene> Student's generation
1.286     matthew  16142: 
1.957     raeburn  16143: =item B<$usec> Student's section in course
1.286     matthew  16144: 
                   16145: =item B<$end> Unix time of the roles expiration
                   16146: 
                   16147: =item B<$start> Unix time of the roles start date
                   16148: 
                   16149: =item B<$forceid> If defined, allow $uid to be changed
                   16150: 
                   16151: =item B<$desiredhome> server to use as home server for student
                   16152: 
1.957     raeburn  16153: =item B<$email> Student's permanent e-mail address
                   16154: 
                   16155: =item B<$type> Type of enrollment (auto or manual)
                   16156: 
1.963     raeburn  16157: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   16158: 
                   16159: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  16160: 
1.963     raeburn  16161: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  16162: 
1.963     raeburn  16163: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  16164: 
1.1216    raeburn  16165: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   16166: 
                   16167: =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  16168: 
1.286     matthew  16169: =back
1.297     matthew  16170: 
                   16171: =item *
                   16172: 
                   16173: modify_student_enrollment
                   16174: 
1.1235    raeburn  16175: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  16176: 'role.request.course' must be defined for this function to proceed.
                   16177: 
                   16178: Inputs:
                   16179: 
                   16180: =over 4
                   16181: 
1.1235    raeburn  16182: =item $udom, student's domain
1.297     matthew  16183: 
1.1235    raeburn  16184: =item $uname, student's name
1.297     matthew  16185: 
1.1235    raeburn  16186: =item $uid, student's user id
1.297     matthew  16187: 
1.1235    raeburn  16188: =item $first, student's first name
1.297     matthew  16189: 
                   16190: =item $middle
                   16191: 
                   16192: =item $last
                   16193: 
                   16194: =item $gene
                   16195: 
                   16196: =item $usec
                   16197: 
                   16198: =item $end
                   16199: 
                   16200: =item $start
                   16201: 
1.957     raeburn  16202: =item $type
                   16203: 
                   16204: =item $locktype
                   16205: 
                   16206: =item $cid
                   16207: 
                   16208: =item $selfenroll
                   16209: 
                   16210: =item $context
                   16211: 
1.1216    raeburn  16212: =item $credits, number of credits student will earn from this class
                   16213: 
1.1314    raeburn  16214: =item $instsec, institutional course section code for student
                   16215: 
1.297     matthew  16216: =back
                   16217: 
1.191     harris41 16218: 
                   16219: =item *
                   16220: 
1.243     albertel 16221: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   16222: custom role; give a custom role to a user for the level given by URL.  Specify
                   16223: name and domain of role author, and role name
1.191     harris41 16224: 
                   16225: =item *
                   16226: 
1.243     albertel 16227: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 16228: 
                   16229: =item *
                   16230: 
1.243     albertel 16231: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   16232: 
                   16233: =back
                   16234: 
                   16235: =head2 Course Infomation
                   16236: 
                   16237: =over 4
1.191     harris41 16238: 
                   16239: =item *
                   16240: 
1.1118    foxr     16241: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 16242: specified course id, including all environment settings for the
                   16243: course, the description of the course will be in the hash under the
                   16244: key 'description'
1.191     harris41 16245: 
1.1118    foxr     16246: $options is an optional parameter that if supplied is a hash reference that controls
                   16247: what how this function works.  It has the following key/values:
                   16248: 
                   16249: =over 4
                   16250: 
                   16251: =item freshen_cache
                   16252: 
                   16253: If defined, and the environment cache for the course is valid, it is 
                   16254: returned in the returned hash.
                   16255: 
                   16256: =item one_time
                   16257: 
                   16258: If defined, the last cache time is set to _now_
                   16259: 
                   16260: =item user
                   16261: 
                   16262: If defined, the supplied username is used instead of the current user.
                   16263: 
                   16264: 
                   16265: =back
                   16266: 
1.191     harris41 16267: =item *
                   16268: 
1.624     albertel 16269: resdata($name,$domain,$type,@which) : request for current parameter
                   16270: setting for a specific $type, where $type is either 'course' or 'user',
                   16271: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  16272: answers for 10 minutes.
1.243     albertel 16273: 
1.877     foxr     16274: =item *
                   16275: 
                   16276: get_courseresdata($courseid, $domain) : dump the entire course resource
                   16277: data base, returning a hash that is keyed by the resource name and has
                   16278: values that are the resource value.  I believe that the timestamps and
                   16279: versions are also returned.
                   16280: 
1.1236    raeburn  16281: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   16282: supplemental content area. This routine caches the number of files for 
                   16283: 10 minutes.
                   16284: 
1.243     albertel 16285: =back
                   16286: 
                   16287: =head2 Course Modification
                   16288: 
                   16289: =over 4
1.191     harris41 16290: 
                   16291: =item *
                   16292: 
1.243     albertel 16293: writecoursepref($courseid,%prefs) : write preferences (environment
                   16294: database) for a course
1.191     harris41 16295: 
                   16296: =item *
                   16297: 
1.1011    raeburn  16298: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   16299: 
                   16300: =item *
                   16301: 
1.1038    raeburn  16302: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 16303: 
1.1167    droeschl 16304: =item *
                   16305: 
                   16306: is_course($courseid), is_course($cdom, $cnum)
                   16307: 
                   16308: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   16309: two component version $cdom, $cnum. It checks if the specified course exists.
                   16310: 
                   16311: Returns:
                   16312:     undef if the course doesn't exist, otherwise
                   16313:     in scalar context the combined courseid.
                   16314:     in list context the two components of the course identifier, domain and 
                   16315:     courseid.    
                   16316: 
1.243     albertel 16317: =back
                   16318: 
1.1401    raeburn  16319: =head2 Bubblesheet Configuration
                   16320: 
                   16321: =over 4
                   16322: 
                   16323: =item *
                   16324: 
                   16325: get_scantron_config($which)
                   16326: 
                   16327: $which - the name of the configuration to parse from the file.
                   16328: 
                   16329: Parses and returns the bubblesheet configuration line selected as a
                   16330: hash of configuration file fields.
                   16331: 
                   16332: 
                   16333: Returns:
                   16334:     If the named configuration is not in the file, an empty
                   16335:     hash is returned.
                   16336: 
                   16337:     a hash with the fields
                   16338:       name         - internal name for the this configuration setup
                   16339:       description  - text to display to operator that describes this config
                   16340:       CODElocation - if 0 or the string 'none'
                   16341:                           - no CODE exists for this config
                   16342:                      if -1 || the string 'letter'
                   16343:                           - a CODE exists for this config and is
                   16344:                             a string of letters
                   16345:                      Unsupported value (but planned for future support)
                   16346:                           if a positive integer
                   16347:                                - The CODE exists as the first n items from
                   16348:                                  the question section of the form
                   16349:                           if the string 'number'
                   16350:                                - The CODE exists for this config and is
                   16351:                                  a string of numbers
                   16352:       CODEstart   - (only matter if a CODE exists) column in the line where
                   16353:                      the CODE starts
                   16354:       CODElength  - length of the CODE
                   16355:       IDstart     - column where the student/employee ID starts
                   16356:       IDlength    - length of the student/employee ID info
                   16357:       Qstart      - column where the information from the bubbled
                   16358:                     'questions' start
                   16359:       Qlength     - number of columns comprising a single bubble line from
                   16360:                     the sheet. (usually either 1 or 10)
                   16361:       Qon         - either a single character representing the character used
                   16362:                     to signal a bubble was chosen in the positional setup, or
                   16363:                     the string 'letter' if the letter of the chosen bubble is
                   16364:                     in the final, or 'number' if a number representing the
                   16365:                     chosen bubble is in the file (1->A 0->J)
                   16366:       Qoff        - the character used to represent that a bubble was
                   16367:                     left blank
                   16368:       PaperID     - if the scanning process generates a unique number for each
                   16369:                     sheet scanned the column that this ID number starts in
                   16370:       PaperIDlength - number of columns that comprise the unique ID number
                   16371:                       for the sheet of paper
                   16372:       FirstName   - column that the first name starts in
                   16373:       FirstNameLength - number of columns that the first name spans
                   16374:       LastName    - column that the last name starts in
                   16375:       LastNameLength - number of columns that the last name spans
                   16376:       BubblesPerRow - number of bubbles available in each row used to
                   16377:                       bubble an answer. (If not specified, 10 assumed).
                   16378: 
                   16379: 
                   16380: =item *
                   16381: 
                   16382: get_scantronformat_file($cdom)
                   16383: 
                   16384: $cdom - the course's domain (optional); if not supplied, uses
                   16385: domain for current $env{'request.course.id'}.
                   16386: 
                   16387: Returns an array containing lines from the scantron format file for
                   16388: the domain of the course.
                   16389: 
                   16390: If a url for a custom.tab file is listed in domain's configuration.db,
                   16391: lines are from this file.
                   16392: 
                   16393: Otherwise, if a default.tab has been published in RES space by the
                   16394: domainconfig user, lines are from this file.
                   16395: 
                   16396: Otherwise, fall back to getting lines from the legacy file on the
                   16397: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   16398: 
                   16399: =back
                   16400: 
1.243     albertel 16401: =head2 Resource Subroutines
                   16402: 
                   16403: =over 4
1.191     harris41 16404: 
                   16405: =item *
                   16406: 
1.243     albertel 16407: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 16408: 
                   16409: =item *
                   16410: 
1.243     albertel 16411: repcopy($filename) : subscribes to the requested file, and attempts to
                   16412: replicate from the owning library server, Might return
1.607     raeburn  16413: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   16414: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 16415: resource. Expects the local filesystem pathname
                   16416: (/home/httpd/html/res/....)
                   16417: 
                   16418: =back
                   16419: 
                   16420: =head2 Resource Information
                   16421: 
                   16422: =over 4
1.191     harris41 16423: 
                   16424: =item *
                   16425: 
1.1228    raeburn  16426: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   16427: and returns the value of a variety of different possible values,
                   16428: $varname should be a request string, and the other parameters can be
                   16429: used to specify who and what one is asking about. Ordinarily, $cid 
                   16430: does not need to be specified, as it is retrived from 
                   16431: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   16432: within lonuserstate::loadmap() when initializing a course, before
                   16433: $env{'request.course.id'} has been set, so it needs to be provided
                   16434: in that one case.
1.243     albertel 16435: 
                   16436: Possible values for $varname are environment.lastname (or other item
                   16437: from the envirnment hash), user.name (or someother aspect about the
                   16438: user), resource.0.maxtries (or some other part and parameter of a
                   16439: resource)
1.204     albertel 16440: 
                   16441: =item *
                   16442: 
1.243     albertel 16443: directcondval($number) : get current value of a condition; reads from a state
                   16444: string
1.204     albertel 16445: 
                   16446: =item *
                   16447: 
1.243     albertel 16448: condval($condidx) : value of condition index based on state
1.204     albertel 16449: 
                   16450: =item *
                   16451: 
1.1362    raeburn  16452: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 16453: resource's metadata, $what should be either a specific key, or either
                   16454: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  16455: packages that this resource currently uses, the last 3 arguments are 
                   16456: only used internally for recursive metadata.
                   16457: 
                   16458: the toolsymb is only used where the uri is for an external tool (for which
                   16459: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 16460: 
1.1371    raeburn  16461: this function automatically caches all requests except any made recursively
                   16462: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   16463: defined).
1.191     harris41 16464: 
                   16465: =item *
                   16466: 
1.243     albertel 16467: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   16468: network of library servers; returns file handle of where SQL and regex results
                   16469: will be stored for query
1.191     harris41 16470: 
                   16471: =item *
                   16472: 
1.1282    raeburn  16473: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   16474: return symbolic list entry (all arguments optional). 
                   16475: 
                   16476: Args: filename is the filename (including path) for the file for which a symb 
                   16477: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   16478: to check access status if more than one resource was found in the bighash 
                   16479: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   16480: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   16481: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   16482: cause possible symbs to be checked to determine if they are subject to content
                   16483: blocking, if so they will not be included as possible symbs; possibles is a
                   16484: ref to a hash, which, as a side effect, will be populated with all possible 
                   16485: symbs (content blocking not tested).
                   16486:  
1.243     albertel 16487: returns the data handle
1.191     harris41 16488: 
                   16489: =item *
                   16490: 
1.1190    raeburn  16491: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   16492: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 16493: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  16494: on failure, user must be in a course, as it assumes the existence of
                   16495: the course initial hash, and uses $env('request.course.id'}.  The third
                   16496: arg is an optional reference to a scalar.  If this arg is passed in the 
                   16497: call to symbverify, it will be set to 1 if the symb has been set to be 
                   16498: encrypted; otherwise it will be null.  
1.191     harris41 16499: 
                   16500: =item *
                   16501: 
1.243     albertel 16502: symbclean($symb) : removes versions numbers from a symb, returns the
                   16503: cleaned symb
1.191     harris41 16504: 
                   16505: =item *
                   16506: 
1.243     albertel 16507: is_on_map($uri) : checks if the $uri is somewhere on the current
                   16508: course map, user must be in a course for it to work.
1.191     harris41 16509: 
                   16510: =item *
                   16511: 
1.243     albertel 16512: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 16513: 
                   16514: =item *
                   16515: 
1.243     albertel 16516: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   16517: a random seed, all arguments are optional, if they aren't sent it uses the
                   16518: environment to derive them. Note: if symb isn't sent and it can't get one
                   16519: from &symbread it will use the current time as its return value
1.191     harris41 16520: 
                   16521: =item *
                   16522: 
1.243     albertel 16523: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   16524: unfakeable, receipt
1.191     harris41 16525: 
                   16526: =item *
                   16527: 
1.620     albertel 16528: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 16529: 
                   16530: =item *
                   16531: 
1.243     albertel 16532: countacc($url) : count the number of accesses to a given URL
1.191     harris41 16533: 
                   16534: =item *
                   16535: 
1.243     albertel 16536: 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 16537: 
                   16538: =item *
                   16539: 
1.243     albertel 16540: 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 16541: 
                   16542: =item *
                   16543: 
1.243     albertel 16544: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 16545: 
                   16546: =item *
                   16547: 
1.243     albertel 16548: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   16549: forcing spreadsheet to reevaluate the resource scores next time.
                   16550: 
1.1195    raeburn  16551: =item * 
                   16552: 
1.1196    raeburn  16553: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   16554: when viewing in course context.
1.1195    raeburn  16555: 
1.1196    raeburn  16556:  input: six args -- filename (decluttered), course number, course domain,
                   16557:                     url, symb (if registered) and group (if this is a 
                   16558:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  16559: 
1.1196    raeburn  16560:  output: array of five scalars --
1.1195    raeburn  16561:          $cfile -- url for file editing if editable on current server
                   16562:          $home -- homeserver of resource (i.e., for author if published,
                   16563:                                           or course if uploaded.).
                   16564:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  16565:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   16566:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  16567: 
                   16568: =item *
                   16569: 
                   16570: is_course_upload($file,$cnum,$cdom)
                   16571: 
                   16572: Used in course context to determine if current file was uploaded to 
                   16573: the course (i.e., would be found in /userfiles/docs on the course's 
                   16574: homeserver.
                   16575: 
                   16576:   input: 3 args -- filename (decluttered), course number and course domain.
                   16577:   output: boolean -- 1 if file was uploaded.
                   16578: 
1.243     albertel 16579: =back
                   16580: 
                   16581: =head2 Storing/Retreiving Data
                   16582: 
                   16583: =over 4
1.191     harris41 16584: 
                   16585: =item *
                   16586: 
1.1269    raeburn  16587: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   16588: permanently for this url; hashref needs to be given and should be a \%hashname;
                   16589: the remaining args aren't required and if they aren't passed or are '' they will
                   16590: be derived from the env (with the exception of $laststore, which is an 
                   16591: optional arg used when a user's submission is stored in grading).
                   16592: $laststore is $version=$timestamp, where $version is the most recent version
                   16593: number retrieved for the corresponding $symb in the $namespace db file, and
                   16594: $timestamp is the timestamp for that transaction (UNIX time).
                   16595: $laststore is currently only passed when cstore() is called by 
                   16596: structuretags::finalize_storage().
1.191     harris41 16597: 
                   16598: =item *
                   16599: 
1.1269    raeburn  16600: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   16601: but uses critical subroutine
1.191     harris41 16602: 
                   16603: =item *
                   16604: 
1.243     albertel 16605: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   16606: all args are optional
1.191     harris41 16607: 
                   16608: =item *
                   16609: 
1.717     albertel 16610: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   16611: dumps the complete (or key matching regexp) namespace into a hash
                   16612: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   16613: normally &store()ed into
                   16614: 
                   16615: $range should be either an integer '100' (give me the first 100
                   16616:                                            matching records)
                   16617:               or be  two integers sperated by a - with no spaces
                   16618:                  '30-50' (give me the 30th through the 50th matching
                   16619:                           records)
                   16620: 
                   16621: 
                   16622: =item *
                   16623: 
1.1269    raeburn  16624: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 16625: replaces a &store() version of data with a replacement set of data
                   16626: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  16627: reference. If $tolog is true, the transaction is logged in the courselog
                   16628: with an action=PUTSTORE.
1.717     albertel 16629: 
                   16630: =item *
                   16631: 
1.243     albertel 16632: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   16633: works very similar to store/cstore, but all data is stored in a
                   16634: temporary location and can be reset using tmpreset, $storehash should
                   16635: be a hash reference, returns nothing on success
1.191     harris41 16636: 
                   16637: =item *
                   16638: 
1.243     albertel 16639: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   16640: similar to restore, but all data is stored in a temporary location and
                   16641: can be reset using tmpreset. Returns a hash of values on success,
                   16642: error string otherwise.
1.191     harris41 16643: 
                   16644: =item *
                   16645: 
1.243     albertel 16646: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   16647: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 16648: 
                   16649: =item *
                   16650: 
1.243     albertel 16651: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16652: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 16653: 
                   16654: =item *
                   16655: 
1.243     albertel 16656: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   16657: namesp ($udom and $uname are optional)
1.191     harris41 16658: 
                   16659: =item *
                   16660: 
1.702     albertel 16661: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 16662: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 16663: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  16664: 
1.702     albertel 16665: $range should be either an integer '100' (give me the first 100
                   16666:                                            matching records)
                   16667:               or be  two integers sperated by a - with no spaces
                   16668:                  '30-50' (give me the 30th through the 50th matching
                   16669:                           records)
1.449     matthew  16670: =item *
                   16671: 
                   16672: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   16673: $store can be a scalar, an array reference, or if the amount to be 
                   16674: incremented is > 1, a hash reference.
                   16675: 
                   16676: ($udom and $uname are optional)
1.191     harris41 16677: 
                   16678: =item *
                   16679: 
1.243     albertel 16680: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   16681: ($udom and $uname are optional)
1.191     harris41 16682: 
                   16683: =item *
                   16684: 
1.243     albertel 16685: cput($namespace,$storehash,$udom,$uname) : critical put
                   16686: ($udom and $uname are optional)
1.191     harris41 16687: 
                   16688: =item *
                   16689: 
1.748     albertel 16690: newput($namespace,$storehash,$udom,$uname) :
                   16691: 
                   16692: Attempts to store the items in the $storehash, but only if they don't
                   16693: currently exist, if this succeeds you can be certain that you have 
                   16694: successfully created a new key value pair in the $namespace db.
                   16695: 
                   16696: 
                   16697: Args:
                   16698:  $namespace: name of database to store values to
                   16699:  $storehash: hashref to store to the db
                   16700:  $udom: (optional) domain of user containing the db
                   16701:  $uname: (optional) name of user caontaining the db
                   16702: 
                   16703: Returns:
                   16704:  'ok' -> succeeded in storing all keys of $storehash
                   16705:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   16706:                         least <key> already existed in the db (other
                   16707:                         requested keys may also already exist)
1.967     bisitz   16708:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 16709:  'con_lost' -> unable to contact request server
                   16710:  'refused' -> action was not allowed by remote machine
                   16711: 
                   16712: 
                   16713: =item *
                   16714: 
1.243     albertel 16715: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16716: reference filled in from namesp (encrypts the return communication)
                   16717: ($udom and $uname are optional)
1.191     harris41 16718: 
                   16719: =item *
                   16720: 
1.243     albertel 16721: log($udom,$name,$home,$message) : write to permanent log for user; use
                   16722: critical subroutine
                   16723: 
1.806     raeburn  16724: =item *
                   16725: 
1.860     raeburn  16726: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   16727: array reference filled in from namespace found in domain level on either
                   16728: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  16729: 
                   16730: =item *
                   16731: 
1.860     raeburn  16732: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   16733: domain level either on specified domain server ($uhome) or primary domain 
                   16734: server ($udom and $uhome are optional)
1.806     raeburn  16735: 
1.943     raeburn  16736: =item * 
                   16737: 
1.1240    raeburn  16738: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   16739: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   16740: the target domain.
                   16741: 
                   16742: May also include additional key => value pairs for the following groups:
                   16743: 
                   16744: =over
                   16745: 
                   16746: =item
                   16747: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   16748: 
                   16749: =over
                   16750: 
                   16751: =item defaultquota, authorquota
                   16752: 
                   16753: =back
                   16754: 
                   16755: =item
                   16756: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   16757: portfolio for users).
                   16758: 
                   16759: =over
                   16760: 
                   16761: =item
                   16762: aboutme, blog, webdav, portfolio
                   16763: 
                   16764: =back
                   16765: 
                   16766: =item
                   16767: requestcourses: ability to request courses, and how requests are processed.
                   16768: 
                   16769: =over
                   16770: 
                   16771: =item
1.1305    raeburn  16772: official, unofficial, community, textbook, placement
1.1240    raeburn  16773: 
                   16774: =back
                   16775: 
                   16776: =item
                   16777: inststatus: types of institutional affiliation, and order in which they are displayed.
                   16778: 
                   16779: =over
                   16780: 
                   16781: =item
1.1256    raeburn  16782: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  16783: 
                   16784: =back
                   16785: 
                   16786: =item
                   16787: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   16788: for course's uploaded content.
                   16789: 
                   16790: =over
                   16791: 
                   16792: =item
1.1246    raeburn  16793: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  16794: communityquota, textbookquota, placementquota
1.1240    raeburn  16795: 
                   16796: =back
                   16797: 
                   16798: =item
                   16799: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   16800: on your servers.
                   16801: 
                   16802: =over
                   16803: 
                   16804: =item 
                   16805: remotesessions, hostedsessions
                   16806: 
                   16807: =back
                   16808: 
                   16809: =back
                   16810: 
                   16811: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   16812: utility to create a configuration.db file on a domain's primary library server 
                   16813: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   16814: -- corresponding values are authentication type (internal, krb4, krb5,
                   16815: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   16816: will be available. Values are retrieved from cache (if current), unless the
                   16817: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   16818: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   16819: 
                   16820: Typical usage:
1.943     raeburn  16821: 
1.1240    raeburn  16822: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  16823: 
1.243     albertel 16824: =back
                   16825: 
                   16826: =head2 Network Status Functions
                   16827: 
                   16828: =over 4
1.191     harris41 16829: 
                   16830: =item *
                   16831: 
1.1137    raeburn  16832: dirlist() : return directory list based on URI (first arg).
                   16833: 
                   16834: Inputs: 1 required, 5 optional.
                   16835: 
                   16836: =over
                   16837: 
                   16838: =item 
                   16839: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   16840: 
                   16841: =item
                   16842: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   16843: 
                   16844: =item
                   16845: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   16846: 
                   16847: =item
                   16848: $getpropath - boolean: 1 if prepend path using &propath(). 
                   16849: 
                   16850: =item
                   16851: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   16852: 
                   16853: =item 
                   16854: $alternateRoot - path to prepend in place of path from $uri.
                   16855: 
                   16856: =back
                   16857: 
                   16858: Returns: Array of up to two items.
                   16859: 
                   16860: =over
                   16861: 
                   16862: a reference to an array of files/subdirectories
                   16863: 
                   16864: =over
                   16865: 
                   16866: Each element in the array of files/subdirectories is a & separated list of
                   16867: item name and the result of running stat on the item.  If dirlist was requested
                   16868: for a file instead of a directory, the item name will be ''. For a directory 
                   16869: listing, if the item is a metadata file, the element will end &N&M 
                   16870: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   16871: default copyright set (1).  
                   16872: 
                   16873: =back
                   16874: 
                   16875: a scalar containing error condition (if encountered).
                   16876: 
                   16877: =over
                   16878: 
                   16879: =item 
                   16880: no_host (no homeserver identified for $username:$domain).
                   16881: 
                   16882: =item 
                   16883: no_such_host (server contacted for listing not identified as valid host).
                   16884: 
                   16885: =item 
                   16886: con_lost (connection to remote server failed).
                   16887: 
                   16888: =item 
                   16889: refused (invalid $username:$domain received on lond side).
                   16890: 
                   16891: =item 
                   16892: no_such_dir (directory at specified path on lond side does not exist). 
                   16893: 
                   16894: =item 
                   16895: empty (directory at specified path on lond side is empty).
                   16896: 
                   16897: =over
                   16898: 
                   16899: This is currently not encountered because the &ls3, &ls2, 
                   16900: &ls (_handler) routines on the lond side do not filter out
                   16901: . and .. from a directory listing. 
                   16902: 
                   16903: =back
                   16904: 
                   16905: =back
                   16906: 
                   16907: =back
1.191     harris41 16908: 
                   16909: =item *
                   16910: 
1.243     albertel 16911: spareserver() : find server with least workload from spare.tab
                   16912: 
1.986     foxr     16913: 
                   16914: =item *
                   16915: 
                   16916: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   16917: if there is no corresponding loncapa host.
                   16918: 
1.243     albertel 16919: =back
                   16920: 
1.986     foxr     16921: 
1.243     albertel 16922: =head2 Apache Request
                   16923: 
                   16924: =over 4
1.191     harris41 16925: 
                   16926: =item *
                   16927: 
1.243     albertel 16928: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   16929: localhost, posts hash
                   16930: 
                   16931: =back
                   16932: 
                   16933: =head2 Data to String to Data
                   16934: 
                   16935: =over 4
1.191     harris41 16936: 
                   16937: =item *
                   16938: 
1.243     albertel 16939: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   16940: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 16941: 
                   16942: =item *
                   16943: 
1.243     albertel 16944: hashref2str($hashref) : convert a hashref into a string complete with
                   16945: escaping and '=' and '&' separators, supports elements that are
                   16946: arrayrefs and hashrefs
1.191     harris41 16947: 
                   16948: =item *
                   16949: 
1.243     albertel 16950: arrayref2str($arrayref) : convert an arrayref into a string complete
                   16951: with escaping and '&' separators, supports elements that are arrayrefs
                   16952: and hashrefs
1.191     harris41 16953: 
                   16954: =item *
                   16955: 
1.243     albertel 16956: str2hash($string) : convert string to hash using unescaping and
                   16957: splitting on '=' and '&', supports elements that are arrayrefs and
                   16958: hashrefs
1.191     harris41 16959: 
                   16960: =item *
                   16961: 
1.243     albertel 16962: str2array($string) : convert string to hash using unescaping and
                   16963: splitting on '&', supports elements that are arrayrefs and hashrefs
                   16964: 
                   16965: =back
                   16966: 
                   16967: =head2 Logging Routines
                   16968: 
                   16969: 
                   16970: These routines allow one to make log messages in the lonnet.log and
                   16971: lonnet.perm logfiles.
1.191     harris41 16972: 
1.1119    foxr     16973: =over 4
                   16974: 
1.191     harris41 16975: =item *
                   16976: 
1.243     albertel 16977: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 16978: 
                   16979: =item *
                   16980: 
1.243     albertel 16981: logthis() : append message to the normal lonnet.log file, it gets
                   16982: preiodically rolled over and deleted.
1.191     harris41 16983: 
                   16984: =item *
                   16985: 
1.243     albertel 16986: logperm() : append a permanent message to lonnet.perm.log, this log
                   16987: file never gets deleted by any automated portion of the system, only
                   16988: messages of critical importance should go in here.
                   16989: 
1.1119    foxr     16990: 
1.243     albertel 16991: =back
                   16992: 
                   16993: =head2 General File Helper Routines
                   16994: 
                   16995: =over 4
1.191     harris41 16996: 
                   16997: =item *
                   16998: 
1.481     raeburn  16999: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   17000: (a) files in /uploaded
                   17001:   (i) If a local copy of the file exists - 
                   17002:       compares modification date of local copy with last-modified date for 
                   17003:       definitive version stored on home server for course. If local copy is 
                   17004:       stale, requests a new version from the home server and stores it. 
                   17005:       If the original has been removed from the home server, then local copy 
                   17006:       is unlinked.
                   17007:   (ii) If local copy does not exist -
                   17008:       requests the file from the home server and stores it. 
                   17009:   
                   17010:   If $caller is 'uploadrep':  
                   17011:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   17012:     for request for files originally uploaded via DOCS. 
                   17013:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   17014:   
                   17015:   Otherwise:
                   17016:      This indicates a call from the content generation phase of the request.
                   17017:      -  returns the entire contents of the file or -1.
                   17018:      
                   17019: (b) files in /res
                   17020:    - returns the entire contents of a file or -1; 
                   17021:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 17022: 
1.712     albertel 17023: 
                   17024: =item *
                   17025: 
                   17026: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   17027:                   reference
                   17028: 
                   17029: returns either a stat() list of data about the file or an empty list
                   17030: if the file doesn't exist or couldn't find out about it (connection
                   17031: problems or user unknown)
                   17032: 
1.191     harris41 17033: =item *
                   17034: 
1.243     albertel 17035: filelocation($dir,$file) : returns file system location of a file
                   17036: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   17037: directory that relative $file lookups are to looked in ($dir of /a/dir
                   17038: and a file of ../bob will become /a/bob)
1.191     harris41 17039: 
                   17040: =item *
                   17041: 
                   17042: hreflocation($dir,$file) : returns file system location or a URL; same as
                   17043: filelocation except for hrefs
                   17044: 
                   17045: =item *
                   17046: 
1.1261    raeburn  17047: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   17048: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 17049: 
1.243     albertel 17050: =back
                   17051: 
1.608     albertel 17052: =head2 Usererfile file routines (/uploaded*)
                   17053: 
                   17054: =over 4
                   17055: 
                   17056: =item *
                   17057: 
                   17058: userfileupload(): main rotine for putting a file in a user or course's
                   17059:                   filespace, arguments are,
                   17060: 
1.620     albertel 17061:  formname - required - this is the name of the element in $env where the
1.608     albertel 17062:            filename, and the contents of the file to create/modifed exist
1.620     albertel 17063:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   17064:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  17065:  context - if coursedoc, store the file in the course of the active role
                   17066:              of the current user; 
                   17067:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   17068:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 17069:  subdir - required - subdirectory to put the file in under ../userfiles/
                   17070:          if undefined, it will be placed in "unknown"
                   17071: 
                   17072:  (This routine calls clean_filename() to remove any dangerous
                   17073:  characters from the filename, and then calls finuserfileupload() to
                   17074:  complete the transaction)
                   17075: 
                   17076:  returns either the url of the uploaded file (/uploaded/....) if successful
                   17077:  and /adm/notfound.html if unsuccessful
                   17078: 
                   17079: =item *
                   17080: 
                   17081: clean_filename(): routine for cleaing a filename up for storage in
                   17082:                  userfile space, argument is:
                   17083: 
                   17084:  filename - proposed filename
                   17085: 
                   17086: returns: the new clean filename
                   17087: 
                   17088: =item *
                   17089: 
1.1090    raeburn  17090: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 17091: userspace, probably shouldn't be called directly
                   17092: 
                   17093:   docuname: username or courseid of destination for the file
                   17094:   docudom: domain of user/course of destination for the file
                   17095:   formname: same as for userfileupload()
1.1090    raeburn  17096:   fname: filename (including subdirectories) for the file
                   17097:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401    raeburn  17098:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  17099:   allfiles: reference to hash used to store objects found by parser
                   17100:   codebase: reference to hash used for codebases of java objects found by parser
                   17101:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   17102:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   17103:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   17104:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   17105:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   17106:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  17107:   mimetype: reference to scalar to accommodate mime type determined
                   17108:             from File::MMagic if $parser = parse.
1.608     albertel 17109: 
                   17110:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  17111:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   17112:  was 'overwrite').
                   17113:  
1.608     albertel 17114: 
                   17115: =item *
                   17116: 
                   17117: renameuserfile(): renames an existing userfile to a new name
                   17118: 
                   17119:   Args:
                   17120:    docuname: username or courseid of destination for the file
                   17121:    docudom: domain of user/course of destination for the file
                   17122:    old: current file name (including any subdirs under userfiles)
                   17123:    new: desired file name (including any subdirs under userfiles)
                   17124: 
                   17125: =item *
                   17126: 
                   17127: mkdiruserfile(): creates a directory is a userfiles dir
                   17128: 
                   17129:   Args:
                   17130:    docuname: username or courseid of destination for the file
                   17131:    docudom: domain of user/course of destination for the file
                   17132:    dir: dir to create (including any subdirs under userfiles)
                   17133: 
                   17134: =item *
                   17135: 
                   17136: removeuserfile(): removes a file that exists in userfiles
                   17137: 
                   17138:   Args:
                   17139:    docuname: username or courseid of destination for the file
                   17140:    docudom: domain of user/course of destination for the file
                   17141:    fname: filname to delete (including any subdirs under userfiles)
                   17142: 
                   17143: =item *
                   17144: 
                   17145: removeuploadedurl(): convience function for removeuserfile()
                   17146: 
                   17147:   Args:
                   17148:    url:  a full /uploaded/... url to delete
                   17149: 
1.747     albertel 17150: =item * 
                   17151: 
                   17152: get_portfile_permissions():
                   17153:   Args:
                   17154:     domain: domain of user or course contain the portfolio files
                   17155:     user: name of user or num of course contain the portfolio files
                   17156:   Returns:
                   17157:     hashref of a dump of the proper file_permissions.db
                   17158:    
                   17159: 
                   17160: =item * 
                   17161: 
                   17162: get_access_controls():
                   17163: 
                   17164: Args:
                   17165:   current_permissions: the hash ref returned from get_portfile_permissions()
                   17166:   group: (optional) the group you want the files associated with
                   17167:   file: (optional) the file you want access info on
                   17168: 
                   17169: Returns:
1.749     raeburn  17170:     a hash (keys are file names) of hashes containing
                   17171:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   17172:         values are XML containing access control settings (see below) 
1.747     albertel 17173: 
                   17174: Internal notes:
                   17175: 
1.749     raeburn  17176:  access controls are stored in file_permissions.db as key=value pairs.
                   17177:     key -> path to file/file_name\0uniqueID:scope_end_start
                   17178:         where scope -> public,guest,course,group,domains or users.
                   17179:               end -> UNIX time for end of access (0 -> no end date)
                   17180:               start -> UNIX time for start of access
                   17181: 
                   17182:     value -> XML description of access control
                   17183:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   17184:             <start></start>
                   17185:             <end></end>
                   17186: 
                   17187:             <password></password>  for scope type = guest
                   17188: 
                   17189:             <domain></domain>     for scope type = course or group
                   17190:             <number></number>
                   17191:             <roles id="">
                   17192:              <role></role>
                   17193:              <access></access>
                   17194:              <section></section>
                   17195:              <group></group>
                   17196:             </roles>
                   17197: 
                   17198:             <dom></dom>         for scope type = domains
                   17199: 
                   17200:             <users>             for scope type = users
                   17201:              <user>
                   17202:               <uname></uname>
                   17203:               <udom></udom>
                   17204:              </user>
                   17205:             </users>
                   17206:            </scope> 
                   17207:               
                   17208:  Access data is also aggregated for each file in an additional key=value pair:
                   17209:  key -> path to file/file_name\0accesscontrol 
                   17210:  value -> reference to hash
                   17211:           hash contains key = value pairs
                   17212:           where key = uniqueID:scope_end_start
                   17213:                 value = UNIX time record was last updated
                   17214: 
                   17215:           Used to improve speed of look-ups of access controls for each file.  
                   17216:  
                   17217:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   17218: 
1.1198    raeburn  17219: =item *
                   17220: 
1.749     raeburn  17221: modify_access_controls():
                   17222: 
                   17223: Modifies access controls for a portfolio file
                   17224: Args
                   17225: 1. file name
                   17226: 2. reference to hash of required changes,
                   17227: 3. domain
                   17228: 4. username
                   17229:   where domain,username are the domain of the portfolio owner 
                   17230:   (either a user or a course) 
                   17231: 
                   17232: Returns:
                   17233: 1. result of additions or updates ('ok' or 'error', with error message). 
                   17234: 2. result of deletions ('ok' or 'error', with error message).
                   17235: 3. reference to hash of any new or updated access controls.
                   17236: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   17237:    key = integer (inbound ID)
1.1198    raeburn  17238:    value = uniqueID
                   17239: 
                   17240: =item *
                   17241: 
                   17242: get_timebased_id():
                   17243: 
                   17244: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   17245: course via the Course Editor (e.g., folders, composite pages, 
                   17246: group bulletin boards).
                   17247: 
                   17248: Args: (first three required; six others optional)
                   17249: 
                   17250: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   17251:    docssequence, or name of group
                   17252: 
                   17253: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   17254:    e.g., num, boardids
                   17255: 
                   17256: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   17257:    file will be named nohist_namespace.db
                   17258: 
                   17259: 4. cdom: domain of course; default is current course domain from %env
                   17260: 
                   17261: 5. cnum: course number; default is current course number from %env
                   17262: 
                   17263: 6. idtype: set to concat if an additional digit is to be appended to the 
                   17264:    unix timestamp to form the suffix, if the plain timestamp is already
                   17265:    in use.  Default is to not do this, but simply increment the unix 
                   17266:    timestamp by 1 until a unique key is obtained.
                   17267: 
                   17268: 7. who: holder of locking key; defaults to user:domain for user.
                   17269: 
                   17270: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   17271:    retrying); default is 3.
                   17272: 
                   17273: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   17274: 
                   17275: Returns:
                   17276: 
                   17277: 1. suffix obtained (numeric)
                   17278: 
                   17279: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   17280: 
                   17281: 3. error: contains (localized) error message if an error occurred.
                   17282: 
1.747     albertel 17283: 
1.608     albertel 17284: =back
                   17285: 
1.243     albertel 17286: =head2 HTTP Helper Routines
                   17287: 
                   17288: =over 4
                   17289: 
1.191     harris41 17290: =item *
                   17291: 
                   17292: escape() : unpack non-word characters into CGI-compatible hex codes
                   17293: 
                   17294: =item *
                   17295: 
                   17296: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   17297: 
1.243     albertel 17298: =back
                   17299: 
                   17300: =head1 PRIVATE SUBROUTINES
                   17301: 
                   17302: =head2 Underlying communication routines (Shouldn't call)
                   17303: 
                   17304: =over 4
                   17305: 
                   17306: =item *
                   17307: 
                   17308: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   17309: 
                   17310: =item *
                   17311: 
                   17312: reply() : uses subreply to send a message to remote machine, logs all failures
                   17313: 
                   17314: =item *
                   17315: 
                   17316: critical() : passes a critical message to another server; if cannot
                   17317: get through then place message in connection buffer directory and
                   17318: returns con_delayed, if incapable of saving message, returns
                   17319: con_failed
                   17320: 
                   17321: =item *
                   17322: 
                   17323: reconlonc() : tries to reconnect lonc client processes.
                   17324: 
                   17325: =back
                   17326: 
                   17327: =head2 Resource Access Logging
                   17328: 
                   17329: =over 4
                   17330: 
                   17331: =item *
                   17332: 
                   17333: flushcourselogs() : flush (save) buffer logs and access logs
                   17334: 
                   17335: =item *
                   17336: 
                   17337: courselog($what) : save message for course in hash
                   17338: 
                   17339: =item *
                   17340: 
                   17341: courseacclog($what) : save message for course using &courselog().  Perform
                   17342: special processing for specific resource types (problems, exams, quizzes, etc).
                   17343: 
1.191     harris41 17344: =item *
                   17345: 
                   17346: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   17347: as a PerlChildExitHandler
1.243     albertel 17348: 
                   17349: =back
                   17350: 
                   17351: =head2 Other
                   17352: 
                   17353: =over 4
                   17354: 
                   17355: =item *
                   17356: 
                   17357: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 17358: 
                   17359: =back
                   17360: 
                   17361: =cut
1.877     foxr     17362: 

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