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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.146.  .13(raeb    4:-23): # $Id: lonnet.pm,v 1.1172.2.146.2.12 2023/01/23 18:12:09 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.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
1.1172.2.107  raeburn    77: use CGI::Cookie;
1.977     amueller   78: 
1.1172.2.104  raeburn    79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138    raeburn    80:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1172.2.114  raeburn    81:             %managerstab $passwdmin);
1.871     albertel   82: 
                     83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     84:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     85:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        86:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        87: 
1.1       albertel   88: use IO::Socket;
1.31      www        89: use GDBM_File;
1.208     albertel   90: use HTML::LCParser;
1.88      www        91: use Fcntl qw(:flock);
1.870     albertel   92: use Storable qw(thaw nfreeze);
1.1172.2.79  raeburn    93: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   94: use Cache::Memcached;
1.676     albertel   95: use Digest::MD5;
1.790     albertel   96: use Math::Random;
1.1024    raeburn    97: use File::MMagic;
1.1172.2.142  raeburn    98: use Net::CIDR;
                     99: use Sys::Hostname::FQDN();
1.807     albertel  100: use LONCAPA qw(:DEFAULT :match);
1.740     www       101: use LONCAPA::Configuration;
1.1160    www       102: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   103: use LONCAPA::Lond;
1.1172.2.110  raeburn   104: use LONCAPA::transliterate;
1.1117    foxr      105: 
1.1090    raeburn   106: use File::Copy;
1.676     albertel  107: 
1.195     www       108: my $readit;
1.1172.2.79  raeburn   109: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  110: 
1.619     albertel  111: require Exporter;
                    112: 
                    113: our @ISA = qw (Exporter);
                    114: our @EXPORT = qw(%env);
                    115: 
1.1172.2.9  raeburn   116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       117: {
                    118:     my $logid;
1.1172.2.9  raeburn   119:     sub write_log {
                    120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    121:         if ($context eq 'course') {
                    122:             if (($cnum eq '') || ($cdom eq '')) {
                    123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    125:             }
1.957     raeburn   126:         }
1.1172.2.13  raeburn   127: 	$logid ++;
1.957     raeburn   128:         my $now = time();
                    129: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.146.  .1(raebu  130:22):         my $ip = &get_requestor_ip();
1.1172.2.9  raeburn   131:         my $logentry = {
                    132:                          $id => {
                    133:                                   'exe_uname' => $env{'user.name'},
                    134:                                   'exe_udom'  => $env{'user.domain'},
                    135:                                   'exe_time'  => $now,
1.1172.2.134  raeburn   136:                                   'exe_ip'    => $ip,
1.1172.2.9  raeburn   137:                                   'delflag'   => $delflag,
                    138:                                   'logentry'  => $storehash,
                    139:                                   'uname'     => $uname,
                    140:                                   'udom'      => $udom,
                    141:                                 }
                    142:                        };
                    143:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       144:     }
                    145: }
1.1       albertel  146: 
1.163     harris41  147: sub logtouch {
                    148:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  149:     unless (-e "$execdir/logs/lonnet.log") {	
1.1172.2.96  raeburn   150: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  151: 	close $fh;
                    152:     }
                    153:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    154:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    155: }
                    156: 
1.1       albertel  157: sub logthis {
                    158:     my $message=shift;
                    159:     my $execdir=$perlvar{'lonDaemons'};
                    160:     my $now=time;
                    161:     my $local=localtime($now);
1.1172.2.96  raeburn   162:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      163: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    164: 	print $fh $logstring;
1.448     albertel  165: 	close($fh);
                    166:     }
1.1       albertel  167:     return 1;
                    168: }
                    169: 
                    170: sub logperm {
                    171:     my $message=shift;
                    172:     my $execdir=$perlvar{'lonDaemons'};
                    173:     my $now=time;
                    174:     my $local=localtime($now);
1.1172.2.96  raeburn   175:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  176: 	print $fh "$now:$message:$local\n";
                    177: 	close($fh);
                    178:     }
1.1       albertel  179:     return 1;
                    180: }
                    181: 
1.850     albertel  182: sub create_connection {
1.853     albertel  183:     my ($hostname,$lonid) = @_;
1.851     albertel  184:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  185: 				     Type    => SOCK_STREAM,
                    186: 				     Timeout => 10);
                    187:     return 0 if (!$client);
1.890     albertel  188:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  189:     my $result = <$client>;
                    190:     chomp($result);
                    191:     return 1 if ($result eq 'done');
                    192:     return 0;
                    193: }
                    194: 
1.983     raeburn   195: sub get_server_timezone {
                    196:     my ($cnum,$cdom) = @_;
                    197:     my $home=&homeserver($cnum,$cdom);
                    198:     if ($home ne 'no_host') {
                    199:         my $cachetime = 24*3600;
                    200:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    201:         if (defined($cached)) {
                    202:             return $timezone;
                    203:         } else {
                    204:             my $timezone = &reply('servertimezone',$home);
                    205:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    206:         }
                    207:     }
                    208: }
1.850     albertel  209: 
1.1106    raeburn   210: sub get_server_distarch {
                    211:     my ($lonhost,$ignore_cache) = @_;
                    212:     if (defined($lonhost)) {
                    213:         if (!defined(&hostname($lonhost))) {
                    214:             return;
                    215:         }
                    216:         my $cachetime = 12*3600;
                    217:         if (!$ignore_cache) {
                    218:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    219:             if (defined($cached)) {
                    220:                 return $distarch;
                    221:             }
                    222:         }
                    223:         my $rep = &reply('serverdistarch',$lonhost);
                    224:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    225:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    226:                 $rep eq '') {
                    227:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    228:         }
                    229:     }
                    230:     return;
                    231: }
                    232: 
1.993     raeburn   233: sub get_server_loncaparev {
1.1073    raeburn   234:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   235:     if (defined($lonhost)) {
                    236:         if (!defined(&hostname($lonhost))) {
                    237:             undef($lonhost);
                    238:         }
                    239:     }
                    240:     if (!defined($lonhost)) {
                    241:         if (defined(&domain($dom,'primary'))) {
                    242:             $lonhost=&domain($dom,'primary');
                    243:             if ($lonhost eq 'no_host') {
                    244:                 undef($lonhost);
                    245:             }
                    246:         }
                    247:     }
                    248:     if (defined($lonhost)) {
1.1073    raeburn   249:         my $cachetime = 12*3600;
                    250:         if (!$ignore_cache) {
                    251:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    252:             if (defined($cached)) {
                    253:                 return $loncaparev;
                    254:             }
                    255:         }
                    256:         my ($answer,$loncaparev);
                    257:         my @ids=&current_machine_ids();
                    258:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    259:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   260:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   261:                 $loncaparev = $1;
                    262:             }
                    263:         } else {
                    264:             $answer = &reply('serverloncaparev',$lonhost);
                    265:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    266:                 if ($caller eq 'loncron') {
                    267:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   268:                     $ua->timeout(4);
1.1172.2.120  raeburn   269:                     my $hostname = &hostname($lonhost);
1.1073    raeburn   270:                     my $protocol = $protocol{$lonhost};
                    271:                     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn   272:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   273:                     my $request=new HTTP::Request('GET',$url);
                    274:                     my $response=$ua->request($request);
                    275:                     unless ($response->is_error()) {
                    276:                         my $content = $response->content;
1.1081    raeburn   277:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   278:                             $loncaparev = $1;
                    279:                         }
                    280:                     }
                    281:                 } else {
                    282:                     $loncaparev = $loncaparevs{$lonhost};
                    283:                 }
1.1081    raeburn   284:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   285:                 $loncaparev = $1;
                    286:             }
1.993     raeburn   287:         }
1.1073    raeburn   288:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   289:     }
                    290: }
                    291: 
1.1074    raeburn   292: sub get_server_homeID {
                    293:     my ($hostname,$ignore_cache,$caller) = @_;
                    294:     unless ($ignore_cache) {
                    295:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    296:         if (defined($cached)) {
                    297:             return $serverhomeID;
                    298:         }
                    299:     }
                    300:     my $cachetime = 12*3600;
                    301:     my $serverhomeID;
                    302:     if ($caller eq 'loncron') { 
                    303:         my @machine_ids = &machine_ids($hostname);
                    304:         foreach my $id (@machine_ids) {
                    305:             my $response = &reply('serverhomeID',$id);
                    306:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    307:                 $serverhomeID = $response;
                    308:                 last;
                    309:             }
                    310:         }
                    311:         if ($serverhomeID eq '') {
                    312:             $serverhomeID = $machine_ids[-1];
                    313:         }
                    314:     } else {
                    315:         $serverhomeID = $serverhomeIDs{$hostname};
                    316:     }
                    317:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    318: }
                    319: 
1.1121    raeburn   320: sub get_remote_globals {
                    321:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   322:     my ($result,%returnhash,%whatneeded);
                    323:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   324:         foreach my $what (sort(keys(%{$whathash}))) {
                    325:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   326:             my ($response,$cached);
1.1121    raeburn   327:             unless ($ignore_cache) {
1.1125    raeburn   328:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   329:             }
                    330:             if (defined($cached)) {
1.1125    raeburn   331:                 $returnhash{$what} = $response;
1.1121    raeburn   332:             } else {
1.1125    raeburn   333:                 $whatneeded{$what} = 1;
1.1121    raeburn   334:             }
                    335:         }
1.1125    raeburn   336:         if (keys(%whatneeded) == 0) {
                    337:             $result = 'ok';
                    338:         } else {
1.1121    raeburn   339:             my $requested = &freeze_escape(\%whatneeded);
                    340:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   341:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    342:                 ($rep eq 'unknown_cmd')) {
                    343:                 $result = $rep;
                    344:             } else {
                    345:                 $result = 'ok';
1.1121    raeburn   346:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   347:                 foreach my $item (@pairs) {
                    348:                     my ($key,$value)=split(/=/,$item,2);
                    349:                     my $what = &unescape($key);
                    350:                     my $hashid = $lonhost.'-'.$what;
                    351:                     $returnhash{$what}=&thaw_unescape($value);
                    352:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   353:                 }
                    354:             }
                    355:         }
                    356:     }
1.1125    raeburn   357:     return ($result,\%returnhash);
1.1121    raeburn   358: }
                    359: 
1.1124    raeburn   360: sub remote_devalidate_cache {
1.1172.2.35  raeburn   361:     my ($lonhost,$cachekeys) = @_;
                    362:     my $items;
                    363:     return unless (ref($cachekeys) eq 'ARRAY');
                    364:     my $cachestr = join('&',@{$cachekeys});
                    365:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   366: }
                    367: 
1.1172.2.146.  .13(raeb  368:-23): sub sign_lti {
                    369:-23):     my ($cdom,$cnum,$crsdef,$type,$context,$url,$ltinum,$keynum,$paramsref,$inforef) = @_;
                    370:-23):     my $chome;
                    371:-23):     if (&domain($cdom) ne '') {
                    372:-23):         if ($crsdef) {
                    373:-23):             $chome = &homeserver($cnum,$cdom);
                    374:-23):         } else {
                    375:-23):             $chome = &domain($cdom,'primary');
                    376:-23):         }
                    377:-23):     }
                    378:-23):     if ($cdom && $chome && ($chome ne 'no_host')) {
                    379:-23):         if ((ref($paramsref) eq 'HASH') &&
                    380:-23):             (ref($inforef) eq 'HASH')) {
                    381:-23):             my $rep;
                    382:-23):             if (grep { $_ eq $chome } &current_machine_ids()) {
                    383:-23):                 # domain information is hosted on this machine
                    384:-23):                 $rep =
                    385:-23):                     &LONCAPA::Lond::sign_lti_payload($cdom,$cnum,$crsdef,$type,
                    386:-23):                                                      $context,$url,$ltinum,$keynum,
                    387:-23):                                                      $perlvar{'lonVersion'},
                    388:-23):                                                      $paramsref,$inforef);
                    389:-23):                 if (ref($rep) eq 'HASH') {
                    390:-23):                     return ('ok',$rep);
                    391:-23):                 }
                    392:-23):             } else {
                    393:-23):                 my ($escurl,$params,$info);
                    394:-23):                 $escurl = &escape($url);
                    395:-23):                 if (ref($paramsref) eq 'HASH') {
                    396:-23):                     $params = &freeze_escape($paramsref);
                    397:-23):                 }
                    398:-23):                 if (ref($inforef) eq 'HASH') {
                    399:-23):                     $info = &freeze_escape($inforef);
                    400:-23):                 }
                    401:-23):                 $rep=&reply("encrypt:signlti:$cdom:$cnum:$crsdef:$type:$context:$escurl:$ltinum:$keynum:$params:$info",$chome);
                    402:-23):             }
                    403:-23):             if (($rep eq '') || ($rep =~ /^con_lost|error|no_such_host|unknown_cmd/i)) {
                    404:-23):                 return ();
                    405:-23):             } elsif (($inforef->{'respfmt'} eq 'to_post_body') ||
                    406:-23):                      ($inforef->{'respfmt'} eq 'to_authorization_header')) {
                    407:-23):                 return ('ok',$rep);
                    408:-23):             } else {
                    409:-23):                 my %returnhash;
                    410:-23):                 foreach my $item (split(/\&/,$rep)) {
                    411:-23):                     my ($name,$value)=split(/\=/,$item);
                    412:-23):                     $returnhash{&unescape($name)}=&thaw_unescape($value);
                    413:-23):                 }
                    414:-23):                 return('ok',\%returnhash);
                    415:-23):             }
                    416:-23):         } else {
                    417:-23):             return ();
                    418:-23):         }
                    419:-23):     } else {
                    420:-23):         return ();
                    421:-23):         &logthis("sign_lti failed - no homeserver and/or domain ($cdom) ($chome)");
                    422:-23):     }
                    423:-23): }
                    424:-23): 
1.1       albertel  425: # -------------------------------------------------- Non-critical communication
                    426: sub subreply {
                    427:     my ($cmd,$server)=@_;
1.838     albertel  428:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      429:     #
                    430:     #  With loncnew process trimming, there's a timing hole between lonc server
                    431:     #  process exit and the master server picking up the listen on the AF_UNIX
                    432:     #  socket.  In that time interval, a lock file will exist:
                    433: 
                    434:     my $lockfile=$peerfile.".lock";
                    435:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   436: 	sleep(0.1);
1.549     foxr      437:     }
                    438:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      439:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      440:     #
1.550     foxr      441:     #   We'll give the connection a few tries before abandoning it.  If
                    442:     #   connection is not possible, we'll con_lost back to the client.
                    443:     #   
                    444:     my $client;
                    445:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    446: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    447: 				      Type    => SOCK_STREAM,
                    448: 				      Timeout => 10);
1.869     albertel  449: 	if ($client) {
1.550     foxr      450: 	    last;		# Connected!
1.850     albertel  451: 	} else {
1.853     albertel  452: 	    &create_connection(&hostname($server),$server);
1.550     foxr      453: 	}
1.1172.2.79  raeburn   454:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      455:     }
                    456:     my $answer;
                    457:     if ($client) {
1.704     albertel  458: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      459: 	$answer=<$client>;
                    460: 	if (!$answer) { $answer="con_lost"; }
                    461: 	chomp($answer);
                    462:     } else {
                    463: 	$answer = 'con_lost';	# Failed connection.
                    464:     }
1.1       albertel  465:     return $answer;
                    466: }
                    467: 
                    468: sub reply {
                    469:     my ($cmd,$server)=@_;
1.838     albertel  470:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  471:     my $answer=subreply($cmd,$server);
1.65      www       472:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111  raeburn   473:         my $logged = $cmd;
                    474:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    475:             my $subcmd = $1;
                    476:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    477:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1172.2.146.  .13(raeb  478:-23):                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
                    479:-23):                 ($subcmd eq 'put')) {
1.1172.2.111  raeburn   480:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    481:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    482:                     splice(@rest,2,1,'Hidden');
                    483:                 } elsif ($subcmd eq 'passwd') {
                    484:                     splice(@rest,2,2,('Hidden','Hidden'));
                    485:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1172.2.146.  .13(raeb  486:-23):                          ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
1.1172.2.111  raeburn   487:                     splice(@rest,3,1,'Hidden');
                    488:                 }
                    489:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    490:             }
                    491:         }
                    492:         &logthis("<font color=\"blue\">WARNING:".
                    493:                  " $logged to $server returned $answer</font>");
1.12      www       494:     }
1.1       albertel  495:     return $answer;
                    496: }
                    497: 
                    498: # ----------------------------------------------------------- Send USR1 to lonc
                    499: 
                    500: sub reconlonc {
1.891     albertel  501:     my ($lonid) = @_;
                    502:     if ($lonid) {
1.1172.2.72  raeburn   503:         my $hostname = &hostname($lonid);
1.891     albertel  504: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    505: 	if ($hostname && -e $peerfile) {
                    506: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    507: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    508: 					     Type    => SOCK_STREAM,
                    509: 					     Timeout => 10);
                    510: 	    if ($client) {
                    511: 		print $client ("reset_retries\n");
                    512: 		my $answer=<$client>;
                    513: 		#reset just this one.
                    514: 	    }
                    515: 	}
                    516: 	return;
                    517:     }
                    518: 
1.836     www       519:     &logthis("Trying to reconnect lonc");
1.1       albertel  520:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96  raeburn   521:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  522: 	my $loncpid=<$fh>;
                    523:         chomp($loncpid);
                    524:         if (kill 0 => $loncpid) {
                    525: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    526:             kill USR1 => $loncpid;
                    527:             sleep 1;
1.836     www       528:          } else {
1.12      www       529: 	    &logthis(
1.672     albertel  530:                "<font color=\"blue\">WARNING:".
1.12      www       531:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  532:         }
                    533:     } else {
1.836     www       534: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  535:     }
                    536: }
                    537: 
                    538: # ------------------------------------------------------ Critical communication
1.12      www       539: 
1.1       albertel  540: sub critical {
                    541:     my ($cmd,$server)=@_;
1.838     albertel  542:     unless (&hostname($server)) {
1.672     albertel  543:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       544:                " Critical message to unknown server ($server)</font>");
                    545:         return 'no_such_host';
                    546:     }
1.1       albertel  547:     my $answer=reply($cmd,$server);
                    548:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   549: 	&reconlonc($server);
1.589     albertel  550: 	my $answer=reply($cmd,$server);
1.1       albertel  551:         if ($answer eq 'con_lost') {
                    552:             my $now=time;
                    553:             my $middlename=$cmd;
1.5       www       554:             $middlename=substr($middlename,0,16);
1.1       albertel  555:             $middlename=~s/\W//g;
                    556:             my $dfilename=
1.305     www       557:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    558:             $dumpcount++;
1.1       albertel  559:             {
1.448     albertel  560: 		my $dfh;
1.1172.2.96  raeburn   561: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  562: 		    print $dfh "$cmd\n"; 
                    563: 		    close($dfh);
                    564: 		}
1.1       albertel  565:             }
1.1172.2.79  raeburn   566:             sleep 1;
1.1       albertel  567:             my $wcmd='';
                    568:             {
1.448     albertel  569: 		my $dfh;
1.1172.2.96  raeburn   570: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  571: 		    $wcmd=<$dfh>; 
                    572: 		    close($dfh);
                    573: 		}
1.1       albertel  574:             }
                    575:             chomp($wcmd);
1.7       www       576:             if ($wcmd eq $cmd) {
1.672     albertel  577: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       578:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  579:                 &logperm("D:$server:$cmd");
                    580: 	        return 'con_delayed';
                    581:             } else {
1.672     albertel  582:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       583:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  584:                 &logperm("F:$server:$cmd");
                    585:                 return 'con_failed';
                    586:             }
                    587:         }
                    588:     }
                    589:     return $answer;
1.405     albertel  590: }
                    591: 
1.755     albertel  592: # ------------------------------------------- check if return value is an error
                    593: 
                    594: sub error {
                    595:     my ($result) = @_;
1.756     albertel  596:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  597: 	if ($2 == 2) { return undef; }
                    598: 	return $1;
                    599:     }
                    600:     return undef;
                    601: }
                    602: 
1.783     albertel  603: sub convert_and_load_session_env {
                    604:     my ($lonidsdir,$handle)=@_;
                    605:     my @profile;
                    606:     {
1.917     albertel  607: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    608: 	if (!$opened) {
1.915     albertel  609: 	    return 0;
                    610: 	}
1.783     albertel  611: 	flock($idf,LOCK_SH);
                    612: 	@profile=<$idf>;
                    613: 	close($idf);
                    614:     }
                    615:     my %temp_env;
                    616:     foreach my $line (@profile) {
1.786     albertel  617: 	if ($line !~ m/=/) {
                    618: 	    return 0;
                    619: 	}
1.783     albertel  620: 	chomp($line);
                    621: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    622: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    623:     }
                    624:     unlink("$lonidsdir/$handle.id");
                    625:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    626: 	    0640)) {
                    627: 	%disk_env = %temp_env;
                    628: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    629: 	untie(%disk_env);
                    630:     }
1.786     albertel  631:     return 1;
1.783     albertel  632: }
                    633: 
1.374     www       634: # ------------------------------------------- Transfer profile into environment
1.780     albertel  635: my $env_loaded;
                    636: sub transfer_profile_to_env {
1.788     albertel  637:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    638:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       639: 
1.720     albertel  640:     if (!defined($lonidsdir)) {
                    641: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    642:     }
                    643:     if (!defined($handle)) {
                    644:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    645:     }
                    646: 
1.786     albertel  647:     my $convert;
                    648:     {
1.917     albertel  649:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    650: 	if (!$opened) {
1.915     albertel  651: 	    return;
                    652: 	}
1.786     albertel  653: 	flock($idf,LOCK_SH);
                    654: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    655: 		&GDBM_READER(),0640)) {
                    656: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    657: 	    untie(%disk_env);
                    658: 	} else {
                    659: 	    $convert = 1;
                    660: 	}
                    661:     }
                    662:     if ($convert) {
                    663: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    664: 	    &logthis("Failed to load session, or convert session.");
                    665: 	}
1.374     www       666:     }
1.783     albertel  667: 
1.786     albertel  668:     my %remove;
1.783     albertel  669:     while ( my $envname = each(%env) ) {
1.433     matthew   670:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    671:             if ($time < time-300) {
1.783     albertel  672:                 $remove{$key}++;
1.433     matthew   673:             }
                    674:         }
                    675:     }
1.783     albertel  676: 
1.619     albertel  677:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  678:     $env_loaded=1;
1.783     albertel  679:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   680:         &delenv($expired_key);
1.374     www       681:     }
1.1       albertel  682: }
                    683: 
1.916     albertel  684: # ---------------------------------------------------- Check for valid session 
                    685: sub check_for_valid_session {
1.1172.2.96  raeburn   686:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  687:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108  raeburn   688:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155    raeburn   689:     if ($name eq 'lonDAV') {
                    690:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    691:     } else {
                    692:         $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108  raeburn   693:         if ($name eq '') {
                    694:             $name = 'lonID';
                    695:         }
                    696:     }
                    697:     if ($name eq 'lonID') {
                    698:         $secure = 'lonSID';
                    699:         $linkname = 'lonLinkID';
                    700:         $pubname = 'lonPubID';
                    701:         if (exists($cookies{$secure})) {
                    702:             $lonid=$cookies{$secure};
                    703:         } elsif (exists($cookies{$name})) {
                    704:             $lonid=$cookies{$name};
                    705:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
                    706:             $lonid=$cookies{$linkname};
                    707:         } elsif (exists($cookies{$pubname})) {
                    708:             $lonid=$cookies{$pubname};
                    709:         }
                    710:     } else {
                    711:         $lonid=$cookies{$name};
                    712:     }
                    713:     return undef if (!$lonid);
                    714: 
                    715:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    716:     if (-l "$lonidsdir/$handle.id") {
                    717:         my $link = readlink("$lonidsdir/$handle.id");
                    718:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    719:             $handle = $1;
                    720:         }
1.1155    raeburn   721:     }
1.1172.2.96  raeburn   722:     if (!-e "$lonidsdir/$handle.id") {
                    723:         if ((ref($domref)) && ($name eq 'lonID') &&
                    724:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    725:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    726:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    727:                 $$domref = $possudom;
                    728:             }
                    729:         }
                    730:         return undef;
                    731:     }
1.916     albertel  732: 
1.917     albertel  733:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    734:     return undef if (!$opened);
1.916     albertel  735: 
                    736:     flock($idf,LOCK_SH);
                    737:     my %disk_env;
                    738:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    739: 	    &GDBM_READER(),0640)) {
                    740: 	return undef;	
                    741:     }
                    742: 
                    743:     if (!defined($disk_env{'user.name'})
                    744: 	|| !defined($disk_env{'user.domain'})) {
1.1172.2.107  raeburn   745:         untie(%disk_env);
1.916     albertel  746: 	return undef;
                    747:     }
1.1172.2.18  raeburn   748: 
1.1172.2.36  raeburn   749:     if (ref($userhashref) eq 'HASH') {
                    750:         $userhashref->{'name'} = $disk_env{'user.name'};
                    751:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.142  raeburn   752:         if ($disk_env{'request.role'}) {
                    753:             $userhashref->{'role'} = $disk_env{'request.role'};
                    754:         }
1.1172.2.146.  .13(raeb  755:-23):         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
                    756:-23):         if ($userhashref->{'lti'}) {
                    757:-23):             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
                    758:-23):             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
                    759:-23):         }
1.1172.2.18  raeburn   760:     }
1.1172.2.107  raeburn   761:     untie(%disk_env);
1.1172.2.18  raeburn   762: 
1.916     albertel  763:     return $handle;
                    764: }
                    765: 
1.830     albertel  766: sub timed_flock {
                    767:     my ($file,$lock_type) = @_;
                    768:     my $failed=0;
                    769:     eval {
                    770: 	local $SIG{__DIE__}='DEFAULT';
                    771: 	local $SIG{ALRM}=sub {
                    772: 	    $failed=1;
                    773: 	    die("failed lock");
                    774: 	};
                    775: 	alarm(13);
                    776: 	flock($file,$lock_type);
                    777: 	alarm(0);
                    778:     };
                    779:     if ($failed) {
                    780: 	return undef;
                    781:     } else {
                    782: 	return 1;
                    783:     }
                    784: }
                    785: 
1.1172.2.107  raeburn   786: sub get_sessionfile_vars {
                    787:     my ($handle,$lonidsdir,$storearr) = @_;
                    788:     my %returnhash;
                    789:     unless (ref($storearr) eq 'ARRAY') {
                    790:         return %returnhash;
                    791:     }
                    792:     if (-l "$lonidsdir/$handle.id") {
                    793:         my $link = readlink("$lonidsdir/$handle.id");
                    794:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    795:             $handle = $1;
                    796:         }
                    797:     }
                    798:     if ((-e "$lonidsdir/$handle.id") &&
                    799:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    800:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    801:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    802:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    803:                 flock($idf,LOCK_SH);
                    804:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    805:                         &GDBM_READER(),0640)) {
                    806:                     foreach my $item (@{$storearr}) {
                    807:                         $returnhash{$item} = $disk_env{$item};
                    808:                     }
                    809:                     untie(%disk_env);
                    810:                 }
                    811:             }
                    812:         }
                    813:     }
                    814:     return %returnhash;
                    815: }
                    816: 
1.5       www       817: # ---------------------------------------------------------- Append Environment
                    818: 
                    819: sub appenv {
1.949     raeburn   820:     my ($newenv,$roles) = @_;
                    821:     if (ref($newenv) eq 'HASH') {
                    822:         foreach my $key (keys(%{$newenv})) {
                    823:             my $refused = 0;
                    824: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    825:                 $refused = 1;
                    826:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   827:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   828:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    829:                         $refused = 0;
                    830:                     }
                    831:                 }
                    832:             }
                    833:             if ($refused) {
                    834:                 &logthis("<font color=\"blue\">WARNING: ".
                    835:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    836:                          .'</font>');
                    837: 	        delete($newenv->{$key});
                    838:             } else {
                    839:                 $env{$key}=$newenv->{$key};
                    840:             }
                    841:         }
1.1172.2.96  raeburn   842:         my $lonids = $perlvar{'lonIDsDir'};
                    843:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    844:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    845:             if ($opened
                    846: 	        && &timed_flock($env_file,LOCK_EX)
                    847: 	        &&
                    848: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    849: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    850: 	        while (my ($key,$value) = each(%{$newenv})) {
                    851: 	            $disk_env{$key} = $value;
                    852: 	        }
                    853: 	        untie(%disk_env);
                    854:             }
1.35      www       855:         }
1.191     harris41  856:     }
1.56      www       857:     return 'ok';
                    858: }
                    859: # ----------------------------------------------------- Delete from Environment
                    860: 
                    861: sub delenv {
1.1104    raeburn   862:     my ($delthis,$regexp,$roles) = @_;
                    863:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    864:         my $refused = 1;
                    865:         if (ref($roles) eq 'ARRAY') {
                    866:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    867:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    868:                 $refused = 0;
                    869:             }
                    870:         }
                    871:         if ($refused) {
                    872:             &logthis("<font color=\"blue\">WARNING: ".
                    873:                      "Attempt to delete from environment ".$delthis);
                    874:             return 'error';
                    875:         }
1.56      www       876:     }
1.917     albertel  877:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    878:     if ($opened
1.915     albertel  879: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  880: 	&&
                    881: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    882: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  883: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   884: 	    if ($regexp) {
                    885:                 if ($key=~/^$delthis/) {
                    886:                     delete($env{$key});
                    887:                     delete($disk_env{$key});
                    888:                 } 
                    889:             } else {
                    890:                 if ($key=~/^\Q$delthis\E/) {
                    891: 		    delete($env{$key});
                    892: 		    delete($disk_env{$key});
                    893: 	        }
                    894:             }
1.448     albertel  895: 	}
1.783     albertel  896: 	untie(%disk_env);
1.5       www       897:     }
                    898:     return 'ok';
1.369     albertel  899: }
                    900: 
1.790     albertel  901: sub get_env_multiple {
                    902:     my ($name) = @_;
                    903:     my @values;
                    904:     if (defined($env{$name})) {
                    905:         # exists is it an array
                    906:         if (ref($env{$name})) {
                    907:             @values=@{ $env{$name} };
                    908:         } else {
                    909:             $values[0]=$env{$name};
                    910:         }
                    911:     }
                    912:     return(@values);
                    913: }
                    914: 
1.958     www       915: # ------------------------------------------------------------------- Locking
                    916: 
                    917: sub set_lock {
                    918:     my ($text)=@_;
                    919:     $locknum++;
                    920:     my $id=$$.'-'.$locknum;
                    921:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    922:              'session.lock.'.$id => $text});
                    923:     return $id;
                    924: }
                    925: 
                    926: sub get_locks {
                    927:     my $num=0;
                    928:     my %texts=();
                    929:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    930:        if ($lock=~/\w/) {
                    931:           $num++;
                    932:           $texts{$lock}=$env{'session.lock.'.$lock};
                    933:        }
                    934:    }
                    935:    return ($num,%texts);
                    936: }
                    937: 
                    938: sub remove_lock {
                    939:     my ($id)=@_;
                    940:     my $newlocks='';
                    941:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    942:        if (($lock=~/\w/) && ($lock ne $id)) {
                    943:           $newlocks.=','.$lock;
                    944:        }
                    945:     }
                    946:     &appenv({'session.locks' => $newlocks});
                    947:     &delenv('session.lock.'.$id);
                    948: }
                    949: 
                    950: sub remove_all_locks {
                    951:     my $activelocks=$env{'session.locks'};
                    952:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    953:        if ($lock=~/\w/) {
                    954:           &remove_lock($lock);
                    955:        }
                    956:     }
                    957: }
                    958: 
                    959: 
1.369     albertel  960: # ------------------------------------------ Find out current server userload
                    961: sub userload {
                    962:     my $numusers=0;
                    963:     {
                    964: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    965: 	my $filename;
                    966: 	my $curtime=time;
                    967: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  968: 	    next if ($filename eq '.' || $filename eq '..');
                    969: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112  raeburn   970:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  971: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  972: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  973: 	}
                    974: 	closedir(LONIDS);
                    975:     }
                    976:     my $userloadpercent=0;
                    977:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    978:     if ($maxuserload) {
1.371     albertel  979: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  980:     }
1.372     albertel  981:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  982:     return $userloadpercent;
1.283     www       983: }
                    984: 
1.1       albertel  985: # ------------------------------ Find server with least workload from spare.tab
1.11      www       986: 
1.1       albertel  987: sub spareserver {
1.1172.2.142  raeburn   988:     my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  989:     my $spare_server;
1.370     albertel  990:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  991:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    992:                                                      :  $userloadpercent;
1.1083    raeburn   993:     my ($uint_dom,$remotesessions);
                    994:     if (($udom ne '') && (&domain($udom) ne '')) {
                    995:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    996:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    997:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    998:         $remotesessions = $udomdefaults{'remotesessions'};
                    999:     }
1.1123    raeburn  1000:     my $spareshash = &this_host_spares($udom);
                   1001:     if (ref($spareshash) eq 'HASH') {
                   1002:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1003:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn  1004:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                   1005:                                              $try_server));
1.1123    raeburn  1006: 	        ($spare_server, $lowest_load) =
                   1007: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                   1008:             }
1.1083    raeburn  1009:         }
1.784     albertel 1010: 
1.1123    raeburn  1011:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                   1012: 
                   1013:         if (!$found_server) {
                   1014:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                   1015: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn  1016:                     next unless (&spare_can_host($udom,$uint_dom,
                   1017:                                                  $remotesessions,$try_server));
1.1123    raeburn  1018: 	            ($spare_server, $lowest_load) =
                   1019: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                   1020:                 }
                   1021: 	    }
                   1022:         }
1.784     albertel 1023:     }
                   1024: 
                   1025:     if (!$want_server_name) {
1.1001    raeburn  1026:         if (defined($spare_server)) {
                   1027:             my $hostname = &hostname($spare_server);
1.1083    raeburn  1028:             if (defined($hostname)) {
1.1172.2.120  raeburn  1029:                 my $protocol = 'http';
                   1030:                 if ($protocol{$spare_server} eq 'https') {
                   1031:                     $protocol = $protocol{$spare_server};
                   1032:                 }
1.1172.2.142  raeburn  1033:                 my $alias = &Apache::lonnet::use_proxy_alias($r,$spare_server);
                   1034:                 $hostname = $alias if ($alias ne '');
1.1001    raeburn  1035: 	        $spare_server = $protocol.'://'.$hostname;
                   1036:             }
                   1037:         }
1.784     albertel 1038:     }
                   1039:     return $spare_server;
                   1040: }
                   1041: 
                   1042: sub compare_server_load {
1.1172.2.41  raeburn  1043:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                   1044: 
                   1045:     if ($required) {
                   1046:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   1047:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1048:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   1049:         if (($major eq '' && $minor eq '') ||
                   1050:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   1051:             return ($spare_server,$lowest_load);
                   1052:         }
                   1053:     }
1.784     albertel 1054: 
                   1055:     my $loadans     = &reply('load',    $try_server);
                   1056:     my $userloadans = &reply('userload',$try_server);
                   1057: 
                   1058:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn  1059: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel 1060:     }
                   1061: 
                   1062:     my $load;
                   1063:     if ($loadans =~ /\d/) {
                   1064: 	if ($userloadans =~ /\d/) {
                   1065: 	    #both are numbers, pick the bigger one
                   1066: 	    $load = ($loadans > $userloadans) ? $loadans 
                   1067: 		                              : $userloadans;
1.411     albertel 1068: 	} else {
1.784     albertel 1069: 	    $load = $loadans;
1.411     albertel 1070: 	}
1.784     albertel 1071:     } else {
                   1072: 	$load = $userloadans;
                   1073:     }
                   1074: 
                   1075:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1076: 	$spare_server = $try_server;
                   1077: 	$lowest_load  = $load;
1.370     albertel 1078:     }
1.784     albertel 1079:     return ($spare_server,$lowest_load);
1.202     matthew  1080: }
1.914     albertel 1081: 
                   1082: # --------------------------- ask offload servers if user already has a session
                   1083: sub find_existing_session {
                   1084:     my ($udom,$uname) = @_;
1.1123    raeburn  1085:     my $spareshash = &this_host_spares($udom);
                   1086:     if (ref($spareshash) eq 'HASH') {
                   1087:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1088:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1089:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1090:             }
                   1091:         }
                   1092:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1093:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1094:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1095:             }
                   1096:         }
1.914     albertel 1097:     }
                   1098:     return;
                   1099: }
                   1100: 
1.1172.2.146.  .13(raeb 1101:-23): sub delusersession {
                   1102:-23):     my ($lonid,$udom,$uname) = @_;
                   1103:-23):     my $uprimary_id = &domain($udom,'primary');
                   1104:-23):     my $uintdom = &internet_dom($uprimary_id);
                   1105:-23):     my $intdom = &internet_dom($lonid);
                   1106:-23):     my $serverhomedom = &host_domain($lonid);
                   1107:-23):     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1108:-23):         return &reply(join(':','delusersession',
                   1109:-23):                             map {&escape($_)} ($udom,$uname)),$lonid);
                   1110:-23):     }
                   1111:-23):     return;
                   1112:-23): }
                   1113:-23): 
                   1114:-23): 
1.1172.2.107  raeburn  1115: # check if user's browser sent load balancer cookie and server still has session
                   1116: # and is not overloaded.
                   1117: sub check_for_balancer_cookie {
                   1118:     my ($r,$update_mtime) = @_;
                   1119:     my ($otherserver,$cookie);
                   1120:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1121:     if (exists($cookies{'balanceID'})) {
                   1122:         my $balid = $cookies{'balanceID'};
                   1123:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1124:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1125:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1126:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1127:                 my ($possudom,$possuname) = ($1,$2);
                   1128:                 my $has_session = 0;
                   1129:                 if ((&domain($possudom) ne '') &&
                   1130:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1131:                     my $try_server;
                   1132:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1133:                     if ($opened) {
                   1134:                         flock($idf,LOCK_SH);
                   1135:                         while (my $line = <$idf>) {
                   1136:                             chomp($line);
                   1137:                             if (&hostname($line) ne '') {
                   1138:                                 $try_server = $line;
                   1139:                                 last;
                   1140:                             }
                   1141:                         }
                   1142:                         close($idf);
                   1143:                         if (($try_server) &&
                   1144:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1145:                             my $lowest_load = 30000;
                   1146:                             ($otherserver,$lowest_load) =
                   1147:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1148:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1149:                                 $has_session = 1;
                   1150:                             } else {
                   1151:                                 undef($otherserver);
                   1152:                             }
                   1153:                         }
                   1154:                     }
                   1155:                 }
                   1156:                 if ($has_session) {
                   1157:                     if ($update_mtime) {
                   1158:                         my $atime = my $mtime = time;
                   1159:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1160:                     }
                   1161:                 } else {
                   1162:                     unlink("$balancedir/$cookie.id");
                   1163:                 }
                   1164:             }
                   1165:         }
                   1166:     }
                   1167:     return ($otherserver,$cookie);
                   1168: }
                   1169: 
1.1172.2.130  raeburn  1170: sub updatebalcookie {
                   1171:     my ($cookie,$balancer,$lastentry)=@_;
                   1172:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1173:         my ($udom,$uname) = ($1,$2);
                   1174:         my $uprimary_id = &domain($udom,'primary');
                   1175:         my $uintdom = &internet_dom($uprimary_id);
                   1176:         my $intdom = &internet_dom($balancer);
                   1177:         my $serverhomedom = &host_domain($balancer);
                   1178:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1179:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
                   1180:         }
                   1181:     }
                   1182:     return;
                   1183: }
                   1184: 
1.1172.2.107  raeburn  1185: sub delbalcookie {
                   1186:     my ($cookie,$balancer) =@_;
                   1187:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1188:         my ($udom,$uname) = ($1,$2);
                   1189:         my $uprimary_id = &domain($udom,'primary');
                   1190:         my $uintdom = &internet_dom($uprimary_id);
                   1191:         my $intdom = &internet_dom($balancer);
                   1192:         my $serverhomedom = &host_domain($balancer);
                   1193:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1172.2.130  raeburn  1194:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1172.2.107  raeburn  1195:         }
                   1196:     }
                   1197: }
                   1198: 
1.914     albertel 1199: # -------------------------------- ask if server already has a session for user
                   1200: sub has_user_session {
                   1201:     my ($lonid,$udom,$uname) = @_;
                   1202:     my $result = &reply(join(':','userhassession',
                   1203: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1204:     return 1 if ($result eq 'ok');
                   1205: 
                   1206:     return 0;
                   1207: }
                   1208: 
1.1076    raeburn  1209: # --------- determine least loaded server in a user's domain which allows login
                   1210: 
                   1211: sub choose_server {
1.1172.2.47  raeburn  1212:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1213:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1214:     my %servers = &get_servers($udom);
1.1076    raeburn  1215:     my $lowest_load = 30000;
1.1172.2.47  raeburn  1216:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1217:     if ($skiploadbal) {
                   1218:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1219:         unless (defined($cached)) {
                   1220:             my $cachetime = 60*60*24;
                   1221:             my %domconfig =
                   1222:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1223:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1224:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1225:                                            $cachetime);
                   1226:             }
                   1227:         }
                   1228:     }
1.1076    raeburn  1229:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn  1230:         my $loginvia;
1.1172.2.47  raeburn  1231:         if ($skiploadbal) {
                   1232:             if (ref($balancers) eq 'HASH') {
                   1233:                 next if (exists($balancers->{$lonhost}));
                   1234:             }
                   1235:         }
1.1115    raeburn  1236:         if ($checkloginvia) {
                   1237:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1238:             if ($loginvia) {
                   1239:                 my ($server,$path) = split(/:/,$loginvia);
                   1240:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1241:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1242:                 if ($login_host eq $server) {
                   1243:                     $portal_path = $path;
1.1151    raeburn  1244:                     $isredirect = 1;
1.1116    raeburn  1245:                 }
                   1246:             } else {
                   1247:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1248:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1249:                 if ($login_host eq $lonhost) {
                   1250:                     $portal_path = '';
1.1151    raeburn  1251:                     $isredirect = ''; 
1.1116    raeburn  1252:                 }
                   1253:             }
                   1254:         } else {
1.1076    raeburn  1255:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1256:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1257:         }
                   1258:     }
                   1259:     if ($login_host ne '') {
1.1116    raeburn  1260:         $hostname = &hostname($login_host);
1.1076    raeburn  1261:     }
1.1172.2.88  raeburn  1262:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1263: }
                   1264: 
1.1172.2.123  raeburn  1265: sub get_course_sessions {
                   1266:     my ($cnum,$cdom,$lastactivity) = @_;
                   1267:     my %servers = &internet_dom_servers($cdom);
                   1268:     my %returnhash;
                   1269:     foreach my $server (sort(keys(%servers))) {
                   1270:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1271:         my @pairs=split(/\&/,$rep);
                   1272:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1273:             foreach my $item (@pairs) {
                   1274:                 my ($key,$value)=split(/=/,$item,2);
                   1275:                 $key = &unescape($key);
                   1276:                 next if ($key =~ /^error: 2 /);
                   1277:                 if (exists($returnhash{$key})) {
                   1278:                     next if ($value < $returnhash{$key});
                   1279:                 }
                   1280:                 $returnhash{$key}=$value;
                   1281:             }
                   1282:         }
                   1283:     }
                   1284:     return %returnhash;
                   1285: }
                   1286: 
1.202     matthew  1287: # --------------------------------------------- Try to change a user's password
                   1288: 
                   1289: sub changepass {
1.799     raeburn  1290:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1291:     $currentpass = &escape($currentpass);
                   1292:     $newpass     = &escape($newpass);
1.1030    raeburn  1293:     my $lonhost = $perlvar{'lonHostID'};
                   1294:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1295: 		       $server);
                   1296:     if (! $answer) {
                   1297: 	&logthis("No reply on password change request to $server ".
                   1298: 		 "by $uname in domain $udom.");
                   1299:     } elsif ($answer =~ "^ok") {
                   1300:         &logthis("$uname in $udom successfully changed their password ".
                   1301: 		 "on $server.");
                   1302:     } elsif ($answer =~ "^pwchange_failure") {
                   1303: 	&logthis("$uname in $udom was unable to change their password ".
                   1304: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1305: 		 "or pwchange");
                   1306:     } elsif ($answer =~ "^non_authorized") {
                   1307:         &logthis("$uname in $udom did not get their password correct when ".
                   1308: 		 "attempting to change it on $server.");
                   1309:     } elsif ($answer =~ "^auth_mode_error") {
                   1310:         &logthis("$uname in $udom attempted to change their password despite ".
                   1311: 		 "not being locally or internally authenticated on $server.");
                   1312:     } elsif ($answer =~ "^unknown_user") {
                   1313:         &logthis("$uname in $udom attempted to change their password ".
                   1314: 		 "on $server but were unable to because $server is not ".
                   1315: 		 "their home server.");
                   1316:     } elsif ($answer =~ "^refused") {
                   1317: 	&logthis("$server refused to change $uname in $udom password because ".
                   1318: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1319:     } elsif ($answer =~ "invalid_client") {
                   1320:         &logthis("$server refused to change $uname in $udom password because ".
                   1321:                  "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113  raeburn  1322:     } elsif ($answer =~ "^prioruse") {
                   1323:        &logthis("$server refused to change $uname in $udom password because ".
                   1324:                 "the password had been used before");
1.202     matthew  1325:     }
                   1326:     return $answer;
1.1       albertel 1327: }
                   1328: 
1.169     harris41 1329: # ----------------------- Try to determine user's current authentication scheme
                   1330: 
                   1331: sub queryauthenticate {
                   1332:     my ($uname,$udom)=@_;
1.456     albertel 1333:     my $uhome=&homeserver($uname,$udom);
1.1172.2.146.  .5(raebu 1334:22):     if ((!$uhome) || ($uhome eq 'no_host')) {
1.456     albertel 1335: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1336: 	return 'no_host';
                   1337:     }
                   1338:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1339:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1340: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1341:     }
1.456     albertel 1342:     return $answer;
1.169     harris41 1343: }
                   1344: 
1.1       albertel 1345: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1346: 
1.1       albertel 1347: sub authenticate {
1.1073    raeburn  1348:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1349:     $upass=&escape($upass);
                   1350:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1351:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1352:     my $newhome;
1.836     www      1353:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1354: # Maybe the machine was offline and only re-appeared again recently?
                   1355:         &reconlonc();
                   1356: # One more
1.952     raeburn  1357: 	$uhome=&homeserver($uname,$udom,1);
                   1358:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1359:             if (defined(&domain($udom,'primary'))) {
                   1360:                 $newhome=&domain($udom,'primary');
                   1361:             }
                   1362:             if ($newhome ne '') {
                   1363:                 $uhome = $newhome;
                   1364:             }
                   1365:         }
1.836     www      1366: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1367: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1368: 	    return 'no_host';
                   1369:         }
1.1       albertel 1370:     }
1.1073    raeburn  1371:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1372:     if ($answer eq 'authorized') {
1.952     raeburn  1373:         if ($newhome) {
                   1374:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1375:             return 'no_account_on_host'; 
                   1376:         } else {
                   1377:             &logthis("User $uname at $udom authorized by $uhome");
                   1378:             return $uhome;
                   1379:         }
1.471     albertel 1380:     }
                   1381:     if ($answer eq 'non_authorized') {
                   1382: 	&logthis("User $uname at $udom rejected by $uhome");
1.1172.2.146.  .5(raebu 1383:22): 	return 'no_host';
1.9       www      1384:     }
1.471     albertel 1385:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1386:     return 'no_host';
                   1387: }
                   1388: 
1.1172.2.146.  .6(raebu 1389:22): sub can_switchserver {
                   1390:22):     my ($udom,$home) = @_;
                   1391:22):     my ($canswitch,@intdoms);
                   1392:22):     my $internet_names = &get_internet_names($home);
                   1393:22):     if (ref($internet_names) eq 'ARRAY') {
                   1394:22):         @intdoms = @{$internet_names};
                   1395:22):     }
                   1396:22):     my $uint_dom = &internet_dom(&domain($udom,'primary'));
                   1397:22):     if ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1398:22):         $canswitch = 1;
                   1399:22):     } else {
                   1400:22):          my $serverhomeID = &get_server_homeID(&hostname($home));
                   1401:22):          my $serverhomedom = &host_domain($serverhomeID);
                   1402:22):          my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1403:22):          my %udomdefaults = &get_domain_defaults($udom);
                   1404:22):          my $remoterev = &get_server_loncaparev('',$home);
                   1405:22):          $canswitch = &can_host_session($udom,$home,$remoterev,
                   1406:22):                                         $udomdefaults{'remotesessions'},
                   1407:22):                                         $defdomdefaults{'hostedsessions'});
                   1408:22):     }
                   1409:22):     return $canswitch;
                   1410:22): }
                   1411:22): 
1.1073    raeburn  1412: sub can_host_session {
1.1074    raeburn  1413:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1414:     my $canhost = 1;
1.1074    raeburn  1415:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1416:     if (ref($remotesessions) eq 'HASH') {
                   1417:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1418:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1419:                 $canhost = 0;
                   1420:             } else {
                   1421:                 $canhost = 1;
                   1422:             }
                   1423:         }
                   1424:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1425:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1426:                 $canhost = 1;
                   1427:             } else {
                   1428:                 $canhost = 0;
                   1429:             }
                   1430:         }
                   1431:         if ($canhost) {
                   1432:             if ($remotesessions->{'version'} ne '') {
                   1433:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1434:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1435:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1436:                         my $major = $1;
                   1437:                         my $minor = $2;
                   1438:                         if (($major < $reqmajor ) ||
                   1439:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1440:                             $canhost = 0;
                   1441:                         }
                   1442:                     } else {
                   1443:                         $canhost = 0;
                   1444:                     }
                   1445:                 }
                   1446:             }
                   1447:         }
                   1448:     }
                   1449:     if ($canhost) {
                   1450:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1451:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1452:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1453:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1454:                 if (($uint_dom ne '') && 
                   1455:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1456:                     $canhost = 0;
                   1457:                 } else {
                   1458:                     $canhost = 1;
                   1459:                 }
                   1460:             }
                   1461:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1462:                 if (($uint_dom ne '') && 
                   1463:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1464:                     $canhost = 1;
                   1465:                 } else {
                   1466:                     $canhost = 0;
                   1467:                 }
                   1468:             }
                   1469:         }
                   1470:     }
                   1471:     return $canhost;
                   1472: }
                   1473: 
1.1083    raeburn  1474: sub spare_can_host {
                   1475:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1476:     my $canhost=1;
1.1172.2.62  raeburn  1477:     my $try_server_hostname = &hostname($try_server);
                   1478:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1479:     my $serverhomedom = &host_domain($serverhomeID);
                   1480:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1481:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1482:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1483:             $canhost = 0;
                   1484:         }
                   1485:     }
1.1172.2.136  raeburn  1486:     if ($canhost) {
                   1487:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
                   1488:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
                   1489:                 unless (&shared_institution($udom,$try_server)) {
                   1490:                     $canhost = 0;
                   1491:                 }
                   1492:             }
                   1493:         }
                   1494:     }
1.1172.2.62  raeburn  1495:     if (($canhost) && ($uint_dom)) {
                   1496:         my @intdoms;
                   1497:         my $internet_names = &get_internet_names($try_server);
                   1498:         if (ref($internet_names) eq 'ARRAY') {
                   1499:             @intdoms = @{$internet_names};
                   1500:         }
                   1501:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1502:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1503:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1504:                                          $remotesessions,
                   1505:                                          $defdomdefaults{'hostedsessions'});
                   1506:         }
1.1083    raeburn  1507:     }
                   1508:     return $canhost;
                   1509: }
                   1510: 
1.1123    raeburn  1511: sub this_host_spares {
                   1512:     my ($dom) = @_;
1.1126    raeburn  1513:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1514:     my @hosts = &current_machine_ids();
                   1515:     foreach my $lonhost (@hosts) {
                   1516:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1517:             $dom_in_use = $dom;
                   1518:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1519:             last;
                   1520:         }
                   1521:     }
1.1126    raeburn  1522:     if ($dom_in_use ne '') {
                   1523:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1524:     }
                   1525:     if (ref($result) ne 'HASH') {
                   1526:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1527:         $dom_in_use = &host_domain($lonhost_in_use);
                   1528:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1529:         if (ref($result) ne 'HASH') {
                   1530:             $result = \%spareid;
                   1531:         }
                   1532:     }
                   1533:     return $result;
                   1534: }
                   1535: 
                   1536: sub spares_for_offload  {
                   1537:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1538:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1539:     if (defined($cached)) {
                   1540:         return $result;
                   1541:     } else {
1.1126    raeburn  1542:         my $cachetime = 60*60*24;
                   1543:         my %domconfig =
                   1544:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1545:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1546:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1547:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1548:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1549:                 }
                   1550:             }
                   1551:         }
                   1552:     }
1.1126    raeburn  1553:     return;
1.1123    raeburn  1554: }
                   1555: 
1.1129    raeburn  1556: sub get_lonbalancer_config {
                   1557:     my ($servers) = @_;
                   1558:     my ($currbalancer,$currtargets);
                   1559:     if (ref($servers) eq 'HASH') {
                   1560:         foreach my $server (keys(%{$servers})) {
                   1561:             my %what = (
                   1562:                          spareid => 1,
                   1563:                          perlvar => 1,
                   1564:                        );
                   1565:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1566:             if ($result eq 'ok') {
                   1567:                 if (ref($returnhash) eq 'HASH') {
                   1568:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1569:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1570:                             $currbalancer = $server;
                   1571:                             $currtargets = {};
                   1572:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1573:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1574:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1575:                                 }
                   1576:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1577:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1578:                                 }
                   1579:                             }
                   1580:                             last;
                   1581:                         }
                   1582:                     }
                   1583:                 }
                   1584:             }
                   1585:         }
                   1586:     }
                   1587:     return ($currbalancer,$currtargets);
                   1588: }
                   1589: 
                   1590: sub check_loadbalancing {
1.1172.2.88  raeburn  1591:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1592:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1593:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1594:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1595:     my @hosts = &current_machine_ids();
1.1129    raeburn  1596:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1597:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1598:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1599:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1600:     my $domneedscache; 
1.1129    raeburn  1601:     my $cachetime = 60*60*24;
                   1602: 
                   1603:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1604:         $dom_in_use = $udom;
                   1605:         $homeintdom = 1;
                   1606:     } else {
                   1607:         $dom_in_use = $serverhomedom;
                   1608:     }
                   1609:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1610:     unless (defined($cached)) {
                   1611:         my %domconfig =
                   1612:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1613:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1614:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1615:         } else {
                   1616:             $domneedscache = $dom_in_use;
1.1129    raeburn  1617:         }
                   1618:     }
                   1619:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1620:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1621:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1622:         if ($is_balancer) {
                   1623:             if (ref($currrules) eq 'HASH') {
                   1624:                 if ($homeintdom) {
                   1625:                     if ($uname ne '') {
                   1626:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1627:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1628:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1629:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1630:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1631:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1632:                             }
                   1633:                         }
                   1634:                         if ($rule_in_effect eq '') {
                   1635:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1636:                             if ($userenv{'inststatus'} ne '') {
                   1637:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1638:                                 my ($othertitle,$usertypes,$types) =
                   1639:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1640:                                 if (ref($types) eq 'ARRAY') {
                   1641:                                     foreach my $type (@{$types}) {
                   1642:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1643:                                             if (exists($currrules->{$type})) {
                   1644:                                                 $rule_in_effect = $currrules->{$type};
                   1645:                                             }
                   1646:                                         }
                   1647:                                     }
                   1648:                                 }
                   1649:                             } else {
                   1650:                                 if (exists($currrules->{'default'})) {
                   1651:                                     $rule_in_effect = $currrules->{'default'};
                   1652:                                 }
                   1653:                             }
                   1654:                         }
                   1655:                     } else {
                   1656:                         if (exists($currrules->{'default'})) {
                   1657:                             $rule_in_effect = $currrules->{'default'};
                   1658:                         }
                   1659:                     }
                   1660:                 } else {
                   1661:                     if ($currrules->{'_LC_external'} ne '') {
                   1662:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1663:                     }
                   1664:                 }
                   1665:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1666:                                                        $uname,$udom);
                   1667:             }
                   1668:         }
                   1669:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1670:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1671:         unless (defined($cached)) {
                   1672:             my %domconfig =
                   1673:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1674:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1675:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1676:             } else {
                   1677:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1678:             }
                   1679:         }
                   1680:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1681:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1682:                 &check_balancer_result($result,@hosts);
                   1683:             if ($is_balancer) {
1.1129    raeburn  1684:                 if (ref($currrules) eq 'HASH') {
                   1685:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1686:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1687:                     }
                   1688:                 }
                   1689:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1690:                                                        $uname,$udom);
                   1691:             }
                   1692:         } else {
                   1693:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1694:                 $is_balancer = 1;
                   1695:                 $offloadto = &this_host_spares($dom_in_use);
                   1696:             }
1.1172.2.75  raeburn  1697:             unless (defined($cached)) {
                   1698:                 $domneedscache = $serverhomedom;
                   1699:             }
1.1129    raeburn  1700:         }
                   1701:     } else {
                   1702:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1703:             $is_balancer = 1;
                   1704:             $offloadto = &this_host_spares($dom_in_use);
                   1705:         }
1.1172.2.75  raeburn  1706:         unless (defined($cached)) {
                   1707:             $domneedscache = $serverhomedom;
                   1708:         }
                   1709:     }
                   1710:     if ($domneedscache) {
                   1711:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1712:     }
1.1172.2.130  raeburn  1713:     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1172.2.5  raeburn  1714:         my $lowest_load = 30000;
                   1715:         if (ref($offloadto) eq 'HASH') {
                   1716:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1717:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1718:                     ($otherserver,$lowest_load) =
                   1719:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1720:                 }
1.1129    raeburn  1721:             }
1.1172.2.5  raeburn  1722:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1723: 
1.1172.2.5  raeburn  1724:             if (!$found_server) {
                   1725:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1726:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1727:                         ($otherserver,$lowest_load) =
                   1728:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1729:                     }
                   1730:                 }
                   1731:             }
                   1732:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1733:             if (@{$offloadto} == 1) {
                   1734:                 $otherserver = $offloadto->[0];
                   1735:             } elsif (@{$offloadto} > 1) {
                   1736:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1737:                     ($otherserver,$lowest_load) =
                   1738:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1739:                 }
                   1740:             }
                   1741:         }
1.1172.2.88  raeburn  1742:         unless ($caller eq 'login') {
                   1743:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1744:                 $is_balancer = 0;
                   1745:                 if ($uname ne '' && $udom ne '') {
                   1746:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1747:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1748:                                  'user.loadbalcheck.time' => time});
                   1749:                     }
1.1172.2.5  raeburn  1750:                 }
1.1129    raeburn  1751:             }
                   1752:         }
1.1172.2.130  raeburn  1753:     }
                   1754:     if (($is_balancer) && (!$homeintdom)) {
                   1755:         undef($setcookie);
1.1129    raeburn  1756:     }
1.1172.2.107  raeburn  1757:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1758: }
                   1759: 
1.1172.2.12  raeburn  1760: sub check_balancer_result {
                   1761:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1762:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1763:     if (ref($result) eq 'HASH') {
                   1764:         if ($result->{'lonhost'} ne '') {
                   1765:             my $currbalancer = $result->{'lonhost'};
                   1766:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1767:                 $is_balancer = 1;
                   1768:                 $currtargets = $result->{'targets'};
                   1769:                 $currrules = $result->{'rules'};
                   1770:             }
                   1771:         } else {
                   1772:             foreach my $key (keys(%{$result})) {
                   1773:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1774:                     (ref($result->{$key}) eq 'HASH')) {
                   1775:                     $is_balancer = 1;
                   1776:                     $currrules = $result->{$key}{'rules'};
                   1777:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1778:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1779:                     last;
                   1780:                 }
                   1781:             }
                   1782:         }
                   1783:     }
1.1172.2.107  raeburn  1784:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1785: }
                   1786: 
1.1129    raeburn  1787: sub get_loadbalancer_targets {
                   1788:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1789:     my $offloadto;
1.1172.2.4  raeburn  1790:     if ($rule_in_effect eq 'none') {
                   1791:         return [$perlvar{'lonHostID'}];
                   1792:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1793:         $offloadto = $currtargets;
                   1794:     } else {
                   1795:         if ($rule_in_effect eq 'homeserver') {
                   1796:             my $homeserver = &homeserver($uname,$udom);
                   1797:             if ($homeserver ne 'no_host') {
                   1798:                 $offloadto = [$homeserver];
                   1799:             }
                   1800:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1801:             my %domconfig =
                   1802:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1803:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1804:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1805:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1806:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1807:                     }
                   1808:                 }
                   1809:             } else {
1.1172.2.7  raeburn  1810:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1811:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1812:                 if (&hostname($remotebalancer) ne '') {
                   1813:                     $offloadto = [$remotebalancer];
                   1814:                 }
                   1815:             }
                   1816:         } elsif (&hostname($rule_in_effect) ne '') {
                   1817:             $offloadto = [$rule_in_effect];
                   1818:         }
                   1819:     }
                   1820:     return $offloadto;
                   1821: }
                   1822: 
1.1127    raeburn  1823: sub internet_dom_servers {
                   1824:     my ($dom) = @_;
                   1825:     my (%uniqservers,%servers);
                   1826:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1827:     my @machinedoms = &machine_domains($primaryserver);
                   1828:     foreach my $mdom (@machinedoms) {
                   1829:         my %currservers = %servers;
                   1830:         my %server = &get_servers($mdom);
                   1831:         %servers = (%currservers,%server);
                   1832:     }
                   1833:     my %by_hostname;
                   1834:     foreach my $id (keys(%servers)) {
                   1835:         push(@{$by_hostname{$servers{$id}}},$id);
                   1836:     }
                   1837:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1838:         if (@{$by_hostname{$hostname}} > 1) {
                   1839:             my $match = 0;
                   1840:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1841:                 if (&host_domain($id) eq $dom) {
                   1842:                     $uniqservers{$id} = $hostname;
                   1843:                     $match = 1;
                   1844:                 }
                   1845:             }
                   1846:             unless ($match) {
                   1847:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1848:             }
                   1849:         } else {
                   1850:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1851:         }
                   1852:     }
                   1853:     return %uniqservers;
                   1854: }
                   1855: 
1.1       albertel 1856: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1857: 
1.599     albertel 1858: my %homecache;
1.1       albertel 1859: sub homeserver {
1.230     stredwic 1860:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1861:     my $index="$uname:$udom";
1.426     albertel 1862: 
1.599     albertel 1863:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1864: 
                   1865:     my %servers = &get_servers($udom,'library');
                   1866:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1867:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1868: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1869: 
                   1870: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1871: 	if ($answer eq 'found') {
                   1872: 	    delete($badServerCache{$tryserver}); 
                   1873: 	    return $homecache{$index}=$tryserver;
                   1874: 	} elsif ($answer eq 'no_host') {
                   1875: 	    $badServerCache{$tryserver}=1;
                   1876: 	}
1.1       albertel 1877:     }    
                   1878:     return 'no_host';
1.70      www      1879: }
                   1880: 
                   1881: # ------------------------------------- Find the usernames behind a list of IDs
                   1882: 
                   1883: sub idget {
                   1884:     my ($udom,@ids)=@_;
                   1885:     my %returnhash=();
                   1886:     
1.841     albertel 1887:     my %servers = &get_servers($udom,'library');
                   1888:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1889: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1890: 	$idlist=~tr/A-Z/a-z/; 
                   1891: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1892: 	my @answer=();
                   1893: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1894: 	    @answer=split(/\&/,$reply);
                   1895: 	}                    ;
                   1896: 	my $i;
                   1897: 	for ($i=0;$i<=$#ids;$i++) {
                   1898: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1899: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1900: 	    } 
                   1901: 	}
                   1902:     } 
1.70      www      1903:     return %returnhash;
                   1904: }
                   1905: 
                   1906: # ------------------------------------- Find the IDs behind a list of usernames
                   1907: 
                   1908: sub idrget {
                   1909:     my ($udom,@unames)=@_;
                   1910:     my %returnhash=();
1.800     albertel 1911:     foreach my $uname (@unames) {
                   1912:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1913:     }
1.70      www      1914:     return %returnhash;
                   1915: }
                   1916: 
                   1917: # ------------------------------- Store away a list of names and associated IDs
                   1918: 
                   1919: sub idput {
                   1920:     my ($udom,%ids)=@_;
                   1921:     my %servers=();
1.800     albertel 1922:     foreach my $uname (keys(%ids)) {
                   1923: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1924:         my $uhom=&homeserver($uname,$udom);
1.70      www      1925:         if ($uhom ne 'no_host') {
1.800     albertel 1926:             my $id=&escape($ids{$uname});
1.70      www      1927:             $id=~tr/A-Z/a-z/;
1.800     albertel 1928:             my $esc_unam=&escape($uname);
1.70      www      1929: 	    if ($servers{$uhom}) {
1.800     albertel 1930: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1931:             } else {
1.800     albertel 1932:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1933:             }
                   1934:         }
1.191     harris41 1935:     }
1.800     albertel 1936:     foreach my $server (keys(%servers)) {
                   1937:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1938:     }
1.344     www      1939: }
                   1940: 
1.1172.2.30  raeburn  1941: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1942: 
                   1943: sub iddel {
                   1944:     my ($udom,$idshashref,$uhome)=@_;
                   1945:     my %result=();
                   1946:     unless (ref($idshashref) eq 'HASH') {
                   1947:         return %result;
                   1948:     }
                   1949:     my %servers=();
                   1950:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1951:         my $uhom;
                   1952:         if ($uhome) {
                   1953:             $uhom = $uhome;
                   1954:         } else {
                   1955:             $uhom=&homeserver($uname,$udom);
                   1956:         }
                   1957:         if ($uhom ne 'no_host') {
                   1958:             if ($servers{$uhom}) {
                   1959:                 $servers{$uhom}.='&'.&escape($id);
                   1960:             } else {
                   1961:                 $servers{$uhom}=&escape($id);
                   1962:             }
                   1963:         }
                   1964:     }
                   1965:     foreach my $server (keys(%servers)) {
                   1966:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1967:     }
                   1968:     return %result;
                   1969: }
                   1970: 
1.1023    raeburn  1971: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1972: sub dump_dom {
1.1165    droeschl 1973:     my ($namespace, $udom, $regexp) = @_;
                   1974: 
                   1975:     $udom ||= $env{'user.domain'};
                   1976: 
                   1977:     return () unless $udom;
                   1978: 
                   1979:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1980: }
                   1981: 
1.1023    raeburn  1982: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1983: 
                   1984: sub get_dom {
1.1172.2.146.  .1(raebu 1985:22):     my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
1.1172.2.57  raeburn  1986:     return if ($udom eq 'public');
1.806     raeburn  1987:     my $items='';
                   1988:     foreach my $item (@$storearr) {
                   1989:         $items.=&escape($item).'&';
                   1990:     }
                   1991:     $items=~s/\&$//;
1.860     raeburn  1992:     if (!$udom) {
                   1993:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1994:         return if ($udom eq 'public');
1.860     raeburn  1995:         if (defined(&domain($udom,'primary'))) {
                   1996:             $uhome=&domain($udom,'primary');
                   1997:         } else {
1.874     albertel 1998:             undef($uhome);
1.860     raeburn  1999:         }
                   2000:     } else {
                   2001:         if (!$uhome) {
                   2002:             if (defined(&domain($udom,'primary'))) {
                   2003:                 $uhome=&domain($udom,'primary');
                   2004:             }
                   2005:         }
                   2006:     }
                   2007:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.139  raeburn  2008:         my $rep;
                   2009:         if (grep { $_ eq $uhome } &current_machine_ids()) {
                   2010:             # domain information is hosted on this machine
                   2011:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1.1172.2.146.  .1(raebu 2012:22):         } else {
                   2013:22):             if ($encrypt) {
                   2014:22):                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2015:22):             } else {
                   2016:22):                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2017:22):             }
1.1172.2.139  raeburn  2018:         }
1.866     raeburn  2019:         my %returnhash;
1.875     albertel 2020:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2021:             return %returnhash;
                   2022:         }
1.806     raeburn  2023:         my @pairs=split(/\&/,$rep);
                   2024:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2025:             return @pairs;
                   2026:         }
                   2027:         my $i=0;
                   2028:         foreach my $item (@$storearr) {
                   2029:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2030:             $i++;
                   2031:         }
                   2032:         return %returnhash;
                   2033:     } else {
1.880     banghart 2034:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2035:     }
                   2036: }
                   2037: 
                   2038: # -------------------------------------------- put items in domain db files 
                   2039: 
                   2040: sub put_dom {
1.1172.2.146.  .1(raebu 2041:22):     my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
1.860     raeburn  2042:     if (!$udom) {
                   2043:         $udom=$env{'user.domain'};
                   2044:         if (defined(&domain($udom,'primary'))) {
                   2045:             $uhome=&domain($udom,'primary');
                   2046:         } else {
1.874     albertel 2047:             undef($uhome);
1.860     raeburn  2048:         }
                   2049:     } else {
                   2050:         if (!$uhome) {
                   2051:             if (defined(&domain($udom,'primary'))) {
                   2052:                 $uhome=&domain($udom,'primary');
                   2053:             }
                   2054:         }
                   2055:     } 
                   2056:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2057:         my $items='';
                   2058:         foreach my $item (keys(%$storehash)) {
                   2059:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2060:         }
                   2061:         $items=~s/\&$//;
1.1172.2.146.  .1(raebu 2062:22):         if ($encrypt) {
                   2063:22):             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2064:22):         } else {
                   2065:22):             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2066:22):         }
1.806     raeburn  2067:     } else {
1.860     raeburn  2068:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2069:     }
                   2070: }
                   2071: 
1.1023    raeburn  2072: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2073: sub newput_dom {
1.1023    raeburn  2074:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2075:     my $result;
                   2076:     if (!$udom) {
                   2077:         $udom=$env{'user.domain'};
                   2078:     }
1.1023    raeburn  2079:     if ($udom) {
                   2080:         my $uname = &get_domainconfiguser($udom);
                   2081:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2082:     }
                   2083:     return $result;
                   2084: }
                   2085: 
1.1023    raeburn  2086: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2087: sub del_dom {
1.1023    raeburn  2088:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2089:     if (ref($storearr) eq 'ARRAY') {
                   2090:         if (!$udom) {
                   2091:             $udom=$env{'user.domain'};
                   2092:         }
1.1023    raeburn  2093:         if ($udom) {
                   2094:             my $uname = &get_domainconfiguser($udom); 
                   2095:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2096:         }
                   2097:     }
                   2098: }
                   2099: 
1.1172.2.146.  .4(raebu 2100:22): sub store_dom {
                   2101:22):     my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
                   2102:22):     $$storehash{'ip'}=&get_requestor_ip();
                   2103:22):     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2104:22):     my $namevalue='';
                   2105:22):     foreach my $key (keys(%{$storehash})) {
                   2106:22):         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   2107:22):     }
                   2108:22):     $namevalue=~s/\&$//;
                   2109:22):     if (grep { $_ eq $home } current_machine_ids()) {
                   2110:22):         return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
                   2111:22):     } else {
                   2112:22):         if ($namespace eq 'private') {
                   2113:22):             return 'refused';
                   2114:22):         } elsif ($encrypt) {
                   2115:22):             return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
                   2116:22):         } else {
                   2117:22):             return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
                   2118:22):         }
                   2119:22):     }
                   2120:22): }
                   2121:22): 
                   2122:22): sub restore_dom {
                   2123:22):     my ($id,$namespace,$dom,$home,$encrypt) = @_;
                   2124:22):     my $answer;
                   2125:22):     if (grep { $_ eq $home } current_machine_ids()) {
                   2126:22):         $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
                   2127:22):     } elsif ($namespace ne 'private') {
                   2128:22):         if ($encrypt) {
                   2129:22):             $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
                   2130:22):         } else {
                   2131:22):             $answer=&reply("restoredom:$dom:$namespace:$id",$home);
                   2132:22):         }
                   2133:22):     }
                   2134:22):     my %returnhash=();
                   2135:22):     unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') ||
                   2136:22):             ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
                   2137:22):         foreach my $line (split(/\&/,$answer)) {
                   2138:22):             my ($name,$value)=split(/\=/,$line);
                   2139:22):             $returnhash{&unescape($name)}=&thaw_unescape($value);
                   2140:22):         }
                   2141:22):         my $version;
                   2142:22):         for ($version=1;$version<=$returnhash{'version'};$version++) {
                   2143:22):             foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2144:22):                 $returnhash{$item}=$returnhash{$version.':'.$item};
                   2145:22):             }
                   2146:22):         }
                   2147:22):     }
                   2148:22):     return %returnhash;
                   2149:22): }
                   2150:22): 
1.1023    raeburn  2151: # ----------------------------------construct domainconfig user for a domain 
                   2152: sub get_domainconfiguser {
                   2153:     my ($udom) = @_;
                   2154:     return $udom.'-domainconfig';
                   2155: }
                   2156: 
1.837     raeburn  2157: sub retrieve_inst_usertypes {
                   2158:     my ($udom) = @_;
                   2159:     my (%returnhash,@order);
1.989     raeburn  2160:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2161:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2162:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  2163:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2164:     } else {
                   2165:         if (defined(&domain($udom,'primary'))) {
                   2166:             my $uhome=&domain($udom,'primary');
                   2167:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2168:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  2169:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2170:                 return (\%returnhash,\@order);
                   2171:             }
                   2172:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2173:             my @pairs=split(/\&/,$hashitems);
                   2174:             foreach my $item (@pairs) {
                   2175:                 my ($key,$value)=split(/=/,$item,2);
                   2176:                 $key = &unescape($key);
                   2177:                 next if ($key =~ /^error: 2 /);
                   2178:                 $returnhash{$key}=&thaw_unescape($value);
                   2179:             }
                   2180:             my @esc_order = split(/\&/,$orderitems);
                   2181:             foreach my $item (@esc_order) {
                   2182:                 push(@order,&unescape($item));
                   2183:             }
                   2184:         } else {
1.1172.2.44  raeburn  2185:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2186:         }
1.1172.2.44  raeburn  2187:         return (\%returnhash,\@order);
1.837     raeburn  2188:     }
                   2189: }
                   2190: 
1.868     raeburn  2191: sub is_domainimage {
                   2192:     my ($url) = @_;
1.1172.2.142  raeburn  2193:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868     raeburn  2194:         if (&domain($1) ne '') {
                   2195:             return '1';
                   2196:         }
                   2197:     }
                   2198:     return;
                   2199: }
                   2200: 
1.899     raeburn  2201: sub inst_directory_query {
                   2202:     my ($srch) = @_;
                   2203:     my $udom = $srch->{'srchdomain'};
                   2204:     my %results;
                   2205:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2206:     my $outcome;
1.899     raeburn  2207:     if ($homeserver ne '') {
1.1172.2.116  raeburn  2208:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2209:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2210:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  2211:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   2212:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2213:                     (($major == 2) && ($minor < 11)) ||
                   2214:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   2215:                     return;
                   2216:                 }
                   2217:             }
                   2218:         }
1.904     albertel 2219: 	my $queryid=&reply("querysend:instdirsearch:".
                   2220: 			   &escape($srch->{'srchby'}).':'.
                   2221: 			   &escape($srch->{'srchterm'}).':'.
                   2222: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2223: 	my $host=&hostname($homeserver);
                   2224: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2225: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2226: 	    return;
                   2227: 	}
                   2228: 	my $response = &get_query_reply($queryid);
                   2229: 	my $maxtries = 5;
                   2230: 	my $tries = 1;
                   2231: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2232: 	    $response = &get_query_reply($queryid);
                   2233: 	    $tries ++;
                   2234: 	}
                   2235: 
                   2236:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2237:             if ($response eq 'unavailable') {
                   2238:                 $outcome = $response;
                   2239:             } else {
                   2240:                 $outcome = 'ok';
                   2241:                 my @matches = split(/\n/,$response);
                   2242:                 foreach my $match (@matches) {
                   2243:                     my ($key,$value) = split(/=/,$match);
                   2244:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2245:                 }
1.899     raeburn  2246:             }
                   2247:         }
                   2248:     }
1.909     raeburn  2249:     return ($outcome,%results);
1.899     raeburn  2250: }
                   2251: 
                   2252: sub usersearch {
                   2253:     my ($srch) = @_;
                   2254:     my $dom = $srch->{'srchdomain'};
                   2255:     my %results;
                   2256:     my %libserv = &all_library();
                   2257:     my $query = 'usersearch';
                   2258:     foreach my $tryserver (keys(%libserv)) {
                   2259:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2260:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2261:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2262:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.119  raeburn  2263:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2264:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2265:                              (($major == 2) && ($minor < 11)) ||
                   2266:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2267:                 }
                   2268:             }
1.899     raeburn  2269:             my $host=&hostname($tryserver);
                   2270:             my $queryid=
1.911     raeburn  2271:                 &reply("querysend:".&escape($query).':'.
                   2272:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2273:                        &escape($srch->{'srchtype'}).':'.
                   2274:                        &escape($srch->{'srchterm'}),$tryserver);
                   2275:             if ($queryid !~/^\Q$host\E\_/) {
                   2276:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2277:                 next;
1.899     raeburn  2278:             }
                   2279:             my $reply = &get_query_reply($queryid);
                   2280:             my $maxtries = 1;
                   2281:             my $tries = 1;
                   2282:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2283:                 $reply = &get_query_reply($queryid);
                   2284:                 $tries ++;
                   2285:             }
                   2286:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2287:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2288:             } else {
1.911     raeburn  2289:                 my @matches;
                   2290:                 if ($reply =~ /\n/) {
                   2291:                     @matches = split(/\n/,$reply);
                   2292:                 } else {
                   2293:                     @matches = split(/\&/,$reply);
                   2294:                 }
1.899     raeburn  2295:                 foreach my $match (@matches) {
                   2296:                     my ($uname,$udom,%userhash);
1.911     raeburn  2297:                     foreach my $entry (split(/:/,$match)) {
                   2298:                         my ($key,$value) =
                   2299:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2300:                         $userhash{$key} = $value;
                   2301:                         if ($key eq 'username') {
                   2302:                             $uname = $value;
                   2303:                         } elsif ($key eq 'domain') {
                   2304:                             $udom = $value;
1.911     raeburn  2305:                         }
1.899     raeburn  2306:                     }
                   2307:                     $results{$uname.':'.$udom} = \%userhash;
                   2308:                 }
                   2309:             }
                   2310:         }
                   2311:     }
                   2312:     return %results;
                   2313: }
                   2314: 
1.912     raeburn  2315: sub get_instuser {
                   2316:     my ($udom,$uname,$id) = @_;
                   2317:     my $homeserver = &domain($udom,'primary');
                   2318:     my ($outcome,%results);
                   2319:     if ($homeserver ne '') {
                   2320:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2321:                            &escape($id).':'.&escape($udom),$homeserver);
                   2322:         my $host=&hostname($homeserver);
                   2323:         if ($queryid !~/^\Q$host\E\_/) {
                   2324:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2325:             return;
                   2326:         }
                   2327:         my $response = &get_query_reply($queryid);
                   2328:         my $maxtries = 5;
                   2329:         my $tries = 1;
                   2330:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2331:             $response = &get_query_reply($queryid);
                   2332:             $tries ++;
                   2333:         }
                   2334:         if (!&error($response) && $response ne 'refused') {
                   2335:             if ($response eq 'unavailable') {
                   2336:                 $outcome = $response;
                   2337:             } else {
                   2338:                 $outcome = 'ok';
                   2339:                 my @matches = split(/\n/,$response);
                   2340:                 foreach my $match (@matches) {
                   2341:                     my ($key,$value) = split(/=/,$match);
                   2342:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2343:                 }
                   2344:             }
                   2345:         }
                   2346:     }
                   2347:     my %userinfo;
                   2348:     if (ref($results{$uname}) eq 'HASH') {
                   2349:         %userinfo = %{$results{$uname}};
                   2350:     } 
                   2351:     return ($outcome,%userinfo);
                   2352: }
                   2353: 
1.1172.2.69  raeburn  2354: sub get_multiple_instusers {
                   2355:     my ($udom,$users,$caller) = @_;
                   2356:     my ($outcome,$results);
                   2357:     if (ref($users) eq 'HASH') {
                   2358:         my $count = keys(%{$users});
                   2359:         my $requested = &freeze_escape($users);
                   2360:         my $homeserver = &domain($udom,'primary');
                   2361:         if ($homeserver ne '') {
                   2362:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2363:             my $host=&hostname($homeserver);
                   2364:             if ($queryid !~/^\Q$host\E\_/) {
                   2365:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2366:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2367:                 return ($outcome,$results);
                   2368:             }
                   2369:             my $response = &get_query_reply($queryid);
                   2370:             my $maxtries = 5;
                   2371:             if ($count > 100) {
                   2372:                 $maxtries = 1+int($count/20);
                   2373:             }
                   2374:             my $tries = 1;
                   2375:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2376:                 $response = &get_query_reply($queryid);
                   2377:                 $tries ++;
                   2378:             }
                   2379:             if ($response eq '') {
                   2380:                 $results = {};
                   2381:                 foreach my $key (keys(%{$users})) {
                   2382:                     my ($uname,$id);
                   2383:                     if ($caller eq 'id') {
                   2384:                         $id = $key;
                   2385:                     } else {
                   2386:                         $uname = $key;
                   2387:                     }
                   2388:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2389:                     $outcome = $resp;
                   2390:                     if ($resp eq 'ok') {
                   2391:                         %{$results} = (%{$results}, %info);
                   2392:                     } else {
                   2393:                         last;
                   2394:                     }
                   2395:                 }
                   2396:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2397:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2398:                     $outcome = $response;
                   2399:                 } else {
                   2400:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2401:                     if ($outcome eq 'ok') {
                   2402:                         $results = &thaw_unescape($userdata);
                   2403:                     }
                   2404:                 }
                   2405:             }
                   2406:         }
                   2407:     }
                   2408:     return ($outcome,$results);
                   2409: }
                   2410: 
1.912     raeburn  2411: sub inst_rulecheck {
1.923     raeburn  2412:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2413:     my %returnhash;
                   2414:     if ($udom ne '') {
                   2415:         if (ref($rules) eq 'ARRAY') {
                   2416:             @{$rules} = map {&escape($_);} (@{$rules});
                   2417:             my $rulestr = join(':',@{$rules});
                   2418:             my $homeserver=&domain($udom,'primary');
                   2419:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2420:                 my $response;
                   2421:                 if ($item eq 'username') {                
                   2422:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2423:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2424:                                               $homeserver));
1.923     raeburn  2425:                 } elsif ($item eq 'id') {
                   2426:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2427:                                               ':'.&escape($id).':'.$rulestr,
                   2428:                                               $homeserver));
1.1172.2.146.  .5(raebu 2429:22):                 } elsif ($item eq 'unamemap') {
                   2430:22):                     $response=&unescape(&reply('instunamemapcheck:'.
                   2431:22):                                                &escape($udom).':'.&escape($uname).
                   2432:22):                                               ':'.$rulestr,$homeserver));
1.945     raeburn  2433:                 } elsif ($item eq 'selfcreate') {
                   2434:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2435:                                                &escape($udom).':'.&escape($uname).
                   2436:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2437:                 }
1.912     raeburn  2438:                 if ($response ne 'refused') {
                   2439:                     my @pairs=split(/\&/,$response);
                   2440:                     foreach my $item (@pairs) {
                   2441:                         my ($key,$value)=split(/=/,$item,2);
                   2442:                         $key = &unescape($key);
                   2443:                         next if ($key =~ /^error: 2 /);
                   2444:                         $returnhash{$key}=&thaw_unescape($value);
                   2445:                     }
                   2446:                 }
                   2447:             }
                   2448:         }
                   2449:     }
                   2450:     return %returnhash;
                   2451: }
                   2452: 
                   2453: sub inst_userrules {
1.923     raeburn  2454:     my ($udom,$check) = @_;
1.912     raeburn  2455:     my (%ruleshash,@ruleorder);
                   2456:     if ($udom ne '') {
                   2457:         my $homeserver=&domain($udom,'primary');
                   2458:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2459:             my $response;
                   2460:             if ($check eq 'id') {
                   2461:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2462:                                  $homeserver);
1.943     raeburn  2463:             } elsif ($check eq 'email') {
                   2464:                 $response=&reply('instemailrules:'.&escape($udom),
                   2465:                                  $homeserver);
1.1172.2.146.  .5(raebu 2466:22):             } elsif ($check eq 'unamemap') {
                   2467:22):                 $response=&reply('unamemaprules:'.&escape($udom),
                   2468:22):                                  $homeserver);
1.923     raeburn  2469:             } else {
                   2470:                 $response=&reply('instuserrules:'.&escape($udom),
                   2471:                                  $homeserver);
                   2472:             }
1.912     raeburn  2473:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2474:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2475:                 ($response ne 'no_such_host')) {
                   2476:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2477:                 my @pairs=split(/\&/,$hashitems);
                   2478:                 foreach my $item (@pairs) {
                   2479:                     my ($key,$value)=split(/=/,$item,2);
                   2480:                     $key = &unescape($key);
                   2481:                     next if ($key =~ /^error: 2 /);
                   2482:                     $ruleshash{$key}=&thaw_unescape($value);
                   2483:                 }
                   2484:                 my @esc_order = split(/\&/,$orderitems);
                   2485:                 foreach my $item (@esc_order) {
                   2486:                     push(@ruleorder,&unescape($item));
                   2487:                 }
                   2488:             }
                   2489:         }
                   2490:     }
                   2491:     return (\%ruleshash,\@ruleorder);
                   2492: }
                   2493: 
1.976     raeburn  2494: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2495: 
                   2496: sub get_domain_defaults {
1.1172.2.35  raeburn  2497:     my ($domain,$ignore_cache) = @_;
                   2498:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2499:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2500:     unless ($ignore_cache) {
                   2501:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2502:         if (defined($cached)) {
                   2503:             if (ref($result) eq 'HASH') {
                   2504:                 return %{$result};
                   2505:             }
1.943     raeburn  2506:         }
                   2507:     }
                   2508:     my %domdefaults;
                   2509:     my %domconfig =
1.989     raeburn  2510:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2511:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2512:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2513:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2514:                                   'coursecategories','autoenroll',
1.1172.2.146.  .13(raeb 2515:-23):                                   'helpsettings','wafproxy','ltisec',
                   2516:-23):                                   'toolsec','domexttool','exttool'],
                   2517:-23):                                   $domain);
1.1172.2.41  raeburn  2518:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2519:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2520:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2521:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2522:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2523:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2524:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2525:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.146.  .12(raeb 2526:-23):         $domdefaults{'portal_def_email'} = $domconfig{'defaults'}{'portal_def_email'};
                   2527:-23):         $domdefaults{'portal_def_web'} = $domconfig{'defaults'}{'portal_def_web'};
1.1172.2.91  raeburn  2528:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2529:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2530:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.1172.2.146.  .5(raebu 2531:22):         $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
1.943     raeburn  2532:     } else {
                   2533:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2534:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2535:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2536:     }
1.976     raeburn  2537:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2538:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2539:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2540:         } else {
                   2541:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2542:         }
1.1172.2.6  raeburn  2543:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2544:         foreach my $item (@usertools) {
                   2545:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2546:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2547:             }
                   2548:         }
1.1172.2.29  raeburn  2549:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2550:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2551:         }
1.976     raeburn  2552:     }
1.985     raeburn  2553:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2554:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2555:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2556:         }
                   2557:     }
1.1172.2.9  raeburn  2558:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2559:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2560:     }
1.989     raeburn  2561:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2562:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2563:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2564:         }
                   2565:     }
1.1047    raeburn  2566:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2567:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1172.2.144  raeburn  2568:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1172.2.60  raeburn  2569:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2570:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2571:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2572:         }
1.1172.2.41  raeburn  2573:         foreach my $type (@coursetypes) {
                   2574:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2575:                 unless ($type eq 'community') {
                   2576:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2577:                 }
                   2578:             }
                   2579:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2580:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2581:             }
1.1172.2.60  raeburn  2582:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2583:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2584:                     $domdefaults{$type.'postsubtimeout'} =
                   2585:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2586:                 }
                   2587:             }
1.1172.2.146.  .13(raeb 2588:-23):             if (ref($domconfig{'coursedefaults'}{'domexttool'}) eq 'HASH') {
                   2589:-23):                 $domdefaults{$type.'domexttool'} = $domconfig{'coursedefaults'}{'domexttool'}{$type};
                   2590:-23):             } else {
                   2591:-23):                 $domdefaults{$type.'domexttool'} = 1;
                   2592:-23):             }
                   2593:-23):             if (ref($domconfig{'coursedefaults'}{'exttool'}) eq 'HASH') {
                   2594:-23):                 $domdefaults{$type.'exttool'} = $domconfig{'coursedefaults'}{'exttool'}{$type};
                   2595:-23):             } else {
                   2596:-23):                 $domdefaults{$type.'exttool'} = 0;
                   2597:-23):             }
1.1172.2.30  raeburn  2598:         }
1.1172.2.67  raeburn  2599:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2600:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2601:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2602:                 if (@clonecodes) {
                   2603:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2604:                 }
                   2605:             }
                   2606:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2607:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2608:         }
1.1172.2.103  raeburn  2609:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2610:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2611:         }
1.1172.2.146.  .3(raebu 2612:22):         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
                   2613:22):             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
                   2614:22):         }
1.1047    raeburn  2615:     }
1.1073    raeburn  2616:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2617:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2618:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2619:         }
                   2620:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2621:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2622:         }
1.1172.2.62  raeburn  2623:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2624:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2625:         }
1.1172.2.137  raeburn  2626:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1172.2.136  raeburn  2627:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2628:         }
1.1073    raeburn  2629:     }
1.1172.2.41  raeburn  2630:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2631:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2632:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2633:                             'approval','limit');
                   2634:             foreach my $type (@coursetypes) {
                   2635:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2636:                     my @mgrdc = ();
                   2637:                     foreach my $item (@settings) {
                   2638:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2639:                             push(@mgrdc,$item);
                   2640:                         }
                   2641:                     }
                   2642:                     if (@mgrdc) {
                   2643:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2644:                     }
                   2645:                 }
                   2646:             }
                   2647:         }
                   2648:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2649:             foreach my $type (@coursetypes) {
                   2650:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2651:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2652:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2653:                     }
                   2654:                 }
                   2655:             }
                   2656:         }
                   2657:     }
1.1172.2.46  raeburn  2658:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2659:         $domdefaults{'catauth'} = 'std';
                   2660:         $domdefaults{'catunauth'} = 'std';
                   2661:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2662:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2663:         }
                   2664:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2665:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2666:         }
                   2667:     }
1.1172.2.76  raeburn  2668:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2669:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1172.2.146  raeburn  2670:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1172.2.76  raeburn  2671:     }
1.1172.2.89  raeburn  2672:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2673:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2674:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2675:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2676:         }
                   2677:     }
1.1172.2.142  raeburn  2678:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   2679:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
                   2680:             if ($domconfig{'wafproxy'}{$item}) {
                   2681:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
                   2682:             }
                   2683:         }
                   2684:     }
1.1172.2.146.  .4(raebu 2685:22):     if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   2686:22):         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
                   2687:22):             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
                   2688:22):             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
                   2689:22):             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
                   2690:22):         }
                   2691:22):         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
                   2692:22):             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
          .13(raeb 2693:-23):                 $domdefaults{'ltiprivhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
                   2694:-23):             }
                   2695:-23):         }
                   2696:-23):     }
                   2697:-23):     if (ref($domconfig{'toolsec'}) eq 'HASH') {
                   2698:-23):         if (ref($domconfig{'toolsec'}{'encrypt'}) eq 'HASH') {
                   2699:-23):             $domdefaults{'toolenc_crs'} = $domconfig{'toolsec'}{'encrypt'}{'crs'};
                   2700:-23):             $domdefaults{'toolenc_dom'} = $domconfig{'toolsec'}{'encrypt'}{'dom'};
                   2701:-23):         }
                   2702:-23):         if (ref($domconfig{'toolsec'}{'private'}) eq 'HASH') {
                   2703:-23):             if (ref($domconfig{'toolsec'}{'private'}{'keys'}) eq 'ARRAY') {
                   2704:-23):                 $domdefaults{'toolprivhosts'} = $domconfig{'toolsec'}{'private'}{'keys'};
          .4(raebu 2705:22):             }
                   2706:22):         }
                   2707:22):     }
1.1172.2.23  raeburn  2708:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2709:     return %domdefaults;
                   2710: }
                   2711: 
1.1172.2.106  raeburn  2712: sub get_dom_cats {
                   2713:     my ($dom) = @_;
                   2714:     return unless (&domain($dom));
                   2715:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2716:     unless (defined($cached)) {
                   2717:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2718:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2719:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2720:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2721:             } else {
                   2722:                 $cats = {};
                   2723:             }
                   2724:         } else {
                   2725:             $cats = {};
                   2726:         }
                   2727:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2728:     }
                   2729:     return $cats;
                   2730: }
                   2731: 
                   2732: sub get_dom_instcats {
                   2733:     my ($dom) = @_;
                   2734:     return unless (&domain($dom));
                   2735:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2736:     unless (defined($cached)) {
                   2737:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2738:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2739:         if ($totcodes > 0) {
                   2740:             my $caller = 'global';
                   2741:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2742:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2743:                 $instcats = {
1.1172.2.146.  .10(raeb 2744:-23):                                 totcodes => $totcodes,
1.1172.2.106  raeburn  2745:                                 codes => \%codes,
                   2746:                                 codetitles => \@codetitles,
                   2747:                                 cat_titles => \%cat_titles,
                   2748:                                 cat_order => \%cat_order,
                   2749:                             };
                   2750:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2751:             }
                   2752:         }
                   2753:     }
                   2754:     return $instcats;
                   2755: }
                   2756: 
                   2757: sub retrieve_instcodes {
                   2758:     my ($coursecodes,$dom) = @_;
                   2759:     my $totcodes;
                   2760:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2761:     foreach my $course (keys(%courses)) {
                   2762:         if (ref($courses{$course}) eq 'HASH') {
                   2763:             if ($courses{$course}{'inst_code'} ne '') {
                   2764:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2765:                 $totcodes ++;
                   2766:             }
                   2767:         }
                   2768:     }
                   2769:     return $totcodes;
                   2770: }
                   2771: 
1.1172.2.113  raeburn  2772: # --------------------------------------------- Get domain config for passwords
                   2773: 
                   2774: sub get_passwdconf {
                   2775:     my ($dom) = @_;
                   2776:     my (%passwdconf,$gotconf,$lookup);
                   2777:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2778:     if (defined($cached)) {
                   2779:         if (ref($result) eq 'HASH') {
                   2780:             %passwdconf = %{$result};
                   2781:             $gotconf = 1;
                   2782:         }
                   2783:     }
                   2784:     unless ($gotconf) {
                   2785:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2786:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2787:             %passwdconf = %{$domconfig{'passwords'}};
                   2788:         }
                   2789:         my $cachetime = 24*60*60;
                   2790:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2791:     }
                   2792:     return %passwdconf;
                   2793: }
                   2794: 
1.1172.2.146.  .1(raebu 2795:22): sub course_portal_url {
                   2796:22):     my ($cnum,$cdom,$r) = @_;
                   2797:22):     my $chome = &homeserver($cnum,$cdom);
                   2798:22):     my $hostname = &hostname($chome);
                   2799:22):     my $protocol = $protocol{$chome};
                   2800:22):     $protocol = 'http' if ($protocol ne 'https');
                   2801:22):     my %domdefaults = &get_domain_defaults($cdom);
                   2802:22):     my $firsturl;
                   2803:22):     if ($domdefaults{'portal_def'}) {
                   2804:22):         $firsturl = $domdefaults{'portal_def'};
                   2805:22):     } else {
                   2806:22):         my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
                   2807:22):         $hostname = $alias if ($alias ne '');
                   2808:22):         $firsturl = $protocol.'://'.$hostname;
                   2809:22):     }
                   2810:22):     return $firsturl;
                   2811:22): }
                   2812:22): 
          .12(raeb 2813:-23): sub url_prefix {
                   2814:-23):     my ($r,$dom,$home,$context) = @_;
                   2815:-23):     my $prefix;
                   2816:-23):     my %domdefs = &get_domain_defaults($dom);
                   2817:-23):     if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
                   2818:-23):         if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
                   2819:-23):             $prefix = $1;
                   2820:-23):         }
                   2821:-23):     }
                   2822:-23):     if ($prefix eq '') {
                   2823:-23):         my $hostname = &hostname($home);
                   2824:-23):         my $protocol = $protocol{$home};
                   2825:-23):         $protocol = 'http' if ($protocol{$home} ne 'https');
                   2826:-23):         my $alias = &use_proxy_alias($r,$home);
                   2827:-23):         $hostname = $alias if ($alias ne '');
                   2828:-23):         $prefix = $protocol.'://'.$hostname;
                   2829:-23):     }
                   2830:-23):     return $prefix;
                   2831:-23): }
                   2832:-23): 
1.344     www      2833: # --------------------------------------------------- Assign a key to a student
                   2834: 
                   2835: sub assign_access_key {
1.364     www      2836: #
                   2837: # a valid key looks like uname:udom#comments
                   2838: # comments are being appended
                   2839: #
1.498     www      2840:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2841:     $kdom=
1.620     albertel 2842:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2843:     $knum=
1.620     albertel 2844:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2845:     $cdom=
1.620     albertel 2846:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2847:     $cnum=
1.620     albertel 2848:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2849:     $udom=$env{'user.name'} unless (defined($udom));
                   2850:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2851:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2852:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2853:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2854:                                                   # assigned to this person
                   2855:                                                   # - this should not happen,
1.345     www      2856:                                                   # unless something went wrong
                   2857:                                                   # the first time around
                   2858: # ready to assign
1.364     www      2859:         $logentry=$1.'; '.$logentry;
1.496     www      2860:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2861:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2862: # key now belongs to user
1.346     www      2863: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2864:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2865:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2866:                 return 'ok';
                   2867:             } else {
                   2868:                 return 
                   2869:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2870: 	    }
                   2871:         } else {
                   2872:             return 'error: Could not assign key, try again later.';
                   2873:         }
1.364     www      2874:     } elsif (!$existing{$ckey}) {
1.345     www      2875: # the key does not exist
                   2876: 	return 'error: The key does not exist';
                   2877:     } else {
                   2878: # the key is somebody else's
                   2879: 	return 'error: The key is already in use';
                   2880:     }
1.344     www      2881: }
                   2882: 
1.364     www      2883: # ------------------------------------------ put an additional comment on a key
                   2884: 
                   2885: sub comment_access_key {
                   2886: #
                   2887: # a valid key looks like uname:udom#comments
                   2888: # comments are being appended
                   2889: #
                   2890:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2891:     $cdom=
1.620     albertel 2892:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2893:     $cnum=
1.620     albertel 2894:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2895:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2896:     if ($existing{$ckey}) {
                   2897:         $existing{$ckey}.='; '.$logentry;
                   2898: # ready to assign
1.367     www      2899:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2900:                                                  $cdom,$cnum) eq 'ok') {
                   2901: 	    return 'ok';
                   2902:         } else {
                   2903: 	    return 'error: Count not store comment.';
                   2904:         }
                   2905:     } else {
                   2906: # the key does not exist
                   2907: 	return 'error: The key does not exist';
                   2908:     }
                   2909: }
                   2910: 
1.344     www      2911: # ------------------------------------------------------ Generate a set of keys
                   2912: 
                   2913: sub generate_access_keys {
1.364     www      2914:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2915:     $cdom=
1.620     albertel 2916:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2917:     $cnum=
1.620     albertel 2918:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2919:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2920:     unless (($cdom) && ($cnum)) { return 0; }
                   2921:     if ($number>10000) { return 0; }
                   2922:     sleep(2); # make sure don't get same seed twice
                   2923:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2924:     my $total=0;
                   2925:     for (my $i=1;$i<=$number;$i++) {
                   2926:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2927:                   sprintf("%lx",int(100000*rand)).'-'.
                   2928:                   sprintf("%lx",int(100000*rand));
                   2929:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2930:        $newkey=~s/0/h/g; # and also 0 and O
                   2931:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2932:        if ($existing{$newkey}) {
                   2933:            $i--;
                   2934:        } else {
1.364     www      2935: 	  if (&put('accesskeys',
                   2936:               { $newkey => '# generated '.localtime().
1.620     albertel 2937:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2938:                            '; '.$logentry },
                   2939: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2940:               $total++;
                   2941: 	  }
                   2942:        }
                   2943:     }
1.620     albertel 2944:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2945:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2946:     return $total;
                   2947: }
                   2948: 
                   2949: # ------------------------------------------------------- Validate an accesskey
                   2950: 
                   2951: sub validate_access_key {
                   2952:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2953:     $cdom=
1.620     albertel 2954:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2955:     $cnum=
1.620     albertel 2956:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2957:     $udom=$env{'user.domain'} unless (defined($udom));
                   2958:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2959:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2960:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2961: }
                   2962: 
                   2963: # ------------------------------------- Find the section of student in a course
1.652     albertel 2964: sub devalidate_getsection_cache {
                   2965:     my ($udom,$unam,$courseid)=@_;
                   2966:     my $hashid="$udom:$unam:$courseid";
                   2967:     &devalidate_cache_new('getsection',$hashid);
                   2968: }
1.298     matthew  2969: 
1.815     albertel 2970: sub courseid_to_courseurl {
                   2971:     my ($courseid) = @_;
                   2972:     #already url style courseid
                   2973:     return $courseid if ($courseid =~ m{^/});
                   2974: 
                   2975:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2976: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2977: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2978: 	return "/$cdom/$cnum";
                   2979:     }
                   2980: 
                   2981:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2982:     if (exists($courseinfo{'num'})) {
                   2983: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2984:     }
                   2985: 
                   2986:     return undef;
                   2987: }
                   2988: 
1.298     matthew  2989: sub getsection {
                   2990:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2991:     my $cachetime=1800;
1.551     albertel 2992: 
                   2993:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2994:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2995:     if (defined($cached)) { return $result; }
                   2996: 
1.298     matthew  2997:     my %Pending; 
                   2998:     my %Expired;
                   2999:     #
                   3000:     # Each role can either have not started yet (pending), be active, 
                   3001:     #    or have expired.
                   3002:     #
                   3003:     # If there is an active role, we are done.
                   3004:     #
                   3005:     # If there is more than one role which has not started yet, 
                   3006:     #     choose the one which will start sooner
                   3007:     # If there is one role which has not started yet, return it.
                   3008:     #
                   3009:     # If there is more than one expired role, choose the one which ended last.
                   3010:     # If there is a role which has expired, return it.
                   3011:     #
1.815     albertel 3012:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  3013:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  3014:     foreach my $key (keys(%roleshash)) {
1.479     albertel 3015:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  3016:         my $section=$1;
                   3017:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  3018:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  3019:         my $now=time;
1.548     albertel 3020:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  3021:             $Expired{$end}=$section;
                   3022:             next;
                   3023:         }
1.548     albertel 3024:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  3025:             $Pending{$start}=$section;
                   3026:             next;
                   3027:         }
1.599     albertel 3028:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  3029:     }
                   3030:     #
                   3031:     # Presumedly there will be few matching roles from the above
                   3032:     # loop and the sorting time will be negligible.
                   3033:     if (scalar(keys(%Pending))) {
                   3034:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 3035:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  3036:     } 
                   3037:     if (scalar(keys(%Expired))) {
                   3038:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   3039:         my $time = pop(@sorted);
1.599     albertel 3040:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  3041:     }
1.599     albertel 3042:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  3043: }
1.70      www      3044: 
1.599     albertel 3045: sub save_cache {
                   3046:     &purge_remembered();
1.722     albertel 3047:     #&Apache::loncommon::validate_page();
1.620     albertel 3048:     undef(%env);
1.780     albertel 3049:     undef($env_loaded);
1.599     albertel 3050: }
1.452     albertel 3051: 
1.599     albertel 3052: my $to_remember=-1;
                   3053: my %remembered;
                   3054: my %accessed;
                   3055: my $kicks=0;
                   3056: my $hits=0;
1.849     albertel 3057: sub make_key {
                   3058:     my ($name,$id) = @_;
1.872     albertel 3059:     if (length($id) > 65 
                   3060: 	&& length(&escape($id)) > 200) {
                   3061: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   3062:     }
1.849     albertel 3063:     return &escape($name.':'.$id);
                   3064: }
                   3065: 
1.599     albertel 3066: sub devalidate_cache_new {
                   3067:     my ($name,$id,$debug) = @_;
                   3068:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  3069:     my $remembered_id=$name.':'.$id;
1.849     albertel 3070:     $id=&make_key($name,$id);
1.599     albertel 3071:     $memcache->delete($id);
1.1172.2.81  raeburn  3072:     delete($remembered{$remembered_id});
                   3073:     delete($accessed{$remembered_id});
1.599     albertel 3074: }
                   3075: 
                   3076: sub is_cached_new {
                   3077:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  3078:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   3079:                                      # keys in %remembered hash, which persists for
                   3080:                                      # duration of request (no restriction on key length).
                   3081:     if (exists($remembered{$remembered_id})) {
                   3082: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   3083: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3084: 	$hits++;
1.1172.2.81  raeburn  3085: 	return ($remembered{$remembered_id},1);
1.599     albertel 3086:     }
1.1172.2.81  raeburn  3087:     $id=&make_key($name,$id);
1.599     albertel 3088:     my $value = $memcache->get($id);
                   3089:     if (!(defined($value))) {
                   3090: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 3091: 	return (undef,undef);
1.416     albertel 3092:     }
1.599     albertel 3093:     if ($value eq '__undef__') {
                   3094: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   3095: 	$value=undef;
                   3096:     }
1.1172.2.81  raeburn  3097:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3098:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   3099:     return ($value,1);
                   3100: }
                   3101: 
                   3102: sub do_cache_new {
                   3103:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  3104:     my $remembered_id=$name.':'.$id;
1.849     albertel 3105:     $id=&make_key($name,$id);
1.599     albertel 3106:     my $setvalue=$value;
                   3107:     if (!defined($setvalue)) {
                   3108: 	$setvalue='__undef__';
                   3109:     }
1.623     albertel 3110:     if (!defined($time) ) {
                   3111: 	$time=600;
                   3112:     }
1.599     albertel 3113:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 3114:     my $result = $memcache->set($id,$setvalue,$time);
                   3115:     if (! $result) {
1.872     albertel 3116: 	&logthis("caching of id -> $id  failed");
1.910     albertel 3117: 	$memcache->disconnect_all();
1.872     albertel 3118:     }
1.600     albertel 3119:     # need to make a copy of $value
1.1172.2.81  raeburn  3120:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3121:     return $value;
                   3122: }
                   3123: 
                   3124: sub make_room {
1.1172.2.81  raeburn  3125:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3126: 
1.1172.2.81  raeburn  3127:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3128:                                     : $value;
1.599     albertel 3129:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  3130:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3131:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3132:     my $to_kick;
                   3133:     my $max_time=0;
                   3134:     foreach my $other (keys(%accessed)) {
                   3135: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3136: 	    $to_kick=$other;
                   3137: 	    $max_time=&tv_interval($accessed{$other});
                   3138: 	}
                   3139:     }
                   3140:     delete($remembered{$to_kick});
                   3141:     delete($accessed{$to_kick});
                   3142:     $kicks++;
                   3143:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3144:     return;
                   3145: }
                   3146: 
1.599     albertel 3147: sub purge_remembered {
1.604     albertel 3148:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3149:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3150:     undef(%remembered);
                   3151:     undef(%accessed);
1.428     albertel 3152: }
1.70      www      3153: # ------------------------------------- Read an entry from a user's environment
                   3154: 
                   3155: sub userenvironment {
                   3156:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3157:     my $items;
                   3158:     foreach my $item (@what) {
                   3159:         $items.=&escape($item).'&';
                   3160:     }
                   3161:     $items=~s/\&$//;
1.70      www      3162:     my %returnhash=();
1.1009    raeburn  3163:     my $uhome = &homeserver($unam,$udom);
                   3164:     unless ($uhome eq 'no_host') {
                   3165:         my @answer=split(/\&/, 
                   3166:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3167:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3168:             return %returnhash;
                   3169:         }
1.1009    raeburn  3170:         my $i;
                   3171:         for ($i=0;$i<=$#what;$i++) {
                   3172: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3173:         }
1.70      www      3174:     }
                   3175:     return %returnhash;
1.1       albertel 3176: }
                   3177: 
1.617     albertel 3178: # ---------------------------------------------------------- Get a studentphoto
                   3179: sub studentphoto {
                   3180:     my ($udom,$unam,$ext) = @_;
                   3181:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3182:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3183:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3184:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3185:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3186:             } else {
                   3187:                 my ($result,$perm_reqd)=
1.707     albertel 3188: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3189:                 if ($result eq 'ok') {
                   3190:                     if (!($perm_reqd eq 'yes')) {
                   3191:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3192:                     }
                   3193:                 }
                   3194:             }
                   3195:         }
                   3196:     } else {
                   3197:         my ($result,$perm_reqd) = 
1.707     albertel 3198: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3199:         if ($result eq 'ok') {
                   3200:             if (!($perm_reqd eq 'yes')) {
                   3201:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3202:             }
                   3203:         }
                   3204:     }
                   3205:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3206: }
                   3207: 
                   3208: sub retrievestudentphoto {
                   3209:     my ($udom,$unam,$ext,$type) = @_;
                   3210:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3211:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3212:     if ($ret eq 'ok') {
                   3213:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3214:         if ($type eq 'thumbnail') {
                   3215:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3216:         }
                   3217:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3218:         return $tokenurl;
                   3219:     } else {
                   3220:         if ($type eq 'thumbnail') {
                   3221:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3222:         } else { 
                   3223:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3224:         }
1.617     albertel 3225:     }
                   3226: }
                   3227: 
1.263     www      3228: # -------------------------------------------------------------------- New chat
                   3229: 
                   3230: sub chatsend {
1.724     raeburn  3231:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3232:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3233:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3234:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3235:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3236: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3237: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3238: }
                   3239: 
                   3240: # ------------------------------------------ Find current version of a resource
                   3241: 
                   3242: sub getversion {
                   3243:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  3244:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3245:     return &currentversion(&filelocation('',$fname));
                   3246: }
                   3247: 
                   3248: sub currentversion {
                   3249:     my $fname=shift;
                   3250:     my $author=$fname;
                   3251:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3252:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3253:     my $home=&homeserver($uname,$udom);
1.292     www      3254:     if ($home eq 'no_host') { 
                   3255:         return -1; 
                   3256:     }
1.1112    www      3257:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3258:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3259: 	return -1;
                   3260:     }
1.1112    www      3261:     return $answer;
1.263     www      3262: }
                   3263: 
1.1111    www      3264: #
                   3265: # Return special version number of resource if set by override, empty otherwise
                   3266: #
                   3267: sub usedversion {
                   3268:     my $fname=shift;
                   3269:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3270:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3271:     if ($urlversion) { return $urlversion; }
                   3272:     return '';
                   3273: }
                   3274: 
1.1       albertel 3275: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3276: 
1.1       albertel 3277: sub subscribe {
                   3278:     my $fname=shift;
1.761     raeburn  3279:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3280:     $fname=~s/[\n\r]//g;
1.1       albertel 3281:     my $author=$fname;
                   3282:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3283:     my ($udom,$uname)=split(/\//,$author);
                   3284:     my $home=homeserver($uname,$udom);
1.335     albertel 3285:     if ($home eq 'no_host') {
                   3286:         return 'not_found';
1.1       albertel 3287:     }
                   3288:     my $answer=reply("sub:$fname",$home);
1.64      www      3289:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3290: 	$answer.=' by '.$home;
                   3291:     }
1.1       albertel 3292:     return $answer;
                   3293: }
                   3294:     
1.8       www      3295: # -------------------------------------------------------------- Replicate file
                   3296: 
                   3297: sub repcopy {
                   3298:     my $filename=shift;
1.23      www      3299:     $filename=~s/\/+/\//g;
1.1142    raeburn  3300:     my $londocroot = $perlvar{'lonDocRoot'};
                   3301:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3302:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3303:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3304: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3305: 	return &repcopy_userfile($filename);
                   3306:     }
1.532     albertel 3307:     $filename=~s/[\n\r]//g;
1.8       www      3308:     my $transname="$filename.in.transfer";
1.828     www      3309: # FIXME: this should flock
1.607     raeburn  3310:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3311:     my $remoteurl=subscribe($filename);
1.64      www      3312:     if ($remoteurl =~ /^con_lost by/) {
                   3313: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3314:            return 'unavailable';
1.8       www      3315:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3316: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3317: 	   return 'not_found';
1.64      www      3318:     } elsif ($remoteurl =~ /^rejected by/) {
                   3319: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3320:            return 'forbidden';
1.20      www      3321:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3322:            return 'ok';
1.8       www      3323:     } else {
1.290     www      3324:         my $author=$filename;
                   3325:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3326:         my ($udom,$uname)=split(/\//,$author);
                   3327:         my $home=homeserver($uname,$udom);
                   3328:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3329:            my @parts=split(/\//,$filename);
                   3330:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3331:            if ($path ne "$londocroot/res") {
1.8       www      3332:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3333: 	       return 'bad_request';
1.8       www      3334:            }
                   3335:            my $count;
                   3336:            for ($count=5;$count<$#parts;$count++) {
                   3337:                $path.="/$parts[$count]";
                   3338:                if ((-e $path)!=1) {
                   3339: 		   mkdir($path,0777);
                   3340:                }
                   3341:            }
                   3342:            my $ua=new LWP::UserAgent;
                   3343:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3344:            my $response=$ua->request($request,$transname);
                   3345:            if ($response->is_error()) {
                   3346: 	       unlink($transname);
                   3347:                my $message=$response->status_line;
1.672     albertel 3348:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3349:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3350:                return 'unavailable';
1.8       www      3351:            } else {
1.16      www      3352: 	       if ($remoteurl!~/\.meta$/) {
                   3353:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3354:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3355:                   if ($mresponse->is_error()) {
                   3356: 		      unlink($filename.'.meta');
                   3357:                       &logthis(
1.672     albertel 3358:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3359:                   }
                   3360: 	       }
1.8       www      3361:                rename($transname,$filename);
1.607     raeburn  3362:                return 'ok';
1.8       www      3363:            }
1.290     www      3364:        }
1.8       www      3365:     }
1.330     www      3366: }
                   3367: 
1.1172.2.124  raeburn  3368: # ------------------------------------------------- Unsubscribe from a resource
                   3369: 
                   3370: sub unsubscribe {
                   3371:     my ($fname) = @_;
                   3372:     my $answer;
                   3373:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3374:     $fname=~s/[\n\r]//g;
                   3375:     my $author=$fname;
                   3376:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3377:     my ($udom,$uname)=split(/\//,$author);
                   3378:     my $home=homeserver($uname,$udom);
                   3379:     if ($home eq 'no_host') {
                   3380:         $answer = 'no_host';
                   3381:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3382:         $answer = 'home';
                   3383:     } else {
1.1172.2.125  raeburn  3384:         $answer = reply("unsub:$fname",$home);
1.1172.2.124  raeburn  3385:     }
                   3386:     return $answer;
                   3387: }
                   3388: 
1.330     www      3389: # ------------------------------------------------ Get server side include body
                   3390: sub ssi_body {
1.381     albertel 3391:     my ($filelink,%form)=@_;
1.606     matthew  3392:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3393:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3394:     }
1.953     www      3395:     my $output='';
                   3396:     my $response;
1.980     raeburn  3397:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3398:        ($output,$response)=&externalssi($filelink);
1.953     www      3399:     } else {
1.1004    droeschl 3400:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3401:        $filelink .= 'inhibitmenu=yes';
1.953     www      3402:        ($output,$response)=&ssi($filelink,%form);
                   3403:     }
1.778     albertel 3404:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3405:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3406:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3407:     if (wantarray) {
                   3408:         return ($output, $response);
                   3409:     } else {
                   3410:         return $output;
                   3411:     }
1.8       www      3412: }
                   3413: 
1.15      www      3414: # --------------------------------------------------------- Server Side Include
                   3415: 
1.782     albertel 3416: sub absolute_url {
1.1172.2.145  raeburn  3417:     my ($host_name,$unalias,$keep_proto) = @_;
1.782     albertel 3418:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3419:     if ($host_name eq '') {
                   3420: 	$host_name = $ENV{'SERVER_NAME'};
                   3421:     }
1.1172.2.145  raeburn  3422:     if ($unalias) {
                   3423:         my $alias = &get_proxy_alias();
                   3424:         if ($alias eq $host_name) {
                   3425:             my $lonhost = $perlvar{'lonHostID'};
                   3426:             my $hostname = &hostname($lonhost);
                   3427:             my $lcproto;
                   3428:             if (($keep_proto) || ($hostname eq '')) {
                   3429:                 $lcproto = $protocol;
                   3430:             } else {
                   3431:                 $lcproto = $protocol{$lonhost};
                   3432:                 $lcproto = 'http' if ($lcproto ne 'https');
                   3433:                 $lcproto .= '://';
                   3434:             }
                   3435:             unless ($hostname eq '') {
                   3436:                 return $lcproto.$hostname;
                   3437:             }
                   3438:         }
                   3439:     } 
1.782     albertel 3440:     return $protocol.$host_name;
                   3441: }
                   3442: 
1.942     foxr     3443: #
                   3444: #   Server side include.
                   3445: # Parameters:
                   3446: #  fn     Possibly encrypted resource name/id.
                   3447: #  form   Hash that describes how the rendering should be done
                   3448: #         and other things.
1.944     foxr     3449: # Returns:
1.950     raeburn  3450: #   Scalar context: The content of the response.
                   3451: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3452: #     
1.15      www      3453: sub ssi {
                   3454: 
1.944     foxr     3455:     my ($fn,%form)=@_;
1.1172.2.145  raeburn  3456:     my ($host,$request,$response);
                   3457:     $host = &absolute_url('',1);
1.711     albertel 3458: 
                   3459:     $form{'no_update_last_known'}=1;
1.895     albertel 3460:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3461:     if (%form) {
1.1172.2.145  raeburn  3462:       $request=new HTTP::Request('POST',$host.$fn);
1.1172.2.58  raeburn  3463:       $request->content(join('&',map {
                   3464:             my $name = escape($_);
                   3465:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3466:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3467:             : &escape($form{$_}) );
                   3468:         } keys(%form)));
1.23      www      3469:     } else {
1.1172.2.145  raeburn  3470:       $request=new HTTP::Request('GET',$host.$fn);
1.23      www      3471:     }
                   3472: 
1.15      www      3473:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3474: 
1.1172.2.101  raeburn  3475:     if (($env{'request.course.id'}) &&
                   3476:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3477:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3478:         ($form{'grade_symb'} ne '') &&
                   3479:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3480:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3481:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3482:             my $ua=new LWP::UserAgent;
                   3483:             $ua->local_address('127.0.0.1');
                   3484:             $response = $ua->request($request);
                   3485:         } else {
                   3486:             {
                   3487:                 require LWP::Protocol::http;
                   3488:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3489:                 my $ua=new LWP::UserAgent;
                   3490:                 $response = $ua->request($request);
                   3491:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3492:             }
                   3493:         }
                   3494:     } else {
                   3495:         my $ua=new LWP::UserAgent;
                   3496:         $response = $ua->request($request);
                   3497:     }
1.944     foxr     3498:     if (wantarray) {
1.1172.2.3  raeburn  3499: 	return ($response->content, $response);
1.944     foxr     3500:     } else {
1.1172.2.3  raeburn  3501: 	return $response->content;
1.942     foxr     3502:     }
1.324     www      3503: }
                   3504: 
                   3505: sub externalssi {
                   3506:     my ($url)=@_;
                   3507:     my $ua=new LWP::UserAgent;
                   3508:     my $request=new HTTP::Request('GET',$url);
                   3509:     my $response=$ua->request($request);
1.954     raeburn  3510:     if (wantarray) {
                   3511:         return ($response->content, $response);
                   3512:     } else {
                   3513:         return $response->content;
                   3514:     }
1.15      www      3515: }
1.254     www      3516: 
1.1172.2.98  raeburn  3517: # If the local copy of a replicated resource is outdated, trigger a
                   3518: # connection from the homeserver to flush the delayed queue. If no update
                   3519: # happens, remove local copies of outdated resource (and corresponding
                   3520: # metadata file).
                   3521: 
                   3522: sub remove_stale_resfile {
                   3523:     my ($url) = @_;
                   3524:     my $removed;
                   3525:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3526:         my $audom = $1;
                   3527:         my $auname = $2;
                   3528:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3529:             my $homeserver = &homeserver($auname,$audom);
                   3530:             unless (($homeserver eq 'no_host') ||
                   3531:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3532:                 my $fname = &filelocation('',$url);
                   3533:                 if (-e $fname) {
                   3534:                     my $hostname = &hostname($homeserver);
                   3535:                     if ($hostname) {
1.1172.2.120  raeburn  3536:                         my $protocol = $protocol{$homeserver};
                   3537:                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3538:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120  raeburn  3539:                         my $ua=new LWP::UserAgent;
                   3540:                         $ua->timeout(5);
1.1172.2.98  raeburn  3541:                         my $request=new HTTP::Request('HEAD',$uri);
                   3542:                         my $response=$ua->request($request);
                   3543:                         if ($response->is_success()) {
                   3544:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3545:                             my $locmodtime = (stat($fname))[9];
                   3546:                             if ($locmodtime < $remmodtime) {
                   3547:                                 my $stale;
                   3548:                                 my $answer = &reply('pong',$homeserver);
                   3549:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3550:                                     sleep(0.2);
                   3551:                                     $locmodtime = (stat($fname))[9];
                   3552:                                     if ($locmodtime < $remmodtime) {
                   3553:                                         my $posstransfer = $fname.'.in.transfer';
                   3554:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3555:                                             $removed = 1;
                   3556:                                         } else {
                   3557:                                             $stale = 1;
                   3558:                                         }
                   3559:                                     } else {
                   3560:                                         $removed = 1;
                   3561:                                     }
                   3562:                                 } else {
                   3563:                                     $stale = 1;
                   3564:                                 }
                   3565:                                 if ($stale) {
1.1172.2.124  raeburn  3566:                                     if (unlink($fname)) {
                   3567:                                         if ($uri!~/\.meta$/) {
                   3568:                                             if (-e $fname.'.meta') {
                   3569:                                                 unlink($fname.'.meta');
                   3570:                                             }
                   3571:                                         }
                   3572:                                         my $unsubresult = &unsubscribe($fname);
                   3573:                                         unless ($unsubresult eq 'ok') {
                   3574:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3575:                                         }
                   3576:                                         $removed = 1;
1.1172.2.98  raeburn  3577:                                     }
                   3578:                                 }
                   3579:                             }
                   3580:                         }
                   3581:                     }
                   3582:                 }
                   3583:             }
                   3584:         }
                   3585:     }
                   3586:     return $removed;
                   3587: }
                   3588: 
1.492     albertel 3589: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3590: 
                   3591: sub allowuploaded {
                   3592:     my ($srcurl,$url)=@_;
                   3593:     $url=&clutter(&declutter($url));
                   3594:     my $dir=$url;
                   3595:     $dir=~s/\/[^\/]+$//;
                   3596:     my %httpref=();
                   3597:     my $httpurl=&hreflocation('',$url);
                   3598:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3599:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3600: }
1.477     raeburn  3601: 
1.1172.2.13  raeburn  3602: #
                   3603: # Determine if the current user should be able to edit a particular resource,
                   3604: # when viewing in course context.
                   3605: # (a) When viewing resource used to determine if "Edit" item is included in
                   3606: #     Functions.
                   3607: # (b) When displaying folder contents in course editor, used to determine if
                   3608: #     "Edit" link will be displayed alongside resource.
                   3609: #
                   3610: #  input: six args -- filename (decluttered), course number, course domain,
                   3611: #                   url, symb (if registered) and group (if this is a group
                   3612: #                   item -- e.g., bulletin board, group page etc.).
                   3613: #  output: array of five scalars --
                   3614: #          $cfile -- url for file editing if editable on current server
                   3615: #          $home -- homeserver of resource (i.e., for author if published,
                   3616: #                                           or course if uploaded.).
                   3617: #          $switchserver --  1 if server switch will be needed.
                   3618: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3619: #          $forceview -- 1 if icon/link should be to go to view mode
                   3620: #
                   3621: 
                   3622: sub can_edit_resource {
                   3623:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3624:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3625: #
                   3626: # For aboutme pages user can only edit his/her own.
                   3627: #
                   3628:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3629:         my ($sdom,$sname) = ($1,$2);
                   3630:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3631:             $home = $env{'user.home'};
                   3632:             $cfile = $resurl;
                   3633:             if ($env{'form.forceedit'}) {
                   3634:                 $forceview = 1;
                   3635:             } else {
                   3636:                 $forceedit = 1;
                   3637:             }
                   3638:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3639:         } else {
                   3640:             return;
                   3641:         }
                   3642:     }
                   3643: 
                   3644:     if ($env{'request.course.id'}) {
                   3645:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3646:         if ($group ne '') {
                   3647: # if this is a group homepage or group bulletin board, check group privs
                   3648:             my $allowed = 0;
                   3649:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3650:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3651:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3652:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3653:                     $allowed = 1;
                   3654:                 }
                   3655:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3656:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3657:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3658:                     $allowed = 1;
                   3659:                 }
                   3660:             }
                   3661:             if ($allowed) {
                   3662:                 $home=&homeserver($cnum,$cdom);
                   3663:                 if ($env{'form.forceedit'}) {
                   3664:                     $forceview = 1;
                   3665:                 } else {
                   3666:                     $forceedit = 1;
                   3667:                 }
                   3668:                 $cfile = $resurl;
                   3669:             } else {
                   3670:                 return;
                   3671:             }
                   3672:         } else {
1.1172.2.15  raeburn  3673:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3674:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3675:                     return;
                   3676:                 }
                   3677:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3678: #
                   3679: # No edit allowed where CC has switched to student role.
                   3680: #
                   3681:                 return;
                   3682:             }
                   3683:         }
                   3684:     }
                   3685: 
                   3686:     if ($file ne '') {
                   3687:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3688:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3689:                 $uploaded = 1;
                   3690:                 $incourse = 1;
                   3691:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3692:                     $cfile = &hreflocation('',$file);
                   3693:                     if ($env{'form.forceedit'}) {
                   3694:                         $forceview = 1;
                   3695:                     } else {
                   3696:                         $forceedit = 1;
                   3697:                     }
                   3698:                 }
                   3699:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3700:                 $incourse = 1;
                   3701:                 if ($env{'form.forceedit'}) {
                   3702:                     $forceview = 1;
                   3703:                 } else {
                   3704:                     $forceedit = 1;
                   3705:                 }
                   3706:                 $cfile = $resurl;
                   3707:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3708:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3709:                     $incourse = 1;
                   3710:                     if ($env{'form.forceedit'}) {
                   3711:                         $forceview = 1;
                   3712:                     } else {
                   3713:                         $forceedit = 1;
                   3714:                     }
                   3715:                     $cfile = $resurl;
                   3716:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3717:                     $incourse = 1;
                   3718:                     $cfile = $resurl.'/smpedit';
                   3719:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3720:                     $incourse = 1;
                   3721:                     if ($env{'form.forceedit'}) {
                   3722:                         $forceview = 1;
                   3723:                     } else {
                   3724:                         $forceedit = 1;
                   3725:                     }
                   3726:                     $cfile = $resurl;
1.1172.2.122  raeburn  3727:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3728:                     my ($map,$id,$res) = &decode_symb($symb);
                   3729:                     if ($map =~ /\.page$/) {
                   3730:                         $incourse = 1;
                   3731:                         if ($env{'form.forceedit'}) {
                   3732:                             $forceview = 1;
                   3733:                             $cfile = $map;
                   3734:                         } else {
                   3735:                             $forceedit = 1;
                   3736:                             $cfile =  '/adm/wrapper'.$resurl;
                   3737:                         }
                   3738:                     }
1.1172.2.146.  .1(raebu 3739:22):                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3740:22):                     $incourse = 1;
                   3741:22):                     if ($env{'form.forceedit'}) {
                   3742:22):                         $forceview = 1;
                   3743:22):                     } else {
                   3744:22):                         $forceedit = 1;
                   3745:22):                     }
                   3746:22):                     $cfile = $resurl;
1.1172.2.15  raeburn  3747:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3748:                     $incourse = 1;
                   3749:                     if ($env{'form.forceedit'}) {
                   3750:                         $forceview = 1;
                   3751:                     } else {
                   3752:                         $forceedit = 1;
                   3753:                     }
                   3754:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3755:                 }
                   3756:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3757:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3758:                 if (&is_on_map($template)) {
                   3759:                     $incourse = 1;
                   3760:                     $forceview = 1;
                   3761:                     $cfile = $template;
                   3762:                 }
                   3763:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3764:                 $incourse = 1;
                   3765:                 if ($env{'form.forceedit'}) {
                   3766:                     $forceview = 1;
                   3767:                 } else {
                   3768:                     $forceedit = 1;
                   3769:                 }
                   3770:                 $cfile = $resurl;
1.1172.2.146.  .1(raebu 3771:22):             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3772:22):                 $incourse = 1;
                   3773:22):                 if ($env{'form.forceedit'}) {
                   3774:22):                     $forceview = 1;
                   3775:22):                 } else {
                   3776:22):                     $forceedit = 1;
                   3777:22):                 }
                   3778:22):                 $cfile = $resurl;
1.1172.2.13  raeburn  3779:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3780:                 $incourse = 1;
                   3781:                 $forceview = 1;
                   3782:                 if ($symb) {
                   3783:                     my ($map,$id,$res)=&decode_symb($symb);
                   3784:                     $env{'request.symb'} = $symb;
                   3785:                     $cfile = &clutter($res);
                   3786:                 } else {
                   3787:                     $cfile = $env{'form.suppurl'};
1.1172.2.146.  .1(raebu 3788:22):                     my $escfile = &unescape($cfile);
                   3789:22):                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3790:22):                         $cfile = '/adm/wrapper'.$escfile;
                   3791:22):                     } else {
                   3792:22):                         $escfile =~ s{^http://}{};
                   3793:22):                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3794:22):                     }
1.1172.2.13  raeburn  3795:                 }
1.1172.2.31  raeburn  3796:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3797:                 if ($env{'form.forceedit'}) {
                   3798:                     $forceview = 1;
                   3799:                 } else {
                   3800:                     $forceedit = 1;
                   3801:                 }
                   3802:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3803:             }
                   3804:         }
                   3805:         if ($uploaded || $incourse) {
                   3806:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3807:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3808:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3809:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3810:             # Check that the user has permission to edit this resource
                   3811:             my $setpriv = 1;
                   3812:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3813:             if (defined($cfudom)) {
                   3814:                 $home=&homeserver($cfuname,$cfudom);
                   3815:                 $cfile=$file;
                   3816:             }
                   3817:         }
                   3818:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3819:             (($home ne '') && ($home ne 'no_host'))) {
                   3820:             my @ids=&current_machine_ids();
                   3821:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3822:                 $switchserver=1;
                   3823:             }
                   3824:         }
                   3825:     }
                   3826:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3827: }
                   3828: 
                   3829: sub is_course_upload {
                   3830:     my ($file,$cnum,$cdom) = @_;
                   3831:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3832:     $uploadpath =~ s{^\/}{};
                   3833:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3834:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3835:         return 1;
                   3836:     }
                   3837:     return;
                   3838: }
                   3839: 
                   3840: sub in_course {
                   3841:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3842:     if ($hideprivileged) {
                   3843:         my $skipuser;
1.1172.2.23  raeburn  3844:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3845:         my @possdoms = ($cdom);
                   3846:         if ($coursehash{'checkforpriv'}) {
                   3847:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3848:         }
                   3849:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3850:             $skipuser = 1;
                   3851:             if ($coursehash{'nothideprivileged'}) {
                   3852:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3853:                     my $user;
                   3854:                     if ($item =~ /:/) {
                   3855:                         $user = $item;
                   3856:                     } else {
                   3857:                         $user = join(':',split(/[\@]/,$item));
                   3858:                     }
                   3859:                     if ($user eq $uname.':'.$udom) {
                   3860:                         undef($skipuser);
                   3861:                         last;
                   3862:                     }
                   3863:                 }
                   3864:             }
                   3865:             if ($skipuser) {
                   3866:                 return 0;
                   3867:             }
                   3868:         }
                   3869:     }
                   3870:     $type ||= 'any';
                   3871:     if (!defined($cdom) || !defined($cnum)) {
                   3872:         my $cid  = $env{'request.course.id'};
                   3873:         $cdom = $env{'course.'.$cid.'.domain'};
                   3874:         $cnum = $env{'course.'.$cid.'.num'};
                   3875:     }
                   3876:     my $typesref;
                   3877:     if (($type eq 'any') || ($type eq 'all')) {
                   3878:         $typesref = ['active','previous','future'];
                   3879:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3880:         $typesref = [$type];
                   3881:     }
                   3882:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3883:                               $typesref,undef,[$cdom]);
                   3884:     my ($tmp) = keys(%roles);
                   3885:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3886:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3887:     if (@course_roles > 0) {
                   3888:         return 1;
                   3889:     }
                   3890:     return 0;
                   3891: }
                   3892: 
1.478     albertel 3893: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3894: # input: action, courseID, current domain, intended
1.637     raeburn  3895: #        path to file, source of file, instruction to parse file for objects,
                   3896: #        ref to hash for embedded objects,
                   3897: #        ref to hash for codebase of java objects.
1.1095    raeburn  3898: #        reference to scalar to accommodate mime type determined
                   3899: #          from File::MMagic if $parser = parse.
1.637     raeburn  3900: #
1.485     raeburn  3901: # output: url to file (if action was uploaddoc), 
                   3902: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3903: #
1.478     albertel 3904: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3905: # course.
1.477     raeburn  3906: #
1.478     albertel 3907: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3908: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3909: #          course's home server.
1.477     raeburn  3910: #
1.478     albertel 3911: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3912: #          be copied from $source (current location) to 
                   3913: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3914: #         and will then be copied to
                   3915: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3916: #         course's home server.
1.485     raeburn  3917: #
1.481     raeburn  3918: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3919: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3920: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3921: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3922: #         in course's home server.
1.637     raeburn  3923: #
1.477     raeburn  3924: 
                   3925: sub process_coursefile {
1.1095    raeburn  3926:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3927:         $mimetype)=@_;
1.477     raeburn  3928:     my $fetchresult;
1.638     albertel 3929:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3930:     if ($action eq 'propagate') {
1.638     albertel 3931:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3932: 			     $home);
1.481     raeburn  3933:     } else {
1.477     raeburn  3934:         my $fpath = '';
                   3935:         my $fname = $file;
1.478     albertel 3936:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3937:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3938:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3939:         if ($action eq 'copy') {
                   3940:             if ($source eq '') {
                   3941:                 $fetchresult = 'no source file';
                   3942:                 return $fetchresult;
                   3943:             } else {
                   3944:                 my $destination = $filepath.'/'.$fname;
                   3945:                 rename($source,$destination);
                   3946:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3947:                                  $home);
1.481     raeburn  3948:             }
                   3949:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3950:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3951:             print $fh $env{'form.'.$source};
1.481     raeburn  3952:             close($fh);
1.637     raeburn  3953:             if ($parser eq 'parse') {
1.1024    raeburn  3954:                 my $mm = new File::MMagic;
1.1095    raeburn  3955:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3956:                 if ($type eq 'text/html') {
1.1024    raeburn  3957:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3958:                     unless ($parse_result eq 'ok') {
                   3959:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3960:                     }
1.637     raeburn  3961:                 }
1.1095    raeburn  3962:                 if (ref($mimetype)) {
                   3963:                     $$mimetype = $type;
                   3964:                 } 
1.637     raeburn  3965:             }
1.477     raeburn  3966:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3967:                                  $home);
1.481     raeburn  3968:             if ($fetchresult eq 'ok') {
                   3969:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3970:             } else {
                   3971:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3972:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3973:                 return '/adm/notfound.html';
                   3974:             }
1.477     raeburn  3975:         }
                   3976:     }
1.485     raeburn  3977:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3978:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3979:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3980:     }
                   3981:     return $fetchresult;
                   3982: }
                   3983: 
1.637     raeburn  3984: sub build_filepath {
                   3985:     my ($fpath) = @_;
                   3986:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3987:     unless ($fpath eq '') {
                   3988:         my @parts=split('/',$fpath);
                   3989:         foreach my $part (@parts) {
                   3990:             $filepath.= '/'.$part;
                   3991:             if ((-e $filepath)!=1) {
                   3992:                 mkdir($filepath,0777);
                   3993:             }
                   3994:         }
                   3995:     }
                   3996:     return $filepath;
                   3997: }
                   3998: 
                   3999: sub store_edited_file {
1.638     albertel 4000:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  4001:     my $file = $primary_url;
                   4002:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   4003:     my $fpath = '';
                   4004:     my $fname = $file;
                   4005:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   4006:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   4007:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  4008:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  4009:     print $fh $content;
                   4010:     close($fh);
1.638     albertel 4011:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  4012:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4013: 			  $home);
1.637     raeburn  4014:     if ($$fetchresult eq 'ok') {
                   4015:         return '/uploaded/'.$fpath.'/'.$fname;
                   4016:     } else {
1.638     albertel 4017:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   4018: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  4019:         return '/adm/notfound.html';
                   4020:     }
                   4021: }
                   4022: 
1.531     albertel 4023: sub clean_filename {
1.831     albertel 4024:     my ($fname,$args)=@_;
1.315     www      4025: # Replace Windows backslashes by forward slashes
1.257     www      4026:     $fname=~s/\\/\//g;
1.831     albertel 4027:     if (!$args->{'keep_path'}) {
                   4028:         # Get rid of everything but the actual filename
                   4029: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   4030:     }
1.315     www      4031: # Replace spaces by underscores
                   4032:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  4033: # Transliterate non-ascii text to ascii
                   4034:     my $lang = &Apache::lonlocal::current_language();
                   4035:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      4036: # Replace all other weird characters by nothing
1.831     albertel 4037:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 4038: # Replace all .\d. sequences with _\d. so they no longer look like version
                   4039: # numbers
                   4040:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.140  raeburn  4041: # Replace three or more adjacent underscores with one for consistency
                   4042: # with loncfile::filename_check() so complete url can be extracted by
                   4043: # lonnet::decode_symb()
                   4044:     $fname=~s/_{3,}/_/g;
1.531     albertel 4045:     return $fname;
                   4046: }
1.1172.2.110  raeburn  4047: 
1.1051    raeburn  4048: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   4049: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   4050: # image with the same aspect ratio as the original, but with dimensions which do 
                   4051: # not exceed $resizewidth and $resizeheight.
                   4052:  
1.984     neumanie 4053: sub resizeImage {
1.1051    raeburn  4054:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   4055:     my $ima = Image::Magick->new;
                   4056:     my $resized;
                   4057:     if (-e $img_path) {
                   4058:         $ima->Read($img_path);
                   4059:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   4060:             my $width = $ima->Get('width');
                   4061:             my $height = $ima->Get('height');
                   4062:             if ($width > $resizewidth) {
                   4063: 	        my $factor = $width/$resizewidth;
                   4064:                 my $newheight = $height/$factor;
                   4065:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   4066:                 $resized = 1;
                   4067:             }
                   4068:         }
                   4069:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   4070:             my $width = $ima->Get('width');
                   4071:             my $height = $ima->Get('height');
                   4072:             if ($height > $resizeheight) {
                   4073:                 my $factor = $height/$resizeheight;
                   4074:                 my $newwidth = $width/$factor;
                   4075:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   4076:                 $resized = 1;
                   4077:             }
                   4078:         }
                   4079:         if ($resized) {
                   4080:             $ima->Write($img_path);
                   4081:         }
                   4082:     }
                   4083:     return;
1.977     amueller 4084: }
                   4085: 
1.608     albertel 4086: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 4087: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  4088: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  4089: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.146.  .13(raeb 4090:-23): #                                    canceloverwrite, scantron, toollogo or ''. 
1.1090    raeburn  4091: #                   if 'coursedoc': upload to the current course
                   4092: #                   if 'existingfile': write file to tmp/overwrites directory 
                   4093: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   4094: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 4095: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  4096: #        $parser - instruction to parse file for objects ($parser = parse) or
                   4097: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   4098: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   4099: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  4100: #        $allfiles - reference to hash for embedded objects
                   4101: #        $codebase - reference to hash for codebase of java objects
1.1172.2.146.  .13(raeb 4102:-23): #        $destuname - username for permanent storage of uploaded file
                   4103:-23): #        $destudom - domain for permanaent storage of uploaded file
1.860     raeburn  4104: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   4105: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  4106: #        $resizewidth - width (pixels) to which to resize uploaded image
                   4107: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  4108: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  4109: #                    from File::MMagic.
1.858     raeburn  4110: # 
1.686     albertel 4111: # output: url of file in userspace, or error: <message> 
                   4112: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 4113: 
1.531     albertel 4114: sub userfileupload {
1.1090    raeburn  4115:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  4116:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 4117:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 4118:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 4119:     $fname=&clean_filename($fname);
1.1090    raeburn  4120:     # See if there is anything left
1.257     www      4121:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  4122:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   4123:     if ($fname =~ /^\./) {
                   4124:         my ($s,$usec) = &gettimeofday();
                   4125:         while (length($usec) < 6) {
                   4126:             $usec = '0'.$usec;
                   4127:         }
                   4128:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   4129:     }
1.1090    raeburn  4130:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   4131:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   4132:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   4133:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  4134:         my $now = time;
1.1090    raeburn  4135:         my $filepath;
1.1095    raeburn  4136:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  4137:              $filepath = 'tmp/helprequests/'.$now;
                   4138:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   4139:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   4140:                          '_'.$env{'user.domain'}.'/pending';
                   4141:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   4142:             my ($docuname,$docudom);
1.1172.2.96  raeburn  4143:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  4144:                 $docudom = $destudom;
                   4145:             } else {
                   4146:                 $docudom = $env{'user.domain'};
                   4147:             }
1.1172.2.96  raeburn  4148:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  4149:                 $docuname = $destuname;
                   4150:             } else {
                   4151:                 $docuname = $env{'user.name'};
                   4152:             }
                   4153:             if (exists($env{'form.group'})) {
                   4154:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4155:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4156:             }
                   4157:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   4158:             if ($context eq 'canceloverwrite') {
                   4159:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   4160:                 if (-e  $tempfile) {
                   4161:                     my @info = stat($tempfile);
                   4162:                     if ($info[9] eq $env{'form.timestamp'}) {
                   4163:                         unlink($tempfile);
                   4164:                     }
                   4165:                 }
                   4166:                 return;
1.523     raeburn  4167:             }
                   4168:         }
1.1090    raeburn  4169:         # Create the directory if not present
1.741     raeburn  4170:         my @parts=split(/\//,$filepath);
                   4171:         my $fullpath = $perlvar{'lonDaemons'};
                   4172:         for (my $i=0;$i<@parts;$i++) {
                   4173:             $fullpath .= '/'.$parts[$i];
                   4174:             if ((-e $fullpath)!=1) {
                   4175:                 mkdir($fullpath,0777);
                   4176:             }
                   4177:         }
1.1172.2.96  raeburn  4178:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  4179:         print $fh $env{'form.'.$formname};
                   4180:         close($fh);
1.1090    raeburn  4181:         if ($context eq 'existingfile') {
                   4182:             my @info = stat($fullpath.'/'.$fname);
                   4183:             return ($fullpath.'/'.$fname,$info[9]);
                   4184:         } else {
                   4185:             return $fullpath.'/'.$fname;
                   4186:         }
1.523     raeburn  4187:     }
1.995     raeburn  4188:     if ($subdir eq 'scantron') {
                   4189:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4190:     } else {
1.995     raeburn  4191:         $fname="$subdir/$fname";
                   4192:     }
1.1090    raeburn  4193:     if ($context eq 'coursedoc') {
1.638     albertel 4194: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4195: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4196:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4197:             return &finishuserfileupload($docuname,$docudom,
                   4198: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4199: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4200:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4201:         } else {
1.1172.2.21  raeburn  4202:             if ($env{'form.folder'}) {
                   4203:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4204:             }
1.638     albertel 4205:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4206: 				       $fname,$formname,$parser,
1.1095    raeburn  4207: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4208:         }
1.719     banghart 4209:     } elsif (defined($destuname)) {
                   4210:         my $docuname=$destuname;
                   4211:         my $docudom=$destudom;
1.860     raeburn  4212: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4213: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4214:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4215:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4216:     } else {
1.638     albertel 4217:         my $docuname=$env{'user.name'};
                   4218:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  4219:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4220:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4221:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4222:         }
1.860     raeburn  4223: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4224: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4225:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4226:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4227:     }
1.271     www      4228: }
                   4229: 
                   4230: sub finishuserfileupload {
1.860     raeburn  4231:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4232:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4233:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4234:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4235:   
1.860     raeburn  4236:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4237:     $file=$fname;
                   4238:     if ($fname=~m|/|) {
                   4239:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4240: 	$path.=$fnamepath.'/';
                   4241:     }
1.259     www      4242:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4243:     my $count;
                   4244:     for ($count=4;$count<=$#parts;$count++) {
                   4245:         $filepath.="/$parts[$count]";
                   4246:         if ((-e $filepath)!=1) {
                   4247: 	    mkdir($filepath,0777);
                   4248:         }
                   4249:     }
1.984     neumanie 4250: 
1.258     www      4251: # Save the file
                   4252:     {
1.1172.2.96  raeburn  4253: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4254: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4255: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4256: 	    return '/adm/notfound.html';
                   4257: 	}
1.1090    raeburn  4258:         if ($context eq 'overwrite') {
1.1117    foxr     4259:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4260:             my $target = $filepath.'/'.$file;
                   4261:             if (-e $source) {
                   4262:                 my @info = stat($source);
                   4263:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4264:                     unless (&File::Copy::move($source,$target)) {
                   4265:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4266:                         return "Moving from $source failed";
                   4267:                     }
                   4268:                 } else {
                   4269:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4270:                 }
                   4271:             } else {
                   4272:                 return "Temporary file: $source missing";
                   4273:             }
                   4274:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4275: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4276: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4277: 	    return '/adm/notfound.html';
                   4278: 	}
1.570     albertel 4279: 	close(FH);
1.1051    raeburn  4280:         if ($resizewidth && $resizeheight) {
                   4281:             my $mm = new File::MMagic;
                   4282:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4283:             if ($mime_type =~ m{^image/}) {
                   4284: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4285:             }  
1.977     amueller 4286: 	}
1.258     www      4287:     }
1.1152    raeburn  4288:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4289:         if (ref($mimetype)) {
                   4290:             if ($$mimetype eq '') {
                   4291:                 my $mm = new File::MMagic;
                   4292:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4293:                 $$mimetype = $type;
                   4294:             }
                   4295:         }
                   4296:     }
1.1172.2.109  raeburn  4297:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4298:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4299:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4300:                                                        $allfiles,$codebase);
                   4301:             unless ($parse_result eq 'ok') {
                   4302:                 &logthis('Failed to parse '.$filepath.$file.
                   4303: 	   	         ' for embedded media: '.$parse_result); 
                   4304:             }
1.637     raeburn  4305:         }
1.1172.2.109  raeburn  4306:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4307:         my $format = $env{'form.scantron_format'};
                   4308:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4309:     }
1.860     raeburn  4310:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4311:         my $input = $filepath.'/'.$file;
                   4312:         my $output = $filepath.'/'.'tn-'.$file;
1.1172.2.146.  .13(raeb 4313:-23):         my $makethumb;
1.860     raeburn  4314:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.146.  .13(raeb 4315:-23):         if ($context eq 'toollogo') {
                   4316:-23):             my ($fullwidth,$fullheight) = &check_dimensions($input);
                   4317:-23):             if ($fullwidth ne '' && $fullheight ne '') {
                   4318:-23):                 if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
                   4319:-23):                     $makethumb = 1;
                   4320:-23):                 }
                   4321:-23):             }
                   4322:-23):         } else {
                   4323:-23):             $makethumb = 1;
                   4324:-23):         }
                   4325:-23):         if ($makethumb) {
                   4326:-23):             my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4327:-23):             system({$args[0]} @args);
                   4328:-23):             if (-e $filepath.'/'.'tn-'.$file) {
                   4329:-23):                 $fetchthumb  = 1;
                   4330:-23):             }
1.860     raeburn  4331:         }
                   4332:     }
1.858     raeburn  4333:  
1.259     www      4334: # Notify homeserver to grep it
                   4335: #
1.984     neumanie 4336:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4337:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4338:     if ($fetchresult eq 'ok') {
1.860     raeburn  4339:         if ($fetchthumb) {
                   4340:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4341:             if ($thumbresult ne 'ok') {
                   4342:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4343:                          $docuhome.': '.$thumbresult);
                   4344:             }
                   4345:         }
1.259     www      4346: #
1.258     www      4347: # Return the URL to it
1.494     albertel 4348:         return '/uploaded/'.$path.$file;
1.263     www      4349:     } else {
1.494     albertel 4350:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4351: 		 ': '.$fetchresult);
1.263     www      4352:         return '/adm/notfound.html';
1.858     raeburn  4353:     }
1.493     albertel 4354: }
                   4355: 
1.637     raeburn  4356: sub extract_embedded_items {
1.961     raeburn  4357:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4358:     my @state = ();
1.1164    raeburn  4359:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4360:     my %javafiles = (
                   4361:                       codebase => '',
                   4362:                       code => '',
                   4363:                       archive => ''
                   4364:                     );
                   4365:     my %mediafiles = (
                   4366:                       src => '',
                   4367:                       movie => '',
                   4368:                      );
1.648     raeburn  4369:     my $p;
                   4370:     if ($content) {
                   4371:         $p = HTML::LCParser->new($content);
                   4372:     } else {
1.961     raeburn  4373:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4374:     }
1.641     albertel 4375:     while (my $t=$p->get_token()) {
1.640     albertel 4376: 	if ($t->[0] eq 'S') {
                   4377: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4378: 	    push(@state, $tagname);
1.648     raeburn  4379:             if (lc($tagname) eq 'allow') {
                   4380:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4381:             }
1.640     albertel 4382: 	    if (lc($tagname) eq 'img') {
                   4383: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4384: 	    }
1.886     albertel 4385: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4386:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4387: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4388:                 }
1.886     albertel 4389: 	    }
1.645     raeburn  4390:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4391:                 my $src;
1.645     raeburn  4392:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4393:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4394:                 } else {
1.1164    raeburn  4395:                     if ($attr->{'src'} ne '') {
                   4396:                         $src = $attr->{'src'};
                   4397:                         &add_filetype($allfiles,$src,'src');
                   4398:                     }
                   4399:                 }
                   4400:                 my $text = $p->get_trimmed_text();
                   4401:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4402:                     my @swfargs = split(/,/,$1);
                   4403:                     foreach my $item (@swfargs) {
                   4404:                         $item =~ s/["']//g;
                   4405:                         $item =~ s/^\s+//;
                   4406:                         $item =~ s/\s+$//;
                   4407:                     }
                   4408:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4409:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4410:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4411:                         } else {
                   4412:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4413:                         }
                   4414:                     }
1.645     raeburn  4415:                 }
                   4416:             }
                   4417:             if (lc($tagname) eq 'link') {
                   4418:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4419:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4420:                 }
                   4421:             }
1.640     albertel 4422: 	    if (lc($tagname) eq 'object' ||
                   4423: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4424: 		foreach my $item (keys(%javafiles)) {
                   4425: 		    $javafiles{$item} = '';
                   4426: 		}
1.1164    raeburn  4427:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4428:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4429:                 }
1.640     albertel 4430: 	    }
                   4431: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4432: 		my $name = lc($attr->{'name'});
                   4433: 		foreach my $item (keys(%javafiles)) {
                   4434: 		    if ($name eq $item) {
                   4435: 			$javafiles{$item} = $attr->{'value'};
                   4436: 			last;
                   4437: 		    }
                   4438: 		}
1.1164    raeburn  4439:                 my $pathfrom;
1.640     albertel 4440: 		foreach my $item (keys(%mediafiles)) {
                   4441: 		    if ($name eq $item) {
1.1164    raeburn  4442:                         $pathfrom = $attr->{'value'};
                   4443:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4444: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4445: 			last;
                   4446: 		    }
                   4447: 		}
1.1164    raeburn  4448:                 if ($name eq 'flashvars') {
                   4449:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4450:                 }
                   4451:                 if ($pathfrom ne '') {
                   4452:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4453:                                          $pathfrom);
                   4454:                 }
1.640     albertel 4455: 	    }
                   4456: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4457: 		foreach my $item (keys(%javafiles)) {
                   4458: 		    if ($attr->{$item}) {
                   4459: 			$javafiles{$item} = $attr->{$item};
                   4460: 			last;
                   4461: 		    }
                   4462: 		}
                   4463: 		foreach my $item (keys(%mediafiles)) {
                   4464: 		    if ($attr->{$item}) {
                   4465: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4466: 			last;
                   4467: 		    }
                   4468: 		}
1.1164    raeburn  4469:                 if (lc($tagname) eq 'embed') {
                   4470:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4471:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4472:                                              $attr->{'src'});
                   4473:                     }
                   4474:                 }
1.640     albertel 4475: 	    }
1.1172.2.35  raeburn  4476:             if (lc($tagname) eq 'iframe') {
                   4477:                 my $src = $attr->{'src'} ;
                   4478:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4479:                     &add_filetype($allfiles,$src,'src');
                   4480:                 } elsif ($src =~ m{^/}) {
                   4481:                     if ($env{'request.course.id'}) {
                   4482:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4483:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4484:                         my $url = &hreflocation('',$fullpath);
                   4485:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4486:                             my $relpath = $1;
                   4487:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4488:                                 &add_filetype($allfiles,$1,'src');
                   4489:                             }
                   4490:                         }
                   4491:                     }
                   4492:                 }
                   4493:             }
1.1164    raeburn  4494:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4495:                 pop(@state);
1.1164    raeburn  4496:             }
1.640     albertel 4497: 	} elsif ($t->[0] eq 'E') {
                   4498: 	    my ($tagname) = ($t->[1]);
                   4499: 	    if ($javafiles{'codebase'} ne '') {
                   4500: 		$javafiles{'codebase'} .= '/';
                   4501: 	    }  
                   4502: 	    if (lc($tagname) eq 'applet' ||
                   4503: 		lc($tagname) eq 'object' ||
                   4504: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4505: 		) {
                   4506: 		foreach my $item (keys(%javafiles)) {
                   4507: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4508: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4509: 			&add_filetype($allfiles,$file,$item);
                   4510: 		    }
                   4511: 		}
                   4512: 	    } 
                   4513: 	    pop @state;
                   4514: 	}
                   4515:     }
1.1164    raeburn  4516:     foreach my $id (sort(keys(%flashvars))) {
                   4517:         if ($shockwave{$id} ne '') {
                   4518:             my @pairs = split(/\&/,$flashvars{$id});
                   4519:             foreach my $pair (@pairs) {
                   4520:                 my ($key,$value) = split(/\=/,$pair);
                   4521:                 if ($key eq 'thumb') {
                   4522:                     &add_filetype($allfiles,$value,$key);
                   4523:                 } elsif ($key eq 'content') {
                   4524:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4525:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4526:                     if ($ext ne '') {
                   4527:                         &add_filetype($allfiles,$path.$value,$ext);
                   4528:                     }
                   4529:                 }
                   4530:             }
                   4531:         }
                   4532:     }
1.637     raeburn  4533:     return 'ok';
                   4534: }
                   4535: 
1.639     albertel 4536: sub add_filetype {
                   4537:     my ($allfiles,$file,$type)=@_;
                   4538:     if (exists($allfiles->{$file})) {
                   4539: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4540: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4541: 	}
                   4542:     } else {
                   4543: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4544:     }
                   4545: }
                   4546: 
1.1164    raeburn  4547: sub embedded_dependency {
                   4548:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4549:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4550:         if (($identifier ne '') &&
                   4551:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4552:             ($pathfrom ne '')) {
                   4553:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4554:             foreach my $dep (@{$related->{$identifier}}) {
                   4555:                 &add_filetype($allfiles,$path.$dep,'object');
                   4556:             }
                   4557:         }
                   4558:     }
                   4559:     return;
                   4560: }
                   4561: 
1.1172.2.146.  .13(raeb 4562:-23): sub check_dimensions {
                   4563:-23):     my ($inputfile) = @_;
                   4564:-23):     my ($fullwidth,$fullheight);
                   4565:-23):     if (($inputfile =~ m|^[/\w.\-]+$|) && (-e $inputfile)) {
                   4566:-23):         my $mm = new File::MMagic;
                   4567:-23):         my $mime_type = $mm->checktype_filename($inputfile);
                   4568:-23):         if ($mime_type =~ m{^image/}) {
                   4569:-23):             if (open(PIPE,"identify $inputfile 2>&1 |")) {
                   4570:-23):                 my $imageinfo = <PIPE>;
                   4571:-23):                 if (!close(PIPE)) {
                   4572:-23):                     &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
                   4573:-23):                 }
                   4574:-23):                 chomp($imageinfo);
                   4575:-23):                 my ($fullsize) =
                   4576:-23):                     ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
                   4577:-23):                 if ($fullsize) {
                   4578:-23):                     ($fullwidth,$fullheight) = split(/x/,$fullsize);
                   4579:-23):                 }
                   4580:-23):             }
                   4581:-23):         }
                   4582:-23):     }
                   4583:-23):     return ($fullwidth,$fullheight);
                   4584:-23): }
                   4585:-23): 
1.1172.2.109  raeburn  4586: sub bubblesheet_converter {
                   4587:     my ($cdom,$fullpath,$config,$format) = @_;
                   4588:     if ((&domain($cdom) ne '') &&
                   4589:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4590:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4591:         my (%csvcols,%csvoptions);
                   4592:         if (ref($config->{'fields'}) eq 'HASH') {
                   4593:             %csvcols = %{$config->{'fields'}};
                   4594:         }
                   4595:         if (ref($config->{'options'}) eq 'HASH') {
                   4596:             %csvoptions = %{$config->{'options'}};
                   4597:         }
                   4598:         my %csvbynum = reverse(%csvcols);
                   4599:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4600:         if (keys(%scantronconf)) {
                   4601:             my %bynum = (
                   4602:                           $scantronconf{CODEstart} => 'CODEstart',
                   4603:                           $scantronconf{IDstart}   => 'IDstart',
                   4604:                           $scantronconf{PaperID}   => 'PaperID',
                   4605:                           $scantronconf{FirstName} => 'FirstName',
                   4606:                           $scantronconf{LastName}  => 'LastName',
                   4607:                           $scantronconf{Qstart}    => 'Qstart',
                   4608:                         );
                   4609:             my @ordered;
                   4610:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4611:                 push(@ordered,$bynum{$item});
                   4612:             }
                   4613:             my %mapstart = (
                   4614:                               CODEstart => 'CODE',
                   4615:                               IDstart   => 'ID',
                   4616:                               PaperID   => 'PaperID',
                   4617:                               FirstName => 'FirstName',
                   4618:                               LastName  => 'LastName',
                   4619:                               Qstart    => 'FirstQuestion',
                   4620:                            );
                   4621:             my %maplength = (
                   4622:                               CODEstart => 'CODElength',
                   4623:                               IDstart   => 'IDlength',
                   4624:                               PaperID   => 'PaperIDlength',
                   4625:                               FirstName => 'FirstNamelength',
                   4626:                               LastName  => 'LastNamelength',
                   4627:             );
                   4628:             if (open(my $fh,'<',$fullpath)) {
                   4629:                 my $output;
                   4630:                 my %lettdig = &letter_to_digits();
                   4631:                 my %diglett = reverse(%lettdig);
                   4632:                 my $numletts = scalar(keys(%lettdig));
                   4633:                 my $num = 0;
                   4634:                 while (my $line=<$fh>) {
                   4635:                     $num ++;
                   4636:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4637:                     $line =~ s{[\r\n]+$}{};
                   4638:                     my %found;
1.1172.2.143  raeburn  4639:                     my @values = split(/,/,$line,-1);
1.1172.2.109  raeburn  4640:                     my ($qstart,$record);
                   4641:                     for (my $i=0; $i<@values; $i++) {
                   4642:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4643:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4644:                             if ($values[$i] eq '') {
                   4645:                                 $values[$i] = $scantronconf{'Qoff'};
                   4646:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4647:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4648:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4649:                                 }
                   4650:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4651:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4652:                                     $values[$i] = $diglett{$values[$i]};
                   4653:                                 }
                   4654:                             } else {
                   4655:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4656:                                     my $digit;
                   4657:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4658:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4659:                                         if ($values[$i] eq 'J') {
                   4660:                                             $digit += $numletts;
                   4661:                                         }
                   4662:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4663:                                         $digit = $values[$i]-1;
                   4664:                                         if ($values[$i] eq '0') {
                   4665:                                             $digit += $numletts;
                   4666:                                         }
                   4667:                                     }
                   4668:                                     my $qval='';
                   4669:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4670:                                         if ($j == $digit) {
                   4671:                                             $qval .= $scantronconf{'Qon'};
                   4672:                                         } else {
                   4673:                                             $qval .= $scantronconf{'Qoff'};
                   4674:                                         }
                   4675:                                     }
                   4676:                                     $values[$i] = $qval;
                   4677:                                 }
                   4678:                             }
                   4679:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4680:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4681:                             }
                   4682:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4683:                             if ($numblank > 0) {
                   4684:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4685:                             }
                   4686:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4687:                                 $qstart = $i;
                   4688:                                 $found{$csvbynum{$i}} = $values[$i];
                   4689:                             } else {
                   4690:                                 $found{'FirstQuestion'} .= $values[$i];
                   4691:                             }
                   4692:                         } elsif (exists($csvbynum{$i})) {
                   4693:                             if ($csvoptions{'rem'}) {
                   4694:                                 $values[$i] =~ s/^\s+//;
                   4695:                             }
                   4696:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4697:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4698:                                     $values[$i] = '0'.$values[$i];
                   4699:                                 }
                   4700:                             }
                   4701:                             $found{$csvbynum{$i}} = $values[$i];
                   4702:                         }
                   4703:                     }
                   4704:                     foreach my $item (@ordered) {
                   4705:                         my $currlength = 1+length($record);
                   4706:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4707:                         if ($numspaces > 0) {
                   4708:                             $record .= (' ' x $numspaces);
                   4709:                         }
                   4710:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4711:                             unless ($item eq 'Qstart') {
                   4712:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4713:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4714:                                 }
                   4715:                             }
                   4716:                             $record .= $found{$mapstart{$item}};
                   4717:                         }
                   4718:                     }
                   4719:                     $output .= "$record\n";
                   4720:                 }
                   4721:                 close($fh);
                   4722:                 if ($output) {
                   4723:                     if (open(my $fh,'>',$fullpath)) {
                   4724:                         print $fh $output;
                   4725:                         close($fh);
                   4726:                     }
                   4727:                 }
                   4728:             }
                   4729:         }
                   4730:         return;
                   4731:     }
                   4732: }
                   4733: 
                   4734: sub letter_to_digits {
                   4735:     my %lettdig = (
                   4736:                     A => 1,
                   4737:                     B => 2,
                   4738:                     C => 3,
                   4739:                     D => 4,
                   4740:                     E => 5,
                   4741:                     F => 6,
                   4742:                     G => 7,
                   4743:                     H => 8,
                   4744:                     I => 9,
                   4745:                     J => 0,
                   4746:                   );
                   4747:     return %lettdig;
                   4748: }
                   4749: 
                   4750: sub get_scantron_config {
                   4751:     my ($which,$cdom) = @_;
                   4752:     my @lines = &get_scantronformat_file($cdom);
                   4753:     my %config;
                   4754:     #FIXME probably should move to XML it has already gotten a bit much now
                   4755:     foreach my $line (@lines) {
                   4756:         my ($name,$descrip)=split(/:/,$line);
                   4757:         if ($name ne $which ) { next; }
                   4758:         chomp($line);
                   4759:         my @config=split(/:/,$line);
                   4760:         $config{'name'}=$config[0];
                   4761:         $config{'description'}=$config[1];
                   4762:         $config{'CODElocation'}=$config[2];
                   4763:         $config{'CODEstart'}=$config[3];
                   4764:         $config{'CODElength'}=$config[4];
                   4765:         $config{'IDstart'}=$config[5];
                   4766:         $config{'IDlength'}=$config[6];
                   4767:         $config{'Qstart'}=$config[7];
                   4768:         $config{'Qlength'}=$config[8];
                   4769:         $config{'Qoff'}=$config[9];
                   4770:         $config{'Qon'}=$config[10];
                   4771:         $config{'PaperID'}=$config[11];
                   4772:         $config{'PaperIDlength'}=$config[12];
                   4773:         $config{'FirstName'}=$config[13];
                   4774:         $config{'FirstNamelength'}=$config[14];
                   4775:         $config{'LastName'}=$config[15];
                   4776:         $config{'LastNamelength'}=$config[16];
                   4777:         $config{'BubblesPerRow'}=$config[17];
                   4778:         last;
                   4779:     }
                   4780:     return %config;
                   4781: }
                   4782: 
                   4783: sub get_scantronformat_file {
                   4784:     my ($cdom) = @_;
                   4785:     if ($cdom eq '') {
                   4786:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4787:     }
                   4788:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4789:     my $gottab = 0;
                   4790:     my @lines;
                   4791:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4792:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4793:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4794:             if ($formatfile ne '-1') {
                   4795:                 @lines = split("\n",$formatfile,-1);
                   4796:                 $gottab = 1;
                   4797:             }
                   4798:         }
                   4799:     }
                   4800:     if (!$gottab) {
                   4801:         my $confname = $cdom.'-domainconfig';
                   4802:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4803:         my $formatfile = &getfile($default);
                   4804:         if ($formatfile ne '-1') {
                   4805:             @lines = split("\n",$formatfile,-1);
                   4806:             $gottab = 1;
                   4807:         }
                   4808:     }
                   4809:     if (!$gottab) {
                   4810:         my @domains = &current_machine_domains();
                   4811:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4812:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4813:                 @lines = <$fh>;
                   4814:                 close($fh);
                   4815:             }
                   4816:         } else {
                   4817:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4818:                 @lines = <$fh>;
                   4819:                 close($fh);
                   4820:             }
                   4821:         }
1.1172.2.146.  .8(raebu 4822:23):         chomp(@lines);
1.1172.2.109  raeburn  4823:     }
                   4824:     return @lines;
                   4825: }
                   4826: 
1.493     albertel 4827: sub removeuploadedurl {
1.984     neumanie 4828:     my ($url)=@_;	
                   4829:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4830:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4831: }
                   4832: 
                   4833: sub removeuserfile {
                   4834:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4835:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4836:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4837:     if ($result eq 'ok') {	
1.798     raeburn  4838:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4839:             my $metafile = $fname.'.meta';
                   4840:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4841: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4842:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4843:             my $sqlresult = 
1.823     albertel 4844:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4845:                                         'portfolio_metadata',$group,
                   4846:                                         'delete');
1.798     raeburn  4847:         }
                   4848:     }
                   4849:     return $result;
1.257     www      4850: }
1.15      www      4851: 
1.530     albertel 4852: sub mkdiruserfile {
                   4853:     my ($docuname,$docudom,$dir)=@_;
                   4854:     my $home=&homeserver($docuname,$docudom);
                   4855:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4856: }
                   4857: 
1.531     albertel 4858: sub renameuserfile {
                   4859:     my ($docuname,$docudom,$old,$new)=@_;
                   4860:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4861:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4862:                         &escape("$old").':'.&escape("$new"),$home);
                   4863:     if ($result eq 'ok') {
                   4864:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4865:             my $oldmeta = $old.'.meta';
                   4866:             my $newmeta = $new.'.meta';
                   4867:             my $metaresult = 
                   4868:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4869: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4870:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4871:             my $sqlresult = 
1.823     albertel 4872:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4873:                                         'portfolio_metadata',$group,
                   4874:                                         'delete');
1.798     raeburn  4875:         }
                   4876:     }
                   4877:     return $result;
1.531     albertel 4878: }
                   4879: 
1.14      www      4880: # ------------------------------------------------------------------------- Log
                   4881: 
                   4882: sub log {
                   4883:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4884:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4885: }
                   4886: 
                   4887: # ------------------------------------------------------------------ Course Log
1.352     www      4888: #
                   4889: # This routine flushes several buffers of non-mission-critical nature
                   4890: #
1.157     www      4891: 
                   4892: sub flushcourselogs {
1.352     www      4893:     &logthis('Flushing log buffers');
                   4894: #
                   4895: # course logs
                   4896: # This is a log of all transactions in a course, which can be used
                   4897: # for data mining purposes
                   4898: #
                   4899: # It also collects the courseid database, which lists last transaction
                   4900: # times and course titles for all courseids
                   4901: #
                   4902:     my %courseidbuffer=();
1.921     raeburn  4903:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4904:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4905: 		          &escape($courselogs{$crsid}),
                   4906: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4907: 	    delete $courselogs{$crsid};
                   4908:         } else {
                   4909:             &logthis('Failed to flush log buffer for '.$crsid);
                   4910:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4911:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4912:                         " exceeded maximum size, deleting.</font>");
                   4913:                delete $courselogs{$crsid};
                   4914:             }
1.352     www      4915:         }
1.920     raeburn  4916:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4917:             'description' => $coursedescrbuf{$crsid},
                   4918:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4919:             'type'        => $coursetypebuf{$crsid},
                   4920:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4921:         };
1.191     harris41 4922:     }
1.352     www      4923: #
                   4924: # Write course id database (reverse lookup) to homeserver of courses 
                   4925: # Is used in pickcourse
                   4926: #
1.840     albertel 4927:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4928:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4929:                                     $courseidbuffer{$crs_home},
                   4930:                                     $crs_home,'timeonly');
1.352     www      4931:     }
                   4932: #
                   4933: # File accesses
                   4934: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4935: #
1.449     matthew  4936:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4937:         if ($entry =~ /___count$/) {
                   4938:             my ($dom,$name);
1.807     albertel 4939:             ($dom,$name,undef)=
1.811     albertel 4940: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4941:             if (! defined($dom) || $dom eq '' || 
                   4942:                 ! defined($name) || $name eq '') {
1.620     albertel 4943:                 my $cid = $env{'request.course.id'};
1.1172.2.142  raeburn  4944: #
                   4945: # FIXME 11/29/2021
                   4946: # Typo in rev. 1.458 (2003/12/09)??
                   4947: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
                   4948: #
1.1172.2.146.  .13(raeb 4949:-23): # While these remain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
1.1172.2.142  raeburn  4950: # $dom and $name will always be null, so the &inc() call will default to storing this data
                   4951: # in a nohist_accesscount.db file for the user rather than the course.
                   4952: #
                   4953: # That said there is a lot of noise in the data being stored.
                   4954: # So counts for prtspool/  and adm/ etc. are recorded.
                   4955: #
                   4956: # A review of which items ending '___count' are written to %accesshash should likely be
                   4957: # made before deciding whether to set these to 'course.' instead of 'request.'
                   4958: #
                   4959: # Under the current scheme each user receives a nohist_accesscount.db file listing
                   4960: # accesses for things which are not published resources, regardless of course, and
                   4961: # there is not a nohist_accesscount.db file in a course, which might log accesses from
                   4962: # anyone in the course for things which are not published resources.
                   4963: #
                   4964: # For an author, nohist_accesscount.db ends up having records for other items
                   4965: # mixed up with the legitimate access counts for the author's published resources.
                   4966: #
1.620     albertel 4967:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4968:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4969:             }
1.450     matthew  4970:             my $value = $accesshash{$entry};
                   4971:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4972:             my %temphash=($url => $value);
1.449     matthew  4973:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4974:             if ($result eq 'ok') {
                   4975:                 delete $accesshash{$entry};
                   4976:             }
                   4977:         } else {
1.811     albertel 4978:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4979:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4980:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4981:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4982:                 delete $accesshash{$entry};
                   4983:             }
1.185     www      4984:         }
1.191     harris41 4985:     }
1.352     www      4986: #
                   4987: # Roles
                   4988: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4989: #
1.800     albertel 4990:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4991:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4992: 	    split(/\:/,$entry);
                   4993:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4994:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4995:                 $rudom,$runame) eq 'ok') {
                   4996: 	    delete $userrolehash{$entry};
                   4997:         }
                   4998:     }
1.662     raeburn  4999: #
1.1172.2.90  raeburn  5000: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  5001: #
                   5002:     my %domrolebuffer = ();
1.1000    raeburn  5003:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 5004:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  5005:         if ($domrolebuffer{$rudom}) {
                   5006:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   5007:                       '='.&escape($domainrolehash{$entry});
                   5008:         } else {
                   5009:             $domrolebuffer{$rudom}.=&escape($entry).
                   5010:                       '='.&escape($domainrolehash{$entry});
                   5011:         }
                   5012:         delete $domainrolehash{$entry};
                   5013:     }
                   5014:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  5015:         my %servers;
                   5016:         if (defined(&domain($dom,'primary'))) {
                   5017:             my $primary=&domain($dom,'primary');
                   5018:             my $hostname=&hostname($primary);
                   5019:             $servers{$primary} = $hostname;
                   5020:         } else {
                   5021:             %servers = &get_servers($dom,'library');
                   5022:         }
1.841     albertel 5023: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  5024: 	    if (&reply('domroleput:'.$dom.':'.
                   5025: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   5026: 	        last;
                   5027: 	    } else {
1.841     albertel 5028: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   5029: 	    }
1.662     raeburn  5030:         }
                   5031:     }
1.186     www      5032:     $dumpcount++;
1.157     www      5033: }
                   5034: 
                   5035: sub courselog {
                   5036:     my $what=shift;
1.158     www      5037:     $what=time.':'.$what;
1.620     albertel 5038:     unless ($env{'request.course.id'}) { return ''; }
                   5039:     $coursedombuf{$env{'request.course.id'}}=
                   5040:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5041:     $coursenumbuf{$env{'request.course.id'}}=
                   5042:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   5043:     $coursehombuf{$env{'request.course.id'}}=
                   5044:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   5045:     $coursedescrbuf{$env{'request.course.id'}}=
                   5046:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   5047:     $courseinstcodebuf{$env{'request.course.id'}}=
                   5048:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   5049:     $courseownerbuf{$env{'request.course.id'}}=
                   5050:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  5051:     $coursetypebuf{$env{'request.course.id'}}=
                   5052:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 5053:     if (defined $courselogs{$env{'request.course.id'}}) {
                   5054: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      5055:     } else {
1.620     albertel 5056: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      5057:     }
1.620     albertel 5058:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      5059: 	&flushcourselogs();
                   5060:     }
1.158     www      5061: }
                   5062: 
                   5063: sub courseacclog {
                   5064:     my $fnsymb=shift;
1.620     albertel 5065:     unless ($env{'request.course.id'}) { return ''; }
                   5066:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      5067:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      5068:         $what.=':POST';
1.583     matthew  5069:         # FIXME: Probably ought to escape things....
1.800     albertel 5070: 	foreach my $key (keys(%env)) {
                   5071:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  5072:                 my $formitem = $1;
                   5073:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   5074:                     $what.=':'.$formitem.'='.$env{$key};
                   5075:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131  raeburn  5076:                     if ($formitem eq 'proctorpassword') {
1.1172.2.132  raeburn  5077:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131  raeburn  5078:                     } else {
                   5079:                         $what.=':'.$formitem.'='.$env{$key};
                   5080:                     }
1.975     raeburn  5081:                 }
1.158     www      5082:             }
1.191     harris41 5083:         }
1.583     matthew  5084:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   5085:         # FIXME: We should not be depending on a form parameter that someone
                   5086:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 5087:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  5088:             $what.= ':POST';
                   5089:             # FIXME: Probably ought to escape things....
                   5090:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   5091:                                  'crsdiscuss') {
1.620     albertel 5092:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  5093:             }
                   5094:         }
1.158     www      5095:     }
                   5096:     &courselog($what);
1.149     www      5097: }
                   5098: 
1.185     www      5099: sub countacc {
                   5100:     my $url=&declutter(shift);
1.458     matthew  5101:     return if (! defined($url) || $url eq '');
1.620     albertel 5102:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      5103: #
                   5104: # Mark that this url was used in this course
                   5105: #
1.620     albertel 5106:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      5107: #
                   5108: # Increase the access count for this resource in this child process
                   5109: #
1.281     www      5110:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  5111:     $accesshash{$key}++;
1.185     www      5112: }
1.349     www      5113: 
1.361     www      5114: sub linklog {
                   5115:     my ($from,$to)=@_;
                   5116:     $from=&declutter($from);
                   5117:     $to=&declutter($to);
                   5118:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   5119:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   5120: }
1.1160    www      5121: 
                   5122: sub statslog {
                   5123:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   5124:     if ($users<2) { return; }
                   5125:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   5126:             'course'       => $env{'request.course.id'},
                   5127:             'sections'     => '"all"',
                   5128:             'num_students' => $users,
                   5129:             'part'         => $part,
                   5130:             'symb'         => $symb,
                   5131:             'mean_tries'   => $av_attempts,
                   5132:             'deg_of_diff'  => $degdiff});
                   5133:     foreach my $key (keys(%dynstore)) {
                   5134:         $accesshash{$key}=$dynstore{$key};
                   5135:     }
                   5136: }
1.361     www      5137:   
1.349     www      5138: sub userrolelog {
                   5139:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 5140:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      5141:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5142:        $userrolehash
                   5143:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      5144:                     =$tend.':'.$tstart;
1.662     raeburn  5145:     }
1.1169    droeschl 5146:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 5147:        $userrolehash
                   5148:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   5149:                     =$tend.':'.$tstart;
                   5150:     }
1.1172.2.90  raeburn  5151:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  5152:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5153:        $domainrolehash
                   5154:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   5155:                     = $tend.':'.$tstart;
                   5156:     }
1.351     www      5157: }
                   5158: 
1.957     raeburn  5159: sub courserolelog {
                   5160:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  5161:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   5162:         my $cdom = $1;
                   5163:         my $cnum = $2;
                   5164:         my $sec = $3;
                   5165:         my $namespace = 'rolelog';
                   5166:         my %storehash = (
                   5167:                            role    => $trole,
                   5168:                            start   => $tstart,
                   5169:                            end     => $tend,
                   5170:                            selfenroll => $selfenroll,
                   5171:                            context    => $context,
                   5172:                         );
                   5173:         if ($trole eq 'gr') {
                   5174:             $namespace = 'groupslog';
                   5175:             $storehash{'group'} = $sec;
                   5176:         } else {
                   5177:             $storehash{'section'} = $sec;
                   5178:         }
                   5179:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   5180:                    $domain,$cnum,$cdom);
                   5181:         if (($trole ne 'st') || ($sec ne '')) {
                   5182:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  5183:         }
                   5184:     }
                   5185:     return;
                   5186: }
                   5187: 
1.1172.2.9  raeburn  5188: sub domainrolelog {
                   5189:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5190:     if ($area =~ m{^/($match_domain)/$}) {
                   5191:         my $cdom = $1;
                   5192:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   5193:         my $namespace = 'rolelog';
                   5194:         my %storehash = (
                   5195:                            role    => $trole,
                   5196:                            start   => $tstart,
                   5197:                            end     => $tend,
                   5198:                            context => $context,
                   5199:                         );
                   5200:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5201:                    $domain,$domconfiguser,$cdom);
                   5202:     }
                   5203:     return;
                   5204: 
                   5205: }
                   5206: 
                   5207: sub coauthorrolelog {
                   5208:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5209:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5210:         my $audom = $1;
                   5211:         my $auname = $2;
                   5212:         my $namespace = 'rolelog';
                   5213:         my %storehash = (
                   5214:                            role    => $trole,
                   5215:                            start   => $tstart,
                   5216:                            end     => $tend,
                   5217:                            context => $context,
                   5218:                         );
                   5219:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5220:                    $domain,$auname,$audom);
                   5221:     }
                   5222:     return;
                   5223: }
                   5224: 
1.351     www      5225: sub get_course_adv_roles {
1.948     raeburn  5226:     my ($cid,$codes) = @_;
1.620     albertel 5227:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5228:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5229:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5230:     my %nothide=();
1.800     albertel 5231:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5232:         if ($user !~ /:/) {
                   5233: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5234:         } else {
                   5235:             $nothide{$user}=1;
                   5236:         }
1.470     www      5237:     }
1.1172.2.23  raeburn  5238:     my @possdoms = ($coursehash{'domain'});
                   5239:     if ($coursehash{'checkforpriv'}) {
                   5240:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5241:     }
1.351     www      5242:     my %returnhash=();
                   5243:     my %dumphash=
                   5244:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5245:     my $now=time;
1.997     raeburn  5246:     my %privileged;
1.1000    raeburn  5247:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5248: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5249:         if (($tstart) && ($tstart<0)) { next; }
                   5250:         if (($tend) && ($tend<$now)) { next; }
                   5251:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5252:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5253: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  5254:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5255:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5256: 	if ($role eq 'cr') { next; }
1.948     raeburn  5257:         if ($codes) {
                   5258:             if ($section) { $role .= ':'.$section; }
                   5259:             if ($returnhash{$role}) {
                   5260:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5261:             } else {
                   5262:                 $returnhash{$role}=$username.':'.$domain;
                   5263:             }
1.351     www      5264:         } else {
1.988     raeburn  5265:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5266:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5267:             if ($returnhash{$key}) {
                   5268: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5269:             } else {
                   5270:                 $returnhash{$key}=$username.':'.$domain;
                   5271:             }
1.351     www      5272:         }
1.948     raeburn  5273:     }
1.400     www      5274:     return %returnhash;
                   5275: }
                   5276: 
                   5277: sub get_my_roles {
1.937     raeburn  5278:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5279:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5280:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5281:     my (%dumphash,%nothide);
1.1086    raeburn  5282:     if ($context eq 'userroles') {
1.1166    raeburn  5283:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5284:     } else {
1.1172.2.23  raeburn  5285:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5286:         if ($hidepriv) {
                   5287:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5288:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5289:                 if ($user !~ /:/) {
                   5290:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5291:                 } else {
                   5292:                     $nothide{$user} = 1;
                   5293:                 }
                   5294:             }
                   5295:         }
1.858     raeburn  5296:     }
1.400     www      5297:     my %returnhash=();
                   5298:     my $now=time;
1.999     raeburn  5299:     my %privileged;
1.800     albertel 5300:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5301:         my ($role,$tend,$tstart);
                   5302:         if ($context eq 'userroles') {
1.1149    raeburn  5303:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5304: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5305:         } else {
                   5306:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5307:         }
1.400     www      5308:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5309:         my $status = 'active';
1.939     raeburn  5310:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5311:             $status = 'previous';
                   5312:         } 
                   5313:         if (($tstart) && ($now<$tstart)) {
                   5314:             $status = 'future';
                   5315:         }
                   5316:         if (ref($types) eq 'ARRAY') {
                   5317:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5318:                 next;
                   5319:             } 
                   5320:         } else {
                   5321:             if ($status ne 'active') {
                   5322:                 next;
                   5323:             }
                   5324:         }
1.867     raeburn  5325:         my ($rolecode,$username,$domain,$section,$area);
                   5326:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  5327:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5328:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5329:         } else {
                   5330:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5331:         }
1.832     raeburn  5332:         if (ref($roledoms) eq 'ARRAY') {
                   5333:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5334:                 next;
                   5335:             }
                   5336:         }
                   5337:         if (ref($roles) eq 'ARRAY') {
                   5338:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5339:                 if ($role =~ /^cr\//) {
                   5340:                     if (!grep(/^cr$/,@{$roles})) {
                   5341:                         next;
                   5342:                     }
1.1104    raeburn  5343:                 } elsif ($role =~ /^gr\//) {
                   5344:                     if (!grep(/^gr$/,@{$roles})) {
                   5345:                         next;
                   5346:                     }
1.922     raeburn  5347:                 } else {
                   5348:                     next;
                   5349:                 }
1.832     raeburn  5350:             }
1.867     raeburn  5351:         }
1.937     raeburn  5352:         if ($hidepriv) {
1.1172.2.23  raeburn  5353:             my @privroles = ('dc','su');
1.999     raeburn  5354:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  5355:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5356:             } else {
1.1172.2.23  raeburn  5357:                 my $possdoms = [$domain];
                   5358:                 if (ref($roledoms) eq 'ARRAY') {
                   5359:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5360:                 }
1.1172.2.23  raeburn  5361:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5362:                     if (!$nothide{$username.':'.$domain}) {
                   5363:                         next;
                   5364:                     }
                   5365:                 }
1.937     raeburn  5366:             }
                   5367:         }
1.933     raeburn  5368:         if ($withsec) {
                   5369:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5370:                 $tstart.':'.$tend;
                   5371:         } else {
                   5372:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5373:         }
1.832     raeburn  5374:     }
1.373     www      5375:     return %returnhash;
1.399     www      5376: }
                   5377: 
1.1172.2.89  raeburn  5378: sub get_all_adhocroles {
                   5379:     my ($dom) = @_;
                   5380:     my @roles_by_num = ();
                   5381:     my %domdefaults = &get_domain_defaults($dom);
                   5382:     my (%description,%access_in_dom,%access_info);
                   5383:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5384:         my $count = 0;
                   5385:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5386:         my %ordered;
                   5387:         foreach my $role (sort(keys(%domcurrent))) {
                   5388:             my ($order,$desc,$access_in_dom);
                   5389:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5390:                 $order = $domcurrent{$role}{'order'};
                   5391:                 $desc = $domcurrent{$role}{'desc'};
                   5392:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5393:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5394:             }
                   5395:             if ($order eq '') {
                   5396:                 $order = $count;
                   5397:             }
                   5398:             $ordered{$order} = $role;
                   5399:             if ($desc ne '') {
                   5400:                 $description{$role} = $desc;
                   5401:             } else {
                   5402:                 $description{$role}= $role;
                   5403:             }
                   5404:             $count++;
                   5405:         }
                   5406:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5407:             push(@roles_by_num,$ordered{$item});
                   5408:         }
                   5409:     }
                   5410:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5411: }
                   5412: 
                   5413: sub get_my_adhocroles {
                   5414:     my ($cid,$checkreg) = @_;
                   5415:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5416:     if ($env{'request.course.id'} eq $cid) {
                   5417:         $cdom = $env{'course.'.$cid.'.domain'};
                   5418:         $cnum = $env{'course.'.$cid.'.num'};
                   5419:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5420:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5421:         $cdom = $1;
                   5422:         $cnum = $2;
                   5423:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5424:                                      $cdom,$cnum);
                   5425:     }
                   5426:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5427:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5428:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5429:         if ($rosterhash{$user} ne '') {
                   5430:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5431:             return ([],{}) if ($type eq 'auto');
                   5432:         }
                   5433:     }
                   5434:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5435:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5436:             my $then=$env{'user.login.time'};
                   5437:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5438:             if (!$update) {
                   5439:                 $update = $then;
                   5440:             }
                   5441:             my @liveroles;
                   5442:             foreach my $role ('dh','da') {
                   5443:                 if ($env{"user.role.$role./$cdom/"}) {
                   5444:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5445:                     my $limit = $update;
                   5446:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5447:                         $limit = $then;
                   5448:                     }
                   5449:                     my $activerole = 1;
                   5450:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5451:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5452:                     if ($activerole) {
                   5453:                         push(@liveroles,$role);
                   5454:                     }
                   5455:                 }
                   5456:             }
                   5457:             if (@liveroles) {
1.1172.2.89  raeburn  5458:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5459:                     my ($accessref,$accessinfo,%access_in_dom);
                   5460:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5461:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5462:                         if (@{$roles_by_num}) {
                   5463:                             my %settings;
                   5464:                             if ($env{'request.course.id'} eq $cid) {
                   5465:                                 foreach my $envkey (keys(%env)) {
                   5466:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5467:                                         $settings{$1} = $env{$envkey};
                   5468:                                     }
                   5469:                                 }
                   5470:                             } else {
                   5471:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5472:                             }
                   5473:                             my %setincrs;
                   5474:                             if ($settings{'internal.adhocaccess'}) {
                   5475:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5476:                             }
                   5477:                             my @statuses;
                   5478:                             if ($env{'environment.inststatus'}) {
                   5479:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5480:                             }
                   5481:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5482:                             if (ref($accessref) eq 'HASH') {
                   5483:                                 %access_in_dom = %{$accessref};
                   5484:                             }
                   5485:                             foreach my $role (@{$roles_by_num}) {
                   5486:                                 my ($curraccess,@okstatus,@personnel);
                   5487:                                 if ($setincrs{$role}) {
                   5488:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5489:                                     if ($curraccess eq 'status') {
                   5490:                                         @okstatus = split(/\&/,$rest);
                   5491:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5492:                                         @personnel = split(/\&/,$rest);
                   5493:                                     }
                   5494:                                 } else {
                   5495:                                     $curraccess = $access_in_dom{$role};
                   5496:                                     if (ref($accessinfo) eq 'HASH') {
                   5497:                                         if ($curraccess eq 'status') {
                   5498:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5499:                                                 @okstatus = @{$accessinfo->{$role}};
                   5500:                                             }
                   5501:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5502:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5503:                                                 @personnel = @{$accessinfo->{$role}};
                   5504:                                             }
                   5505:                                         }
                   5506:                                     }
                   5507:                                 }
                   5508:                                 if ($curraccess eq 'none') {
                   5509:                                     next;
                   5510:                                 } elsif ($curraccess eq 'all') {
                   5511:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5512:                                 } elsif ($curraccess eq 'dh') {
                   5513:                                     if (grep(/^dh$/,@liveroles)) {
                   5514:                                         push(@possroles,$role);
                   5515:                                     } else {
                   5516:                                         next;
                   5517:                                     }
                   5518:                                 } elsif ($curraccess eq 'da') {
                   5519:                                     if (grep(/^da$/,@liveroles)) {
                   5520:                                         push(@possroles,$role);
                   5521:                                     } else {
                   5522:                                         next;
                   5523:                                     }
1.1172.2.89  raeburn  5524:                                 } elsif ($curraccess eq 'status') {
                   5525:                                     if (@okstatus) {
                   5526:                                         if (!@statuses) {
                   5527:                                             if (grep(/^default$/,@okstatus)) {
                   5528:                                                 push(@possroles,$role);
                   5529:                                             }
                   5530:                                         } else {
                   5531:                                             foreach my $status (@okstatus) {
                   5532:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5533:                                                     push(@possroles,$role);
                   5534:                                                     last;
                   5535:                                                 }
                   5536:                                             }
                   5537:                                         }
                   5538:                                     }
                   5539:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5540:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5541:                                         if ($curraccess eq 'exc') {
                   5542:                                             push(@possroles,$role);
                   5543:                                         }
                   5544:                                     } elsif ($curraccess eq 'inc') {
                   5545:                                         push(@possroles,$role);
                   5546:                                     }
                   5547:                                 }
                   5548:                             }
                   5549:                         }
                   5550:                     }
                   5551:                 }
                   5552:             }
                   5553:         }
                   5554:     }
                   5555:     unless (ref($description) eq 'HASH') {
                   5556:         if (ref($roles_by_num) eq 'ARRAY') {
                   5557:             my %desc;
                   5558:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5559:             $description = \%desc;
                   5560:         } else {
                   5561:             $description = {};
                   5562:         }
                   5563:     }
                   5564:     return (\@possroles,$description);
                   5565: }
                   5566: 
1.399     www      5567: # ----------------------------------------------------- Frontpage Announcements
                   5568: #
                   5569: #
                   5570: 
                   5571: sub postannounce {
                   5572:     my ($server,$text)=@_;
1.844     albertel 5573:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5574:     unless ($text=~/\w/) { $text=''; }
                   5575:     return &reply('setannounce:'.&escape($text),$server);
                   5576: }
                   5577: 
                   5578: sub getannounce {
1.448     albertel 5579: 
1.1172.2.96  raeburn  5580:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5581: 	my $announcement='';
1.800     albertel 5582: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5583: 	close($fh);
1.399     www      5584: 	if ($announcement=~/\w/) { 
                   5585: 	    return 
                   5586:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5587:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5588: 	} else {
                   5589: 	    return '';
                   5590: 	}
                   5591:     } else {
                   5592: 	return '';
                   5593:     }
1.351     www      5594: }
1.353     www      5595: 
                   5596: # ---------------------------------------------------------- Course ID routines
                   5597: # Deal with domain's nohist_courseid.db files
                   5598: #
                   5599: 
                   5600: sub courseidput {
1.921     raeburn  5601:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5602:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5603:     my $outcome;
                   5604:     if ($caller eq 'timeonly') {
                   5605:         my $cids = '';
                   5606:         foreach my $item (keys(%$storehash)) {
                   5607:             $cids.=&escape($item).'&';
                   5608:         }
                   5609:         $cids=~s/\&$//;
                   5610:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5611:                           $coursehome);       
                   5612:     } else {
                   5613:         my $items = '';
                   5614:         foreach my $item (keys(%$storehash)) {
                   5615:             $items.= &escape($item).'='.
                   5616:                      &freeze_escape($$storehash{$item}).'&';
                   5617:         }
                   5618:         $items=~s/\&$//;
                   5619:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5620:                           $coursehome);
1.918     raeburn  5621:     }
                   5622:     if ($outcome eq 'unknown_cmd') {
                   5623:         my $what;
                   5624:         foreach my $cid (keys(%$storehash)) {
                   5625:             $what .= &escape($cid).'=';
1.921     raeburn  5626:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5627:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5628:             }
                   5629:             $what =~ s/\:$/&/;
                   5630:         }
                   5631:         $what =~ s/\&$//;  
                   5632:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5633:     } else {
                   5634:         return $outcome;
                   5635:     }
1.353     www      5636: }
                   5637: 
                   5638: sub courseiddump {
1.921     raeburn  5639:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5640:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5641:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5642:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5643:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5644:     my $as_hash = 1;
                   5645:     my %returnhash;
                   5646:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5647:     my %libserv = &all_library();
                   5648:     foreach my $tryserver (keys(%libserv)) {
                   5649:         if ( (  $hostidflag == 1 
                   5650: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5651: 	     || (!defined($hostidflag)) ) {
                   5652: 
1.918     raeburn  5653: 	    if (($domfilter eq '') ||
                   5654: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5655:                 my $rep;
                   5656:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5657:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5658:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5659:                                 &escape($descfilter), &escape($instcodefilter),
                   5660:                                 &escape($ownerfilter), &escape($coursefilter),
                   5661:                                 &escape($typefilter), &escape($regexp_ok),
                   5662:                                 $as_hash, &escape($selfenrollonly),
                   5663:                                 &escape($catfilter), $showhidden, $caller,
                   5664:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5665:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5666:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5667:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5668:                 } else {
                   5669:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5670:                              $sincefilter.':'.&escape($descfilter).':'.
                   5671:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5672:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5673:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5674:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5675:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5676:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5677:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5678:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5679:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5680:                 }
                   5681: 
1.918     raeburn  5682:                 my @pairs=split(/\&/,$rep);
                   5683:                 foreach my $item (@pairs) {
                   5684:                     my ($key,$value)=split(/\=/,$item,2);
                   5685:                     $key = &unescape($key);
                   5686:                     next if ($key =~ /^error: 2 /);
                   5687:                     my $result = &thaw_unescape($value);
                   5688:                     if (ref($result) eq 'HASH') {
                   5689:                         $returnhash{$key}=$result;
                   5690:                     } else {
1.921     raeburn  5691:                         my @responses = split(/:/,$value);
                   5692:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5693:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5694:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5695:                         }
1.1008    raeburn  5696:                     }
1.353     www      5697:                 }
                   5698:             }
                   5699:         }
                   5700:     }
                   5701:     return %returnhash;
                   5702: }
                   5703: 
1.1055    raeburn  5704: sub courselastaccess {
                   5705:     my ($cdom,$cnum,$hostidref) = @_;
                   5706:     my %returnhash;
                   5707:     if ($cdom && $cnum) {
                   5708:         my $chome = &homeserver($cnum,$cdom);
                   5709:         if ($chome ne 'no_host') {
                   5710:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5711:             &extract_lastaccess(\%returnhash,$rep);
                   5712:         }
                   5713:     } else {
                   5714:         if (!$cdom) { $cdom=''; }
                   5715:         my %libserv = &all_library();
                   5716:         foreach my $tryserver (keys(%libserv)) {
                   5717:             if (ref($hostidref) eq 'ARRAY') {
                   5718:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5719:             } 
                   5720:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5721:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5722:                 &extract_lastaccess(\%returnhash,$rep);
                   5723:             }
                   5724:         }
                   5725:     }
                   5726:     return %returnhash;
                   5727: }
                   5728: 
                   5729: sub extract_lastaccess {
                   5730:     my ($returnhash,$rep) = @_;
                   5731:     if (ref($returnhash) eq 'HASH') {
                   5732:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5733:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5734:                  $rep eq '') {
                   5735:             my @pairs=split(/\&/,$rep);
                   5736:             foreach my $item (@pairs) {
                   5737:                 my ($key,$value)=split(/\=/,$item,2);
                   5738:                 $key = &unescape($key);
                   5739:                 next if ($key =~ /^error: 2 /);
                   5740:                 $returnhash->{$key} = &thaw_unescape($value);
                   5741:             }
                   5742:         }
                   5743:     }
                   5744:     return;
                   5745: }
                   5746: 
1.658     raeburn  5747: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5748: 
                   5749: sub dcmailput {
1.685     raeburn  5750:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5751:     my $status = &Apache::lonnet::critical(
1.740     www      5752:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5753:        &escape($message),$server);
1.662     raeburn  5754:     return $status;
                   5755: }
                   5756: 
1.658     raeburn  5757: sub dcmaildump {
                   5758:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5759:     my %returnhash=();
1.846     albertel 5760: 
                   5761:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5762:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5763:                                                          &escape($enddate).':';
                   5764: 	my @esc_senders=map { &escape($_)} @$senders;
                   5765: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5766: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5767:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5768:             if (($key) && ($value)) {
                   5769:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5770:             }
                   5771:         }
                   5772:     }
                   5773:     return %returnhash;
                   5774: }
1.662     raeburn  5775: # ---------------------------------------------------------- Domain roles
                   5776: 
                   5777: sub get_domain_roles {
                   5778:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5779:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5780:         $startdate = '.';
                   5781:     }
1.1018    raeburn  5782:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5783:         $enddate = '.';
                   5784:     }
1.922     raeburn  5785:     my $rolelist;
                   5786:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5787:         $rolelist = join('&',@{$roles});
1.922     raeburn  5788:     }
1.662     raeburn  5789:     my %personnel = ();
1.841     albertel 5790: 
                   5791:     my %servers = &get_servers($dom,'library');
                   5792:     foreach my $tryserver (keys(%servers)) {
                   5793: 	%{$personnel{$tryserver}}=();
                   5794: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5795: 					    &escape($startdate).':'.
                   5796: 					    &escape($enddate).':'.
                   5797: 					    &escape($rolelist), $tryserver))) {
                   5798: 	    my ($key,$value) = split(/\=/,$line,2);
                   5799: 	    if (($key) && ($value)) {
                   5800: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5801: 	    }
                   5802: 	}
1.662     raeburn  5803:     }
                   5804:     return %personnel;
                   5805: }
1.658     raeburn  5806: 
1.1172.2.89  raeburn  5807: sub get_active_domroles {
                   5808:     my ($dom,$roles) = @_;
                   5809:     return () unless (ref($roles) eq 'ARRAY');
                   5810:     my $now = time;
                   5811:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5812:     my %domroles;
                   5813:     foreach my $server (keys(%dompersonnel)) {
                   5814:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5815:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5816:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5817:         }
                   5818:     }
                   5819:     return %domroles;
                   5820: }
                   5821: 
1.1057    www      5822: # ----------------------------------------------------------- Interval timing 
1.149     www      5823: 
1.1153    www      5824: {
                   5825: # Caches needed for speedup of navmaps
                   5826: # We don't want to cache this for very long at all (5 seconds at most)
                   5827: # 
                   5828: # The user for whom we cache
                   5829: my $cachedkey='';
                   5830: # The cached times for this user
                   5831: my %cachedtimes=();
                   5832: # When this was last done
1.1172.2.66  raeburn  5833: my $cachedtime='';
1.1153    www      5834: 
                   5835: sub load_all_first_access {
1.1172.2.146.  .1(raebu 5836:22):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5837:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.146.  .1(raebu 5838:22):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5839:22):         (!$ignorecache)) {
1.1154    raeburn  5840:         return;
                   5841:     }
                   5842:     $cachedtime=time;
                   5843:     $cachedkey=$uname.':'.$udom;
                   5844:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5845: }
                   5846: 
1.504     albertel 5847: sub get_first_access {
1.1172.2.146.  .1(raebu 5848:22):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5849:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5850:     if ($argsymb) { $symb=$argsymb; }
                   5851:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5852:     if ($argmap) { $map = $argmap; }
1.926     albertel 5853:     if ($type eq 'course') {
                   5854: 	$res='course';
                   5855:     } elsif ($type eq 'map') {
1.588     albertel 5856: 	$res=&symbread($map);
                   5857:     } else {
                   5858: 	$res=$symb;
                   5859:     }
1.1172.2.146.  .1(raebu 5860:22):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5861:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5862: }
                   5863: 
                   5864: sub set_first_access {
1.1162    raeburn  5865:     my ($type,$interval)=@_;
1.790     albertel 5866:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5867:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5868:     if ($type eq 'course') {
                   5869: 	$res='course';
                   5870:     } elsif ($type eq 'map') {
1.588     albertel 5871: 	$res=&symbread($map);
                   5872:     } else {
                   5873: 	$res=$symb;
                   5874:     }
1.1153    www      5875:     $cachedkey='';
1.1162    raeburn  5876:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5877:     if ($firstaccess) {
                   5878:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5879:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5880:                  "in $courseid");
                   5881:         return 'already_set';
                   5882:     } else {
1.1162    raeburn  5883:         my $start = time;
                   5884: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5885:                           $udom,$uname);
                   5886:         if ($putres eq 'ok') {
                   5887:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5888:                  $udom,$uname); 
                   5889:             &appenv(
                   5890:                      {
                   5891:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5892:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5893:                      }
                   5894:                   );
1.1172.2.97  raeburn  5895:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5896:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5897:             }
1.1172.2.102  raeburn  5898:         } elsif ($putres ne 'refused') {
                   5899:             &logthis("Result: $putres when attempting to set first access time ".
                   5900:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5901:         }
                   5902:         return $putres;
1.505     albertel 5903:     }
                   5904:     return 'already_set';
1.504     albertel 5905: }
1.1153    www      5906: }
1.1172.2.32  raeburn  5907: 
                   5908: sub checkout {
                   5909:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5910:     my $now=time;
                   5911:     my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134  raeburn  5912:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5913:     my $infostr=&escape(
                   5914:                  'CHECKOUTTOKEN&'.
                   5915:                  $tuname.'&'.
                   5916:                  $tudom.'&'.
                   5917:                  $tcrsid.'&'.
                   5918:                  $symb.'&'.
1.1172.2.134  raeburn  5919:                  $now.'&'.$ip);
1.1172.2.32  raeburn  5920:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5921:     if ($token=~/^error\:/) {
                   5922:         &logthis("<font color=\"blue\">WARNING: ".
                   5923:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5924:                  "</font>");
                   5925:         return '';
                   5926:     }
                   5927: 
                   5928:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5929:     $token=~tr/a-z/A-Z/;
                   5930: 
                   5931:     my %infohash=('resource.0.outtoken' => $token,
                   5932:                   'resource.0.checkouttime' => $now,
1.1172.2.134  raeburn  5933:                   'resource.0.outremote' => $ip);
1.1172.2.32  raeburn  5934: 
                   5935:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5936:        return '';
                   5937:     } else {
                   5938:         &logthis("<font color=\"blue\">WARNING: ".
                   5939:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5940:                  "</font>");
                   5941:     }
                   5942: 
                   5943:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5944:                          &escape('Checkout '.$infostr.' - '.
                   5945:                                                  $token)) ne 'ok') {
                   5946:         return '';
                   5947:     } else {
                   5948:         &logthis("<font color=\"blue\">WARNING: ".
                   5949:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5950:                  "</font>");
                   5951:     }
                   5952:     return $token;
                   5953: }
                   5954: 
                   5955: # ------------------------------------------------------------ Check in an item
                   5956: 
                   5957: sub checkin {
                   5958:     my $token=shift;
                   5959:     my $now=time;
                   5960:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5961:     $lonhost=~tr/A-Z/a-z/;
                   5962:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5963:     $dtoken=~s/\W/\_/g;
1.1172.2.134  raeburn  5964:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5965:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5966:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5967: 
                   5968:     unless (($tuname) && ($tudom)) {
                   5969:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5970:         return '';
                   5971:     }
                   5972: 
                   5973:     unless (&allowed('mgr',$tcrsid)) {
                   5974:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5975:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5976:         return '';
                   5977:     }
                   5978: 
                   5979:     my %infohash=('resource.0.intoken' => $token,
                   5980:                   'resource.0.checkintime' => $now,
1.1172.2.134  raeburn  5981:                   'resource.0.inremote' => $ip);
1.1172.2.32  raeburn  5982: 
                   5983:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5984:        return '';
                   5985:     }
                   5986: 
                   5987:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5988:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5989:         return '';
                   5990:     }
                   5991: 
                   5992:     return ($symb,$tuname,$tudom,$tcrsid);
                   5993: }
                   5994: 
1.110     www      5995: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5996: 
                   5997: sub expirespread {
                   5998:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5999:     my $cid=$env{'request.course.id'}; 
1.110     www      6000:     if ($cid) {
                   6001:        my $now=time;
                   6002:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 6003:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   6004:                             $env{'course.'.$cid.'.num'}.
1.110     www      6005: 	        	    ':nohist_expirationdates:'.
                   6006:                             &escape($key).'='.$now,
1.620     albertel 6007:                             $env{'course.'.$cid.'.home'})
1.110     www      6008:     }
                   6009:     return 'ok';
1.14      www      6010: }
                   6011: 
1.109     www      6012: # ----------------------------------------------------- Devalidate Spreadsheets
                   6013: 
                   6014: sub devalidate {
1.325     www      6015:     my ($symb,$uname,$udom)=@_;
1.620     albertel 6016:     my $cid=$env{'request.course.id'}; 
1.109     www      6017:     if ($cid) {
1.391     matthew  6018:         # delete the stored spreadsheets for
                   6019:         # - the student level sheet of this user in course's homespace
                   6020:         # - the assessment level sheet for this resource 
                   6021:         #   for this user in user's homespace
1.553     albertel 6022: 	# - current conditional state info
1.325     www      6023: 	my $key=$uname.':'.$udom.':';
1.109     www      6024:         my $status=
1.299     matthew  6025: 	    &del('nohist_calculatedsheets',
1.391     matthew  6026: 		 [$key.'studentcalc:'],
1.620     albertel 6027: 		 $env{'course.'.$cid.'.domain'},
                   6028: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 6029: 		.' '.
                   6030: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  6031: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      6032:         unless ($status eq 'ok ok') {
                   6033:            &logthis('Could not devalidate spreadsheet '.
1.325     www      6034:                     $uname.' at '.$udom.' for '.
1.109     www      6035: 		    $symb.': '.$status);
1.133     albertel 6036:         }
1.553     albertel 6037: 	&delenv('user.state.'.$cid);
1.109     www      6038:     }
                   6039: }
                   6040: 
1.265     albertel 6041: sub get_scalar {
                   6042:     my ($string,$end) = @_;
                   6043:     my $value;
                   6044:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   6045: 	$value = $1;
                   6046:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   6047: 	$value = $1;
                   6048:     }
                   6049:     return &unescape($value);
                   6050: }
                   6051: 
                   6052: sub array2str {
                   6053:   my (@array) = @_;
                   6054:   my $result=&arrayref2str(\@array);
                   6055:   $result=~s/^__ARRAY_REF__//;
                   6056:   $result=~s/__END_ARRAY_REF__$//;
                   6057:   return $result;
                   6058: }
                   6059: 
1.204     albertel 6060: sub arrayref2str {
                   6061:   my ($arrayref) = @_;
1.265     albertel 6062:   my $result='__ARRAY_REF__';
1.204     albertel 6063:   foreach my $elem (@$arrayref) {
1.265     albertel 6064:     if(ref($elem) eq 'ARRAY') {
                   6065:       $result.=&arrayref2str($elem).'&';
                   6066:     } elsif(ref($elem) eq 'HASH') {
                   6067:       $result.=&hashref2str($elem).'&';
                   6068:     } elsif(ref($elem)) {
                   6069:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 6070:     } else {
                   6071:       $result.=&escape($elem).'&';
                   6072:     }
                   6073:   }
                   6074:   $result=~s/\&$//;
1.265     albertel 6075:   $result .= '__END_ARRAY_REF__';
1.204     albertel 6076:   return $result;
                   6077: }
                   6078: 
1.168     albertel 6079: sub hash2str {
1.204     albertel 6080:   my (%hash) = @_;
                   6081:   my $result=&hashref2str(\%hash);
1.265     albertel 6082:   $result=~s/^__HASH_REF__//;
                   6083:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 6084:   return $result;
                   6085: }
                   6086: 
                   6087: sub hashref2str {
                   6088:   my ($hashref)=@_;
1.265     albertel 6089:   my $result='__HASH_REF__';
1.800     albertel 6090:   foreach my $key (sort(keys(%$hashref))) {
                   6091:     if (ref($key) eq 'ARRAY') {
                   6092:       $result.=&arrayref2str($key).'=';
                   6093:     } elsif (ref($key) eq 'HASH') {
                   6094:       $result.=&hashref2str($key).'=';
                   6095:     } elsif (ref($key)) {
1.265     albertel 6096:       $result.='=';
1.800     albertel 6097:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 6098:     } else {
1.1132    raeburn  6099: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 6100:     }
                   6101: 
1.800     albertel 6102:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   6103:       $result.=&arrayref2str($hashref->{$key}).'&';
                   6104:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   6105:       $result.=&hashref2str($hashref->{$key}).'&';
                   6106:     } elsif(ref($hashref->{$key})) {
1.265     albertel 6107:        $result.='&';
1.800     albertel 6108:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 6109:     } else {
1.800     albertel 6110:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 6111:     }
                   6112:   }
1.168     albertel 6113:   $result=~s/\&$//;
1.265     albertel 6114:   $result .= '__END_HASH_REF__';
1.168     albertel 6115:   return $result;
                   6116: }
                   6117: 
                   6118: sub str2hash {
1.265     albertel 6119:     my ($string)=@_;
                   6120:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   6121:     return %$hash;
                   6122: }
                   6123: 
                   6124: sub str2hashref {
1.168     albertel 6125:   my ($string) = @_;
1.265     albertel 6126: 
                   6127:   my %hash;
                   6128: 
                   6129:   if($string !~ /^__HASH_REF__/) {
                   6130:       if (! ($string eq '' || !defined($string))) {
                   6131: 	  $hash{'error'}='Not hash reference';
                   6132:       }
                   6133:       return (\%hash, $string);
                   6134:   }
                   6135: 
                   6136:   $string =~ s/^__HASH_REF__//;
                   6137: 
                   6138:   while($string !~ /^__END_HASH_REF__/) {
                   6139:       #key
                   6140:       my $key='';
                   6141:       if($string =~ /^__HASH_REF__/) {
                   6142:           ($key, $string)=&str2hashref($string);
                   6143:           if(defined($key->{'error'})) {
                   6144:               $hash{'error'}='Bad data';
                   6145:               return (\%hash, $string);
                   6146:           }
                   6147:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6148:           ($key, $string)=&str2arrayref($string);
                   6149:           if($key->[0] eq 'Array reference error') {
                   6150:               $hash{'error'}='Bad data';
                   6151:               return (\%hash, $string);
                   6152:           }
                   6153:       } else {
                   6154:           $string =~ s/^(.*?)=//;
1.267     albertel 6155: 	  $key=&unescape($1);
1.265     albertel 6156:       }
                   6157:       $string =~ s/^=//;
                   6158: 
                   6159:       #value
                   6160:       my $value='';
                   6161:       if($string =~ /^__HASH_REF__/) {
                   6162:           ($value, $string)=&str2hashref($string);
                   6163:           if(defined($value->{'error'})) {
                   6164:               $hash{'error'}='Bad data';
                   6165:               return (\%hash, $string);
                   6166:           }
                   6167:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6168:           ($value, $string)=&str2arrayref($string);
                   6169:           if($value->[0] eq 'Array reference error') {
                   6170:               $hash{'error'}='Bad data';
                   6171:               return (\%hash, $string);
                   6172:           }
                   6173:       } else {
                   6174: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   6175:       }
                   6176:       $string =~ s/^&//;
                   6177: 
                   6178:       $hash{$key}=$value;
1.204     albertel 6179:   }
1.265     albertel 6180: 
                   6181:   $string =~ s/^__END_HASH_REF__//;
                   6182: 
                   6183:   return (\%hash, $string);
1.204     albertel 6184: }
                   6185: 
                   6186: sub str2array {
1.265     albertel 6187:     my ($string)=@_;
                   6188:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   6189:     return @$array;
                   6190: }
                   6191: 
                   6192: sub str2arrayref {
1.204     albertel 6193:   my ($string) = @_;
1.265     albertel 6194:   my @array;
                   6195: 
                   6196:   if($string !~ /^__ARRAY_REF__/) {
                   6197:       if (! ($string eq '' || !defined($string))) {
                   6198: 	  $array[0]='Array reference error';
                   6199:       }
                   6200:       return (\@array, $string);
                   6201:   }
                   6202: 
                   6203:   $string =~ s/^__ARRAY_REF__//;
                   6204: 
                   6205:   while($string !~ /^__END_ARRAY_REF__/) {
                   6206:       my $value='';
                   6207:       if($string =~ /^__HASH_REF__/) {
                   6208:           ($value, $string)=&str2hashref($string);
                   6209:           if(defined($value->{'error'})) {
                   6210:               $array[0] ='Array reference error';
                   6211:               return (\@array, $string);
                   6212:           }
                   6213:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6214:           ($value, $string)=&str2arrayref($string);
                   6215:           if($value->[0] eq 'Array reference error') {
                   6216:               $array[0] ='Array reference error';
                   6217:               return (\@array, $string);
                   6218:           }
                   6219:       } else {
                   6220: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   6221:       }
                   6222:       $string =~ s/^&//;
                   6223: 
                   6224:       push(@array, $value);
1.191     harris41 6225:   }
1.265     albertel 6226: 
                   6227:   $string =~ s/^__END_ARRAY_REF__//;
                   6228: 
                   6229:   return (\@array, $string);
1.168     albertel 6230: }
                   6231: 
1.167     albertel 6232: # -------------------------------------------------------------------Temp Store
                   6233: 
1.168     albertel 6234: sub tmpreset {
                   6235:   my ($symb,$namespace,$domain,$stuname) = @_;
                   6236:   if (!$symb) {
                   6237:     $symb=&symbread();
1.620     albertel 6238:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6239:   }
                   6240:   $symb=escape($symb);
                   6241: 
1.620     albertel 6242:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 6243:   $namespace=~s/\//\_/g;
                   6244:   $namespace=~s/\W//g;
                   6245: 
1.620     albertel 6246:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6247:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6248:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6249:       $stuname=&get_requestor_ip();
1.591     albertel 6250:   }
1.1117    foxr     6251:   my $path=LONCAPA::tempdir();
1.168     albertel 6252:   my %hash;
                   6253:   if (tie(%hash,'GDBM_File',
                   6254: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6255: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6256:     foreach my $key (keys(%hash)) {
1.180     albertel 6257:       if ($key=~ /:$symb/) {
1.168     albertel 6258: 	delete($hash{$key});
                   6259:       }
                   6260:     }
                   6261:   }
                   6262: }
                   6263: 
1.167     albertel 6264: sub tmpstore {
1.168     albertel 6265:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6266: 
                   6267:   if (!$symb) {
                   6268:     $symb=&symbread();
1.620     albertel 6269:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6270:   }
                   6271:   $symb=escape($symb);
                   6272: 
                   6273:   if (!$namespace) {
                   6274:     # I don't think we would ever want to store this for a course.
                   6275:     # it seems this will only be used if we don't have a course.
1.620     albertel 6276:     #$namespace=$env{'request.course.id'};
1.168     albertel 6277:     #if (!$namespace) {
1.620     albertel 6278:       $namespace=$env{'request.state'};
1.168     albertel 6279:     #}
                   6280:   }
                   6281:   $namespace=~s/\//\_/g;
                   6282:   $namespace=~s/\W//g;
1.620     albertel 6283:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6284:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6285:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6286:       $stuname=&get_requestor_ip();
1.591     albertel 6287:   }
1.168     albertel 6288:   my $now=time;
                   6289:   my %hash;
1.1117    foxr     6290:   my $path=LONCAPA::tempdir();
1.168     albertel 6291:   if (tie(%hash,'GDBM_File',
                   6292: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6293: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6294:     $hash{"version:$symb"}++;
                   6295:     my $version=$hash{"version:$symb"};
                   6296:     my $allkeys=''; 
                   6297:     foreach my $key (keys(%$storehash)) {
                   6298:       $allkeys.=$key.':';
1.591     albertel 6299:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6300:     }
                   6301:     $hash{"$version:$symb:timestamp"}=$now;
                   6302:     $allkeys.='timestamp';
                   6303:     $hash{"$version:keys:$symb"}=$allkeys;
                   6304:     if (untie(%hash)) {
                   6305:       return 'ok';
                   6306:     } else {
                   6307:       return "error:$!";
                   6308:     }
                   6309:   } else {
                   6310:     return "error:$!";
                   6311:   }
                   6312: }
1.167     albertel 6313: 
1.168     albertel 6314: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6315: 
1.168     albertel 6316: sub tmprestore {
                   6317:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6318: 
1.168     albertel 6319:   if (!$symb) {
                   6320:     $symb=&symbread();
1.620     albertel 6321:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6322:   }
                   6323:   $symb=escape($symb);
                   6324: 
1.620     albertel 6325:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6326: 
1.620     albertel 6327:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6328:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6329:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6330:       $stuname=&get_requestor_ip();
1.591     albertel 6331:   }
1.168     albertel 6332:   my %returnhash;
                   6333:   $namespace=~s/\//\_/g;
                   6334:   $namespace=~s/\W//g;
                   6335:   my %hash;
1.1117    foxr     6336:   my $path=LONCAPA::tempdir();
1.168     albertel 6337:   if (tie(%hash,'GDBM_File',
                   6338: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6339: 	  &GDBM_READER(),0640)) {
1.168     albertel 6340:     my $version=$hash{"version:$symb"};
                   6341:     $returnhash{'version'}=$version;
                   6342:     my $scope;
                   6343:     for ($scope=1;$scope<=$version;$scope++) {
                   6344:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6345:       my @keys=split(/:/,$vkeys);
                   6346:       my $key;
                   6347:       $returnhash{"$scope:keys"}=$vkeys;
                   6348:       foreach $key (@keys) {
1.591     albertel 6349: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6350: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6351:       }
                   6352:     }
1.168     albertel 6353:     if (!(untie(%hash))) {
                   6354:       return "error:$!";
                   6355:     }
                   6356:   } else {
                   6357:     return "error:$!";
                   6358:   }
                   6359:   return %returnhash;
1.167     albertel 6360: }
                   6361: 
1.9       www      6362: # ----------------------------------------------------------------------- Store
                   6363: 
                   6364: sub store {
1.1172.2.64  raeburn  6365:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6366:     my $home='';
                   6367: 
1.168     albertel 6368:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6369: 
1.213     www      6370:     $symb=&symbclean($symb);
1.122     albertel 6371:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6372: 
1.620     albertel 6373:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6374:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6375: 
                   6376:     &devalidate($symb,$stuname,$domain);
1.109     www      6377: 
                   6378:     $symb=escape($symb);
1.187     www      6379:     if (!$namespace) { 
1.620     albertel 6380:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6381:           return ''; 
                   6382:        } 
                   6383:     }
1.620     albertel 6384:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6385: 
1.1172.2.138  raeburn  6386:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6387:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6388: 
1.12      www      6389:     my $namevalue='';
1.800     albertel 6390:     foreach my $key (keys(%$storehash)) {
                   6391:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6392:     }
1.12      www      6393:     $namevalue=~s/\&$//;
1.187     www      6394:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6395:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6396: }
                   6397: 
1.47      www      6398: # -------------------------------------------------------------- Critical Store
                   6399: 
                   6400: sub cstore {
1.1172.2.64  raeburn  6401:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6402:     my $home='';
                   6403: 
1.168     albertel 6404:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6405: 
1.213     www      6406:     $symb=&symbclean($symb);
1.122     albertel 6407:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6408: 
1.620     albertel 6409:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6410:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6411: 
                   6412:     &devalidate($symb,$stuname,$domain);
1.109     www      6413: 
                   6414:     $symb=escape($symb);
1.187     www      6415:     if (!$namespace) { 
1.620     albertel 6416:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6417:           return ''; 
                   6418:        } 
                   6419:     }
1.620     albertel 6420:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6421: 
1.1172.2.138  raeburn  6422:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6423:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6424: 
1.47      www      6425:     my $namevalue='';
1.800     albertel 6426:     foreach my $key (keys(%$storehash)) {
                   6427:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6428:     }
1.47      www      6429:     $namevalue=~s/\&$//;
1.187     www      6430:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6431:     return critical
1.1172.2.64  raeburn  6432:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6433: }
                   6434: 
1.9       www      6435: # --------------------------------------------------------------------- Restore
                   6436: 
                   6437: sub restore {
1.124     www      6438:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6439:     my $home='';
                   6440: 
1.168     albertel 6441:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6442: 
1.122     albertel 6443:     if (!$symb) {
1.1172.2.26  raeburn  6444:         return if ($namespace eq 'courserequests');
                   6445:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6446:     } else {
1.1172.2.26  raeburn  6447:         unless ($namespace eq 'courserequests') {
                   6448:             $symb=&escape(&symbclean($symb));
                   6449:         }
1.122     albertel 6450:     }
1.188     www      6451:     if (!$namespace) { 
1.620     albertel 6452:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6453:           return ''; 
                   6454:        } 
                   6455:     }
1.620     albertel 6456:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6457:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6458:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6459:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6460: 
1.12      www      6461:     my %returnhash=();
1.800     albertel 6462:     foreach my $line (split(/\&/,$answer)) {
                   6463: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6464:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6465:     }
1.75      www      6466:     my $version;
                   6467:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6468:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6469:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6470:        }
1.75      www      6471:     }
1.13      www      6472:     return %returnhash;
1.34      www      6473: }
                   6474: 
                   6475: # ---------------------------------------------------------- Course Description
1.1118    foxr     6476: #
                   6477: #  
1.34      www      6478: 
                   6479: sub coursedescription {
1.731     albertel 6480:     my ($courseid,$args)=@_;
1.34      www      6481:     $courseid=~s/^\///;
1.49      www      6482:     $courseid=~s/\_/\//g;
1.34      www      6483:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6484:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6485:     my $normalid=$cdomain.'_'.$cnum;
                   6486:     # need to always cache even if we get errors otherwise we keep 
                   6487:     # trying and trying and trying to get the course description.
                   6488:     my %envhash=();
                   6489:     my %returnhash=();
1.731     albertel 6490:     
                   6491:     my $expiretime=600;
                   6492:     if ($env{'request.course.id'} eq $normalid) {
                   6493: 	$expiretime=120;
                   6494:     }
                   6495: 
                   6496:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6497:     if (!$args->{'freshen_cache'}
                   6498: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6499: 	foreach my $key (keys(%env)) {
                   6500: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6501: 	    my ($setting) = $1;
                   6502: 	    $returnhash{$setting} = $env{$key};
                   6503: 	}
                   6504: 	return %returnhash;
                   6505:     }
                   6506: 
1.1118    foxr     6507:     # get the data again
                   6508: 
1.731     albertel 6509:     if (!$args->{'one_time'}) {
                   6510: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6511:     }
1.811     albertel 6512: 
1.34      www      6513:     if ($chome ne 'no_host') {
1.302     albertel 6514:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6515:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6516: 	   my $username = $env{'user.name'}; # Defult username
                   6517: 	   if(defined $args->{'user'}) {
                   6518: 	       $username = $args->{'user'};
                   6519: 	   }
1.129     albertel 6520:            $returnhash{'home'}= $chome;
                   6521: 	   $returnhash{'domain'} = $cdomain;
                   6522: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6523:            if (!defined($returnhash{'type'})) {
                   6524:                $returnhash{'type'} = 'Course';
                   6525:            }
1.130     albertel 6526:            while (my ($name,$value) = each %returnhash) {
1.53      www      6527:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6528:            }
1.270     www      6529:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6530:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6531: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6532:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6533:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6534:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6535:        }
                   6536:     }
1.731     albertel 6537:     if (!$args->{'one_time'}) {
1.949     raeburn  6538: 	&appenv(\%envhash);
1.731     albertel 6539:     }
1.302     albertel 6540:     return %returnhash;
1.461     www      6541: }
                   6542: 
1.1080    raeburn  6543: sub update_released_required {
                   6544:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6545:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6546:         $cid = $env{'request.course.id'};
                   6547:         $cdom = $env{'course.'.$cid.'.domain'};
                   6548:         $cnum = $env{'course.'.$cid.'.num'};
                   6549:         $chome = $env{'course.'.$cid.'.home'};
                   6550:     }
                   6551:     if ($needsrelease) {
                   6552:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6553:         my $needsupdate;
                   6554:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6555:             $needsupdate = 1;
                   6556:         } else {
                   6557:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6558:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6559:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6560:                 $needsupdate = 1;
                   6561:             }
                   6562:         }
                   6563:         if ($needsupdate) {
                   6564:             my %needshash = (
                   6565:                              'internal.releaserequired' => $needsrelease,
                   6566:                             );
                   6567:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6568:             if ($putresult eq 'ok') {
                   6569:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6570:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6571:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6572:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6573:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6574:                 }
                   6575:             }
                   6576:         }
                   6577:     }
                   6578:     return;
                   6579: }
                   6580: 
1.461     www      6581: # -------------------------------------------------See if a user is privileged
                   6582: 
                   6583: sub privileged {
1.1172.2.23  raeburn  6584:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6585:     my $now = time;
1.1172.2.23  raeburn  6586:     my $roles;
                   6587:     if (ref($possroles) eq 'ARRAY') {
                   6588:         $roles = $possroles;
                   6589:     } else {
                   6590:         $roles = ['dc','su'];
                   6591:     }
                   6592:     if (ref($possdomains) eq 'ARRAY') {
                   6593:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6594:         foreach my $dom (@{$possdomains}) {
                   6595:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6596:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6597:                 foreach my $role (@{$roles}) {
                   6598:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6599:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6600:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6601:                             return 1 unless (($end && $end < $now) ||
                   6602:                                              ($start && $start > $now));
                   6603:                         }
                   6604:                     }
                   6605:                 }
                   6606:             }
                   6607:         }
                   6608:     } else {
                   6609:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6610:         my $now = time;
1.1170    droeschl 6611: 
1.1172.2.58  raeburn  6612:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6613:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6614:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6615:                 return 1 unless ($tend && $tend < $now)
                   6616:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6617:             }
1.1172.2.23  raeburn  6618:         }
                   6619:     }
1.461     www      6620:     return 0;
1.9       www      6621: }
1.1       albertel 6622: 
1.1172.2.23  raeburn  6623: sub privileged_by_domain {
                   6624:     my ($domains,$roles) = @_;
                   6625:     my %privileged = ();
                   6626:     my $cachetime = 60*60*24;
                   6627:     my $now = time;
                   6628:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6629:         return %privileged;
                   6630:     }
                   6631:     foreach my $dom (@{$domains}) {
                   6632:         next if (ref($privileged{$dom}) eq 'HASH');
                   6633:         my $needroles;
                   6634:         foreach my $role (@{$roles}) {
                   6635:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6636:             if (defined($cached)) {
                   6637:                 if (ref($result) eq 'HASH') {
                   6638:                     $privileged{$dom}{$role} = $result;
                   6639:                 }
                   6640:             } else {
                   6641:                 $needroles = 1;
                   6642:             }
                   6643:         }
                   6644:         if ($needroles) {
                   6645:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6646:             $privileged{$dom} = {};
                   6647:             foreach my $server (keys(%dompersonnel)) {
                   6648:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6649:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6650:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6651:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6652:                         next if ($end && $end < $now);
                   6653:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6654:                             $dompersonnel{$server}{$item};
                   6655:                     }
                   6656:                 }
                   6657:             }
                   6658:             if (ref($privileged{$dom}) eq 'HASH') {
                   6659:                 foreach my $role (@{$roles}) {
                   6660:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6661:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6662:                     } else {
                   6663:                         my %hash = ();
                   6664:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6665:                     }
                   6666:                 }
                   6667:             }
                   6668:         }
                   6669:     }
                   6670:     return %privileged;
                   6671: }
                   6672: 
1.103     harris41 6673: # -------------------------------------------------------- Get user privileges
1.11      www      6674: 
                   6675: sub rolesinit {
1.1169    droeschl 6676:     my ($domain, $username) = @_;
                   6677:     my %userroles = ('user.login.time' => time);
                   6678:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6679: 
                   6680:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6681:     # also, blocking can be triggered by an activating timer
                   6682:     # it's saved in the user's %env.
                   6683:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6684:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6685:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6686:         %timerintchk, %timerintenv);
                   6687: 
1.1162    raeburn  6688:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6689:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6690:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6691:     }
1.1169    droeschl 6692: 
1.1162    raeburn  6693:     foreach my $key (keys(%timerinterval)) {
                   6694:         my ($cid,$rest) = split(/\0/,$key);
                   6695:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6696:     }
1.1169    droeschl 6697: 
1.11      www      6698:     my %allroles=();
1.1162    raeburn  6699:     my %allgroups=();
1.11      www      6700: 
1.1172.2.58  raeburn  6701:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6702:         my $role = $rolesdump{$area};
                   6703:         $area =~ s/\_\w\w$//;
                   6704: 
                   6705:         my ($trole, $tend, $tstart, $group_privs);
                   6706: 
                   6707:         if ($role =~ /^cr/) {
                   6708:         # Custom role, defined by a user 
                   6709:         # e.g., user.role.cr/msu/smith/mynewrole
                   6710:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6711:                 $trole = $1;
                   6712:                 ($tend, $tstart) = split('_', $2);
                   6713:             } else {
                   6714:                 $trole = $role;
                   6715:             }
                   6716:         } elsif ($role =~ m|^gr/|) {
                   6717:         # Role of member in a group, defined within a course/community
                   6718:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6719:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6720:             next if $tstart eq '-1';
                   6721:             ($trole, $group_privs) = split(/\//, $trole);
                   6722:             $group_privs = &unescape($group_privs);
                   6723:         } else {
                   6724:         # Just a normal role, defined in roles.tab
                   6725:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6726:         }
                   6727: 
                   6728:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6729:                  $username);
                   6730:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6731: 
                   6732:         # role expired or not available yet?
                   6733:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6734:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6735: 
                   6736:         next if $area eq '' or $trole eq '';
                   6737: 
                   6738:         my $spec = "$trole.$area";
                   6739:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6740: 
                   6741:         if ($trole =~ /^cr\//) {
                   6742:         # Custom role, defined by a user
                   6743:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6744:         } elsif ($trole eq 'gr') {
                   6745:         # Role of a member in a group, defined within a course/community
                   6746:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6747:             next;
                   6748:         } else {
                   6749:         # Normal role, defined in roles.tab
                   6750:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6751:         }
                   6752: 
                   6753:         my $cid = $tdomain.'_'.$trest;
                   6754:         unless ($firstaccchk{$cid}) {
                   6755:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6756:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6757:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6758:                         $coursetimerstarts{$cid}{$item}; 
                   6759:                 }
                   6760:             }
                   6761:             $firstaccchk{$cid} = 1;
                   6762:         }
                   6763:         unless ($timerintchk{$cid}) {
                   6764:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6765:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6766:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6767:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6768:                 }
1.12      www      6769:             }
1.1169    droeschl 6770:             $timerintchk{$cid} = 1;
1.191     harris41 6771:         }
1.11      www      6772:     }
1.1169    droeschl 6773: 
1.1172.2.91  raeburn  6774:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6775:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6776:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6777:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6778: 
1.1162    raeburn  6779:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6780: }
                   6781: 
1.567     raeburn  6782: sub set_arearole {
1.1172.2.19  raeburn  6783:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6784:     unless ($nolog) {
1.567     raeburn  6785: # log the associated role with the area
1.1172.2.19  raeburn  6786:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6787:     }
1.743     albertel 6788:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6789: }
                   6790: 
                   6791: sub custom_roleprivs {
                   6792:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6793:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6794:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6795:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6796:         my ($rdummy,$roledef)=
                   6797:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6798:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6799:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6800:             if (defined($syspriv)) {
1.1043    raeburn  6801:                 if ($trest =~ /^$match_community$/) {
                   6802:                     $syspriv =~ s/bre\&S//; 
                   6803:                 }
1.567     raeburn  6804:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6805:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6806:             }
                   6807:             if ($tdomain ne '') {
                   6808:                 if (defined($dompriv)) {
                   6809:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6810:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6811:                 }
                   6812:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6813:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6814:                         my $rolename = $1;
                   6815:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6816:                     }
1.567     raeburn  6817:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6818:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6819:                 }
                   6820:             }
                   6821:         }
                   6822:     }
                   6823: }
                   6824: 
1.1172.2.89  raeburn  6825: sub course_adhocrole_privs {
                   6826:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6827:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6828:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6829:         my (%currprivs,%storeprivs);
                   6830:         foreach my $item (split(/:/,$coursepriv)) {
                   6831:             my ($priv,$restrict) = split(/\&/,$item);
                   6832:             $currprivs{$priv} = $restrict;
                   6833:         }
                   6834:         my (%possadd,%possremove,%full);
                   6835:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6836:             my ($priv,$restrict)=split(/\&/,$item);
                   6837:             $full{$priv} = $restrict;
                   6838:         }
                   6839:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
1.1172.2.146.  .6(raebu 6840:22):             next if ($item eq '');
                   6841:22):             my ($rule,$rest) = split(/=/,$item);
                   6842:22):             next unless (($rule eq 'off') || ($rule eq 'on'));
                   6843:22):             foreach my $priv (split(/:/,$rest)) {
                   6844:22):                 if ($priv ne '') {
                   6845:22):                     if ($rule eq 'off') {
                   6846:22):                         $possremove{$priv} = 1;
                   6847:22):                     } else {
                   6848:22):                         $possadd{$priv} = 1;
                   6849:22):                     }
                   6850:22):                 }
                   6851:22):             }
                   6852:22):         }
                   6853:22):         foreach my $priv (sort(keys(%full))) {
                   6854:22):             if (exists($currprivs{$priv})) {
                   6855:22):                 unless (exists($possremove{$priv})) {
                   6856:22):                     $storeprivs{$priv} = $currprivs{$priv};
                   6857:22):                 }
                   6858:22):             } elsif (exists($possadd{$priv})) {
                   6859:22):                 $storeprivs{$priv} = $full{$priv};
                   6860:22):             }
                   6861:22):         }
                   6862:22):         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6863:22):     }
                   6864:22):     return $coursepriv;
1.1172.2.89  raeburn  6865: }
                   6866: 
1.678     raeburn  6867: sub group_roleprivs {
                   6868:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6869:     my $access = 1;
                   6870:     my $now = time;
                   6871:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6872:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6873:     if ($access) {
1.811     albertel 6874:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6875:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6876:     }
                   6877: }
1.567     raeburn  6878: 
                   6879: sub standard_roleprivs {
                   6880:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6881:     if (defined($pr{$trole.':s'})) {
                   6882:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6883:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6884:     }
                   6885:     if ($tdomain ne '') {
                   6886:         if (defined($pr{$trole.':d'})) {
                   6887:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6888:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6889:         }
                   6890:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6891:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6892:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6893:         }
                   6894:     }
                   6895: }
                   6896: 
                   6897: sub set_userprivs {
1.1064    raeburn  6898:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6899:     my $author=0;
                   6900:     my $adv=0;
1.1172.2.91  raeburn  6901:     my $rar=0;
1.678     raeburn  6902:     my %grouproles = ();
                   6903:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6904:         my @groupkeys; 
1.1000    raeburn  6905:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6906:             push(@groupkeys,$role);
                   6907:         }
                   6908:         if (ref($groups_roles) eq 'HASH') {
                   6909:             foreach my $key (keys(%{$groups_roles})) {
                   6910:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6911:                     push(@groupkeys,$key);
                   6912:                 }
                   6913:             }
                   6914:         }
                   6915:         if (@groupkeys > 0) {
                   6916:             foreach my $role (@groupkeys) {
                   6917:                 my ($trole,$area,$sec,$extendedarea);
                   6918:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6919:                     $trole = $1;
                   6920:                     $area = $2;
                   6921:                     $sec = $3;
                   6922:                     $extendedarea = $area.$sec;
                   6923:                     if (exists($$allgroups{$area})) {
                   6924:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6925:                             my $spec = $trole.'.'.$extendedarea;
                   6926:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6927:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6928:                         }
1.678     raeburn  6929:                     }
                   6930:                 }
                   6931:             }
                   6932:         }
                   6933:     }
1.800     albertel 6934:     foreach my $group (keys(%grouproles)) {
                   6935:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6936:     }
1.800     albertel 6937:     foreach my $role (keys(%{$allroles})) {
                   6938:         my %thesepriv;
1.941     raeburn  6939:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6940:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6941:             if ($item ne '') {
                   6942:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6943:                 if ($restrictions eq '') {
                   6944:                     $thesepriv{$privilege}='F';
                   6945:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6946:                     $thesepriv{$privilege}.=$restrictions;
                   6947:                 }
                   6948:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6949:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6950:             }
                   6951:         }
                   6952:         my $thesestr='';
1.1104    raeburn  6953:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6954: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6955: 	}
                   6956:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6957:     }
1.1172.2.91  raeburn  6958:     return ($author,$adv,$rar);
1.567     raeburn  6959: }
                   6960: 
1.994     raeburn  6961: sub role_status {
1.1104    raeburn  6962:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6963:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6964:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6965:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6966:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6967:             $$where = '/'.$two;
1.994     raeburn  6968:             $$trolecode=$$role.'.'.$$where;
                   6969:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6970:             $$tstatus='is';
1.1104    raeburn  6971:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6972:                 $$tstatus='future';
1.1034    raeburn  6973:                 if ($$tstart<$now) {
                   6974:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6975:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6976:                             my (%allroles,%allgroups,$group_privs,
                   6977:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6978:                             my %userroles = (
                   6979:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6980:                             );
1.1064    raeburn  6981:                             @rolecodes = ('cm'); 
1.1002    raeburn  6982:                             my $spec=$$role.'.'.$$where;
                   6983:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6984:                             if ($$role =~ /^cr\//) {
                   6985:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6986:                                 push(@rolecodes,'cr');
1.1002    raeburn  6987:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6988:                                 push(@rolecodes,$$role);
1.1002    raeburn  6989:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6990:                                                     $env{'user.name'});
1.1064    raeburn  6991:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6992:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6993:                                 $group_privs = &unescape($group_privs);
                   6994:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6995:                                 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  6996:                                 &get_groups_roles($tdomain,$trest,
                   6997:                                                   \%course_roles,\@rolecodes,
                   6998:                                                   \%groups_roles);
1.1002    raeburn  6999:                             } else {
1.1064    raeburn  7000:                                 push(@rolecodes,$$role);
1.1002    raeburn  7001:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   7002:                             }
1.1172.2.91  raeburn  7003:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   7004:                                                                    \%groups_roles);
1.1064    raeburn  7005:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  7006:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  7007:                         }
                   7008:                     }
1.1034    raeburn  7009:                     $$tstatus = 'is';
1.1002    raeburn  7010:                 }
1.994     raeburn  7011:             }
                   7012:             if ($$tend) {
1.1104    raeburn  7013:                 if ($$tend<$update) {
1.994     raeburn  7014:                     $$tstatus='expired';
                   7015:                 } elsif ($$tend<$now) {
                   7016:                     $$tstatus='will_not';
                   7017:                 }
                   7018:             }
                   7019:         }
                   7020:     }
                   7021: }
                   7022: 
1.1104    raeburn  7023: sub get_groups_roles {
                   7024:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   7025:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   7026:                   (ref($rolecodes) eq 'ARRAY') && 
                   7027:                   (ref($groups_roles) eq 'HASH')); 
                   7028:     if (keys(%{$cdom_courseroles}) > 0) {
                   7029:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   7030:         if ($cdom ne '' && $cnum ne '') {
                   7031:             foreach my $key (keys(%{$cdom_courseroles})) {
                   7032:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   7033:                     my $crsrole = $1;
                   7034:                     my $crssec = $2;
                   7035:                     if ($crsrole =~ /^cr/) {
                   7036:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   7037:                             push(@{$rolecodes},'cr');
                   7038:                         }
                   7039:                     } else {
                   7040:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   7041:                             push(@{$rolecodes},$crsrole);
                   7042:                         }
                   7043:                     }
                   7044:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   7045:                     if ($crssec ne '') {
                   7046:                         $rolekey .= "/$crssec";
                   7047:                     }
                   7048:                     $rolekey .= './';
                   7049:                     $groups_roles->{$rolekey} = $rolecodes;
                   7050:                 }
                   7051:             }
                   7052:         }
                   7053:     }
                   7054:     return;
                   7055: }
                   7056: 
                   7057: sub delete_env_groupprivs {
                   7058:     my ($where,$courseroles,$possroles) = @_;
                   7059:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   7060:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   7061:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   7062:         %{$courseroles->{$udom}} =
                   7063:             &get_my_roles('','','userroles',['active'],
                   7064:                           $possroles,[$udom],1);
                   7065:     }
                   7066:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   7067:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   7068:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   7069:             my $area = '/'.$cdom.'/'.$cnum;
                   7070:             my $privkey = "user.priv.$crsrole.$area";
                   7071:             if ($crssec ne '') {
                   7072:                 $privkey .= '/'.$crssec;
                   7073:             }
                   7074:             $privkey .= ".$area/$group";
                   7075:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   7076:         }
                   7077:     }
                   7078:     return;
                   7079: }
                   7080: 
1.994     raeburn  7081: sub check_adhoc_privs {
1.1172.2.86  raeburn  7082:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  7083:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  7084:     if ($sec) {
                   7085:         $cckey .= '/'.$sec;
                   7086:     }
1.1172.2.9  raeburn  7087:     my $setprivs;
1.994     raeburn  7088:     if ($env{$cckey}) {
                   7089:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  7090:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  7091:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  7092:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  7093:             $setprivs = 1;
1.994     raeburn  7094:         }
                   7095:     } else {
1.1172.2.87  raeburn  7096:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  7097:         $setprivs = 1;
1.994     raeburn  7098:     }
1.1172.2.9  raeburn  7099:     return $setprivs;
1.994     raeburn  7100: }
                   7101: 
                   7102: sub set_adhoc_privileges {
1.1172.2.84  raeburn  7103: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  7104:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  7105:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  7106:     if ($sec ne '') {
                   7107:         $area .= '/'.$sec;
                   7108:     }
1.994     raeburn  7109:     my $spec = $role.'.'.$area;
                   7110:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  7111:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  7112:     my %rolehash = ();
1.1172.2.89  raeburn  7113:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   7114:         my $rolename = $1;
1.1172.2.84  raeburn  7115:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  7116:         my %domdef = &get_domain_defaults($dcdom);
                   7117:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   7118:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   7119:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   7120:             }
                   7121:         }
1.1172.2.84  raeburn  7122:     } else {
                   7123:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   7124:     }
1.1172.2.91  raeburn  7125:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  7126:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  7127:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1172.2.146.  .1(raebu 7128:22):     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   7129:22):             ($caller eq 'tiny')) {
1.1088    raeburn  7130:         &appenv( {'request.role'        => $spec,
                   7131:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  7132:                   'request.course.sec'  => $sec, 
1.1088    raeburn  7133:                  }
                   7134:                );
                   7135:         my $tadv=0;
                   7136:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   7137:         &appenv({'request.role.adv'    => $tadv});
                   7138:     }
1.994     raeburn  7139: }
                   7140: 
1.12      www      7141: # --------------------------------------------------------------- get interface
                   7142: 
                   7143: sub get {
1.131     albertel 7144:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7145:    my $items='';
1.800     albertel 7146:    foreach my $item (@$storearr) {
                   7147:        $items.=&escape($item).'&';
1.191     harris41 7148:    }
1.12      www      7149:    $items=~s/\&$//;
1.620     albertel 7150:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7151:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 7152:    my $uhome=&homeserver($uname,$udomain);
                   7153: 
1.133     albertel 7154:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7155:    my @pairs=split(/\&/,$rep);
1.273     albertel 7156:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   7157:      return @pairs;
                   7158:    }
1.15      www      7159:    my %returnhash=();
1.42      www      7160:    my $i=0;
1.800     albertel 7161:    foreach my $item (@$storearr) {
                   7162:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7163:       $i++;
1.191     harris41 7164:    }
1.15      www      7165:    return %returnhash;
1.27      www      7166: }
                   7167: 
                   7168: # --------------------------------------------------------------- del interface
                   7169: 
                   7170: sub del {
1.133     albertel 7171:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      7172:    my $items='';
1.800     albertel 7173:    foreach my $item (@$storearr) {
                   7174:        $items.=&escape($item).'&';
1.191     harris41 7175:    }
1.984     neumanie 7176: 
1.27      www      7177:    $items=~s/\&$//;
1.620     albertel 7178:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7179:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7180:    my $uhome=&homeserver($uname,$udomain);
                   7181:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7182: }
                   7183: 
                   7184: # -------------------------------------------------------------- dump interface
                   7185: 
1.1172.2.22  raeburn  7186: sub unserialize {
                   7187:     my ($rep, $escapedkeys) = @_;
                   7188: 
                   7189:     return {} if $rep =~ /^error/;
                   7190: 
                   7191:     my %returnhash=();
                   7192:     foreach my $item (split(/\&/,$rep)) {
                   7193:         my ($key, $value) = split(/=/, $item, 2);
                   7194:         $key = unescape($key) unless $escapedkeys;
                   7195:         next if $key =~ /^error: 2 /;
                   7196:         $returnhash{$key} = &thaw_unescape($value);
                   7197:     }
                   7198:     return \%returnhash;
                   7199: }
                   7200: 
                   7201: # see Lond::dump_with_regexp
                   7202: # if $escapedkeys hash keys won't get unescaped.
1.15      www      7203: sub dump {
1.1172.2.146.  .1(raebu 7204:22):     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755     albertel 7205:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7206:     if (!$uname) { $uname=$env{'user.name'}; }
                   7207:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 7208: 
1.1172.2.55  raeburn  7209:     if ($regexp) {
                   7210:         $regexp=&escape($regexp);
                   7211:     } else {
                   7212:         $regexp='.';
                   7213:     }
1.1172.2.22  raeburn  7214:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   7215:         # user is hosted on this machine
1.1172.2.55  raeburn  7216:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  7217:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  7218:         return %{&unserialize($reply, $escapedkeys)};
                   7219:     }
1.1172.2.146.  .1(raebu 7220:22):     my $rep;
                   7221:22):     if ($encrypt) {
                   7222:22):         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7223:22):     } else {
                   7224:22):         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7225:22):     }
1.755     albertel 7226:     my @pairs=split(/\&/,$rep);
                   7227:     my %returnhash=();
1.1098    foxr     7228:     if (!($rep =~ /^error/ )) {
                   7229: 	foreach my $item (@pairs) {
                   7230: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  7231:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     7232: 	    next if ($key =~ /^error: 2 /);
                   7233: 	    $returnhash{$key}=&thaw_unescape($value);
                   7234: 	}
1.755     albertel 7235:     }
                   7236:     return %returnhash;
1.407     www      7237: }
                   7238: 
1.1098    foxr     7239: 
1.717     albertel 7240: # --------------------------------------------------------- dumpstore interface
                   7241: 
                   7242: sub dumpstore {
                   7243:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  7244:    # same as dump but keys must be escaped. They may contain colon separated
                   7245:    # lists of values that may themself contain colons (e.g. symbs).
                   7246:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7247: }
                   7248: 
1.407     www      7249: # -------------------------------------------------------------- keys interface
                   7250: 
                   7251: sub getkeys {
                   7252:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7253:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7254:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7255:    my $uhome=&homeserver($uname,$udomain);
                   7256:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7257:    my @keyarray=();
1.800     albertel 7258:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7259:       next if ($key =~ /^error: 2 /);
1.800     albertel 7260:       push(@keyarray,&unescape($key));
1.407     www      7261:    }
                   7262:    return @keyarray;
1.318     matthew  7263: }
                   7264: 
1.319     matthew  7265: # --------------------------------------------------------------- currentdump
                   7266: sub currentdump {
1.328     matthew  7267:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7268:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7269:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7270:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7271:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  7272:    my $rep;
                   7273: 
                   7274:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7275:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   7276:                    $courseid)));
                   7277:    } else {
                   7278:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7279:    }
                   7280: 
1.318     matthew  7281:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7282:    #
1.318     matthew  7283:    my %returnhash=();
1.319     matthew  7284:    #
                   7285:    if ($rep eq "unknown_cmd") { 
                   7286:        # an old lond will not know currentdump
                   7287:        # Do a dump and make it look like a currentdump
1.822     albertel 7288:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7289:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7290:        my %hash = @tmp;
                   7291:        @tmp=();
1.424     matthew  7292:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7293:    } else {
                   7294:        my @pairs=split(/\&/,$rep);
1.800     albertel 7295:        foreach my $pair (@pairs) {
                   7296:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7297:            my ($symb,$param) = split(/:/,$key);
                   7298:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7299:                                                         &thaw_unescape($value);
1.319     matthew  7300:        }
1.191     harris41 7301:    }
1.12      www      7302:    return %returnhash;
1.424     matthew  7303: }
                   7304: 
                   7305: sub convert_dump_to_currentdump{
                   7306:     my %hash = %{shift()};
                   7307:     my %returnhash;
                   7308:     # Code ripped from lond, essentially.  The only difference
                   7309:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7310:     # we might run in to problems with parameter names =~ /^v\./
                   7311:     while (my ($key,$value) = each(%hash)) {
                   7312:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7313: 	$symb  = &unescape($symb);
                   7314: 	$param = &unescape($param);
1.424     matthew  7315:         next if ($v eq 'version' || $symb eq 'keys');
                   7316:         next if (exists($returnhash{$symb}) &&
                   7317:                  exists($returnhash{$symb}->{$param}) &&
                   7318:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7319:         $returnhash{$symb}->{$param}=$value;
                   7320:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7321:     }
                   7322:     #
                   7323:     # Remove all of the keys in the hashes which keep track of
                   7324:     # the version of the parameter.
                   7325:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7326:         # use a foreach because we are going to delete from the hash.
                   7327:         foreach my $key (keys(%$param_hash)) {
                   7328:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7329:         }
                   7330:     }
                   7331:     return \%returnhash;
1.12      www      7332: }
                   7333: 
1.627     albertel 7334: # ------------------------------------------------------ critical inc interface
                   7335: 
                   7336: sub cinc {
                   7337:     return &inc(@_,'critical');
                   7338: }
                   7339: 
1.449     matthew  7340: # --------------------------------------------------------------- inc interface
                   7341: 
                   7342: sub inc {
1.627     albertel 7343:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7344:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7345:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7346:     my $uhome=&homeserver($uname,$udomain);
                   7347:     my $items='';
                   7348:     if (! ref($store)) {
                   7349:         # got a single value, so use that instead
                   7350:         $items = &escape($store).'=&';
                   7351:     } elsif (ref($store) eq 'SCALAR') {
                   7352:         $items = &escape($$store).'=&';        
                   7353:     } elsif (ref($store) eq 'ARRAY') {
                   7354:         $items = join('=&',map {&escape($_);} @{$store});
                   7355:     } elsif (ref($store) eq 'HASH') {
                   7356:         while (my($key,$value) = each(%{$store})) {
                   7357:             $items.= &escape($key).'='.&escape($value).'&';
                   7358:         }
                   7359:     }
                   7360:     $items=~s/\&$//;
1.627     albertel 7361:     if ($critical) {
                   7362: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7363:     } else {
                   7364: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7365:     }
1.449     matthew  7366: }
                   7367: 
1.12      www      7368: # --------------------------------------------------------------- put interface
                   7369: 
                   7370: sub put {
1.1172.2.146.  .1(raebu 7371:22):    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620     albertel 7372:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7373:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7374:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7375:    my $items='';
1.800     albertel 7376:    foreach my $item (keys(%$storehash)) {
                   7377:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7378:    }
1.12      www      7379:    $items=~s/\&$//;
1.1172.2.146.  .1(raebu 7380:22):    if ($encrypt) {
                   7381:22):        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
                   7382:22):    } else {
                   7383:22):        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   7384:22):    }
1.47      www      7385: }
                   7386: 
1.631     albertel 7387: # ------------------------------------------------------------ newput interface
                   7388: 
                   7389: sub newput {
                   7390:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7391:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7392:    if (!$uname) { $uname=$env{'user.name'}; }
                   7393:    my $uhome=&homeserver($uname,$udomain);
                   7394:    my $items='';
                   7395:    foreach my $key (keys(%$storehash)) {
                   7396:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7397:    }
                   7398:    $items=~s/\&$//;
                   7399:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7400: }
                   7401: 
                   7402: # ---------------------------------------------------------  putstore interface
                   7403: 
1.524     raeburn  7404: sub putstore {
1.1172.2.59  raeburn  7405:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7406:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7407:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7408:    my $uhome=&homeserver($uname,$udomain);
                   7409:    my $items='';
1.715     albertel 7410:    foreach my $key (keys(%$storehash)) {
                   7411:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7412:    }
1.715     albertel 7413:    $items=~s/\&$//;
1.716     albertel 7414:    my $esc_symb=&escape($symb);
                   7415:    my $esc_v=&escape($version);
1.715     albertel 7416:    my $reply =
1.716     albertel 7417:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7418: 	      $uhome);
1.1172.2.59  raeburn  7419:    if (($tolog) && ($reply eq 'ok')) {
                   7420:        my $namevalue='';
                   7421:        foreach my $key (keys(%{$storehash})) {
                   7422:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7423:        }
1.1172.2.134  raeburn  7424:        my $ip = &get_requestor_ip();
1.1172.2.135  raeburn  7425:        $namevalue .= 'ip='.&escape($ip).
1.1172.2.59  raeburn  7426:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7427:                      '&version='.$esc_v.
                   7428:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7429:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7430:    }
1.715     albertel 7431:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7432:        # gfall back to way things use to be done
1.715     albertel 7433:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7434: 			    $uname);
1.524     raeburn  7435:    }
1.715     albertel 7436:    return $reply;
                   7437: }
                   7438: 
                   7439: sub old_putstore {
1.716     albertel 7440:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7441:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7442:     if (!$uname) { $uname=$env{'user.name'}; }
                   7443:     my $uhome=&homeserver($uname,$udomain);
                   7444:     my %newstorehash;
1.800     albertel 7445:     foreach my $item (keys(%$storehash)) {
                   7446: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7447: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7448:     }
                   7449:     my $items='';
                   7450:     my %allitems = ();
1.800     albertel 7451:     foreach my $item (keys(%newstorehash)) {
                   7452: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7453: 	    my $key = $1.':keys:'.$2;
                   7454: 	    $allitems{$key} .= $3.':';
                   7455: 	}
1.800     albertel 7456: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7457:     }
1.800     albertel 7458:     foreach my $item (keys(%allitems)) {
                   7459: 	$allitems{$item} =~ s/\:$//;
                   7460: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7461:     }
                   7462:     $items=~s/\&$//;
                   7463:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7464: }
                   7465: 
1.47      www      7466: # ------------------------------------------------------ critical put interface
                   7467: 
                   7468: sub cput {
1.134     albertel 7469:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7470:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7471:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7472:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7473:    my $items='';
1.800     albertel 7474:    foreach my $item (keys(%$storehash)) {
                   7475:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7476:    }
1.47      www      7477:    $items=~s/\&$//;
1.134     albertel 7478:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7479: }
                   7480: 
                   7481: # -------------------------------------------------------------- eget interface
                   7482: 
                   7483: sub eget {
1.133     albertel 7484:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7485:    my $items='';
1.800     albertel 7486:    foreach my $item (@$storearr) {
                   7487:        $items.=&escape($item).'&';
1.191     harris41 7488:    }
1.12      www      7489:    $items=~s/\&$//;
1.620     albertel 7490:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7491:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7492:    my $uhome=&homeserver($uname,$udomain);
                   7493:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7494:    my @pairs=split(/\&/,$rep);
                   7495:    my %returnhash=();
1.42      www      7496:    my $i=0;
1.800     albertel 7497:    foreach my $item (@$storearr) {
                   7498:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7499:       $i++;
1.191     harris41 7500:    }
1.12      www      7501:    return %returnhash;
                   7502: }
                   7503: 
1.667     albertel 7504: # ------------------------------------------------------------ tmpput interface
                   7505: sub tmpput {
1.802     raeburn  7506:     my ($storehash,$server,$context)=@_;
1.667     albertel 7507:     my $items='';
1.800     albertel 7508:     foreach my $item (keys(%$storehash)) {
                   7509: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7510:     }
                   7511:     $items=~s/\&$//;
1.802     raeburn  7512:     if (defined($context)) {
                   7513:         $items .= ':'.&escape($context);
                   7514:     }
1.667     albertel 7515:     return &reply("tmpput:$items",$server);
                   7516: }
                   7517: 
                   7518: # ------------------------------------------------------------ tmpget interface
                   7519: sub tmpget {
1.688     albertel 7520:     my ($token,$server)=@_;
                   7521:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7522:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7523:     my %returnhash;
1.1172.2.85  raeburn  7524:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7525:         return %returnhash;
                   7526:     }
1.667     albertel 7527:     foreach my $item (split(/\&/,$rep)) {
                   7528: 	my ($key,$value)=split(/=/,$item);
                   7529: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7530:     }
                   7531:     return %returnhash;
                   7532: }
                   7533: 
1.1113    raeburn  7534: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7535: sub tmpdel {
                   7536:     my ($token,$server)=@_;
                   7537:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7538:     return &reply("tmpdel:$token",$server);
                   7539: }
                   7540: 
1.1172.2.13  raeburn  7541: # ------------------------------------------------------------ get_timebased_id
                   7542: 
                   7543: sub get_timebased_id {
                   7544:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7545:         $maxtries) = @_;
                   7546:     my ($newid,$error,$dellock);
                   7547:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7548:         return ('','ok','invalid call to get suffix');
                   7549:     }
                   7550: 
                   7551: # set defaults for any optional args for which values were not supplied
                   7552:     if ($who eq '') {
                   7553:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7554:     }
                   7555:     if (!$locktries) {
                   7556:         $locktries = 3;
                   7557:     }
                   7558:     if (!$maxtries) {
                   7559:         $maxtries = 10;
                   7560:     }
                   7561: 
                   7562:     if (($cdom eq '') || ($cnum eq '')) {
                   7563:         if ($env{'request.course.id'}) {
                   7564:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7565:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7566:         }
                   7567:         if (($cdom eq '') || ($cnum eq '')) {
                   7568:             return ('','ok','call to get suffix not in course context');
                   7569:         }
                   7570:     }
                   7571: 
                   7572: # construct locking item
                   7573:     my $lockhash = {
                   7574:                       $prefix."\0".'locked_'.$keyid => $who,
                   7575:                    };
                   7576:     my $tries = 0;
                   7577: 
                   7578: # attempt to get lock on nohist_$namespace file
                   7579:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7580:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7581:         $tries ++;
                   7582:         sleep 1;
                   7583:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7584:     }
                   7585: 
                   7586: # attempt to get unique identifier, based on current timestamp
                   7587:     if ($gotlock eq 'ok') {
                   7588:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7589:         my $id = time;
                   7590:         $newid = $id;
1.1172.2.56  raeburn  7591:         if ($idtype eq 'addcode') {
                   7592:             $newid .= &sixnum_code();
                   7593:         }
1.1172.2.13  raeburn  7594:         my $idtries = 0;
                   7595:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7596:             if ($idtype eq 'concat') {
                   7597:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7598:             } elsif ($idtype eq 'addcode') {
                   7599:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7600:             } else {
                   7601:                 $newid ++;
                   7602:             }
                   7603:             $idtries ++;
                   7604:         }
                   7605:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7606:             my %new_item =  (
                   7607:                               $prefix."\0".$newid => $who,
                   7608:                             );
                   7609:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7610:                                                  $cdom,$cnum);
                   7611:             if ($putresult ne 'ok') {
                   7612:                 undef($newid);
                   7613:                 $error = 'error saving new item: '.$putresult;
                   7614:             }
                   7615:         } else {
1.1172.2.56  raeburn  7616:              undef($newid);
1.1172.2.13  raeburn  7617:              $error = ('error: no unique suffix available for the new item ');
                   7618:         }
                   7619: #  remove lock
                   7620:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7621:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7622:     } else {
                   7623:         $error = "error: could not obtain lockfile\n";
                   7624:         $dellock = 'ok';
1.1172.2.58  raeburn  7625:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7626:             $dellock = 'nolock';
                   7627:         }
1.1172.2.13  raeburn  7628:     }
                   7629:     return ($newid,$dellock,$error);
                   7630: }
                   7631: 
1.1172.2.56  raeburn  7632: sub sixnum_code {
                   7633:     my $code;
                   7634:     for (0..6) {
                   7635:         $code .= int( rand(9) );
                   7636:     }
                   7637:     return $code;
                   7638: }
                   7639: 
1.765     albertel 7640: # -------------------------------------------------- portfolio access checking
                   7641: 
                   7642: sub portfolio_access {
1.1172.2.77  raeburn  7643:     my ($requrl,$clientip) = @_;
1.765     albertel 7644:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7645:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7646:     if ($result) {
                   7647:         my %setters;
                   7648:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142  raeburn  7649:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7650:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
                   7651:             if (($startblock && $endblock) || ($by_ip))  {
1.814     raeburn  7652:                 return 'B';
                   7653:             }
                   7654:         } else {
1.1172.2.142  raeburn  7655:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
                   7656:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7657:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7658:                 return 'B';
                   7659:             }
                   7660:         }
                   7661:     }
1.765     albertel 7662:     if ($result eq 'ok') {
1.766     albertel 7663:        return 'F';
1.765     albertel 7664:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7665:        return 'A';
1.765     albertel 7666:     }
1.766     albertel 7667:     return '';
1.765     albertel 7668: }
                   7669: 
                   7670: sub get_portfolio_access {
1.1172.2.77  raeburn  7671:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7672: 
                   7673:     if (!ref($access_hash)) {
                   7674: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7675: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7676: 						   $file_name);
                   7677: 	$access_hash = $access_controls{$file_name};
                   7678:     }
                   7679: 
1.1172.2.77  raeburn  7680:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7681:     my $now = time;
                   7682:     if (ref($access_hash) eq 'HASH') {
                   7683:         foreach my $key (keys(%{$access_hash})) {
                   7684:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7685:             if ($start > $now) {
                   7686:                 next;
                   7687:             }
                   7688:             if ($end && $end<$now) {
                   7689:                 next;
                   7690:             }
                   7691:             if ($scope eq 'public') {
                   7692:                 $public = $key;
                   7693:                 last;
                   7694:             } elsif ($scope eq 'guest') {
                   7695:                 $guest = $key;
                   7696:             } elsif ($scope eq 'domains') {
                   7697:                 push(@domains,$key);
                   7698:             } elsif ($scope eq 'users') {
                   7699:                 push(@users,$key);
                   7700:             } elsif ($scope eq 'course') {
                   7701:                 push(@courses,$key);
                   7702:             } elsif ($scope eq 'group') {
                   7703:                 push(@groups,$key);
1.1172.2.77  raeburn  7704:             } elsif ($scope eq 'ip') {
                   7705:                 push(@ips,$key);
1.765     albertel 7706:             }
                   7707:         }
                   7708:         if ($public) {
                   7709:             return 'ok';
1.1172.2.77  raeburn  7710:         } elsif (@ips > 0) {
                   7711:             my $allowed;
                   7712:             foreach my $ipkey (@ips) {
                   7713:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7714:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7715:                         $allowed = 1;
                   7716:                         last;
                   7717:                     }
                   7718:                 }
                   7719:             }
                   7720:             if ($allowed) {
                   7721:                 return 'ok';
                   7722:             }
1.765     albertel 7723:         }
                   7724:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7725:             if ($guest) {
                   7726:                 return $guest;
                   7727:             }
                   7728:         } else {
                   7729:             if (@domains > 0) {
                   7730:                 foreach my $domkey (@domains) {
                   7731:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7732:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7733:                             return 'ok';
                   7734:                         }
                   7735:                     }
                   7736:                 }
                   7737:             }
                   7738:             if (@users > 0) {
                   7739:                 foreach my $userkey (@users) {
1.865     raeburn  7740:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7741:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7742:                             if (ref($item) eq 'HASH') {
                   7743:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7744:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7745:                                     return 'ok';
                   7746:                                 }
                   7747:                             }
                   7748:                         }
                   7749:                     } 
1.765     albertel 7750:                 }
                   7751:             }
                   7752:             my %roleshash;
                   7753:             my @courses_and_groups = @courses;
                   7754:             push(@courses_and_groups,@groups); 
                   7755:             if (@courses_and_groups > 0) {
                   7756:                 my (%allgroups,%allroles); 
                   7757:                 my ($start,$end,$role,$sec,$group);
                   7758:                 foreach my $envkey (%env) {
1.1060    raeburn  7759:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7760:                         my $cid = $2.'_'.$3; 
                   7761:                         if ($1 eq 'gr') {
                   7762:                             $group = $4;
                   7763:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7764:                         } else {
                   7765:                             if ($4 eq '') {
                   7766:                                 $sec = 'none';
                   7767:                             } else {
                   7768:                                 $sec = $4;
                   7769:                             }
                   7770:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7771:                         }
1.811     albertel 7772:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7773:                         my $cid = $2.'_'.$3;
                   7774:                         if ($4 eq '') {
                   7775:                             $sec = 'none';
                   7776:                         } else {
                   7777:                             $sec = $4;
                   7778:                         }
                   7779:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7780:                     }
                   7781:                 }
                   7782:                 if (keys(%allroles) == 0) {
                   7783:                     return;
                   7784:                 }
                   7785:                 foreach my $key (@courses_and_groups) {
                   7786:                     my %content = %{$$access_hash{$key}};
                   7787:                     my $cnum = $content{'number'};
                   7788:                     my $cdom = $content{'domain'};
                   7789:                     my $cid = $cdom.'_'.$cnum;
                   7790:                     if (!exists($allroles{$cid})) {
                   7791:                         next;
                   7792:                     }    
                   7793:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7794:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7795:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7796:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7797:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7798:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7799:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7800:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7801:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7802:                                         if (grep/^all$/,@sections) {
                   7803:                                             return 'ok';
                   7804:                                         } else {
                   7805:                                             if (grep/^$sec$/,@sections) {
                   7806:                                                 return 'ok';
                   7807:                                             }
                   7808:                                         }
                   7809:                                     }
                   7810:                                 }
                   7811:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7812:                                     if (grep/^none$/,@groups) {
                   7813:                                         return 'ok';
                   7814:                                     }
                   7815:                                 } else {
                   7816:                                     if (grep/^all$/,@groups) {
                   7817:                                         return 'ok';
                   7818:                                     } 
                   7819:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7820:                                         if (grep/^$group$/,@groups) {
                   7821:                                             return 'ok';
                   7822:                                         }
                   7823:                                     }
                   7824:                                 } 
                   7825:                             }
                   7826:                         }
                   7827:                     }
                   7828:                 }
                   7829:             }
                   7830:             if ($guest) {
                   7831:                 return $guest;
                   7832:             }
                   7833:         }
                   7834:     }
                   7835:     return;
                   7836: }
                   7837: 
                   7838: sub course_group_datechecker {
                   7839:     my ($dates,$now,$status) = @_;
                   7840:     my ($start,$end) = split(/\./,$dates);
                   7841:     if (!$start && !$end) {
                   7842:         return 'ok';
                   7843:     }
                   7844:     if (grep/^active$/,@{$status}) {
                   7845:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7846:             return 'ok';
                   7847:         }
                   7848:     }
                   7849:     if (grep/^previous$/,@{$status}) {
                   7850:         if ($end > $now ) {
                   7851:             return 'ok';
                   7852:         }
                   7853:     }
                   7854:     if (grep/^future$/,@{$status}) {
                   7855:         if ($start > $now) {
                   7856:             return 'ok';
                   7857:         }
                   7858:     }
                   7859:     return; 
                   7860: }
                   7861: 
                   7862: sub parse_portfolio_url {
                   7863:     my ($url) = @_;
                   7864: 
                   7865:     my ($type,$udom,$unum,$group,$file_name);
                   7866:     
1.823     albertel 7867:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7868: 	$type = 1;
                   7869:         $udom = $1;
                   7870:         $unum = $2;
                   7871:         $file_name = $3;
1.823     albertel 7872:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7873: 	$type = 2;
                   7874:         $udom = $1;
                   7875:         $unum = $2;
                   7876:         $group = $3;
                   7877:         $file_name = $3.'/'.$4;
                   7878:     }
                   7879:     if (wantarray) {
                   7880: 	return ($type,$udom,$unum,$file_name,$group);
                   7881:     }
                   7882:     return $type;
                   7883: }
                   7884: 
                   7885: sub is_portfolio_url {
                   7886:     my ($url) = @_;
                   7887:     return scalar(&parse_portfolio_url($url));
                   7888: }
                   7889: 
1.798     raeburn  7890: sub is_portfolio_file {
                   7891:     my ($file) = @_;
1.820     raeburn  7892:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7893:         return 1;
                   7894:     }
                   7895:     return;
                   7896: }
                   7897: 
1.1172.2.146.  .13(raeb 7898:-23): sub is_coursetool_logo {
                   7899:-23):     my ($uri) = @_;
                   7900:-23):     if ($env{'request.course.id'}) {
                   7901:-23):         my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   7902:-23):         if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
                   7903:-23):             return 1;
                   7904:-23):         }
                   7905:-23):     }
                   7906:-23):     return;
                   7907:-23): }
                   7908:-23): 
1.976     raeburn  7909: sub usertools_access {
1.1084    raeburn  7910:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7911:     my ($access,%tools);
                   7912:     if ($context eq '') {
                   7913:         $context = 'tools';
                   7914:     }
                   7915:     if ($context eq 'requestcourses') {
                   7916:         %tools = (
                   7917:                       official   => 1,
                   7918:                       unofficial => 1,
1.1006    raeburn  7919:                       community  => 1,
1.1172.2.37  raeburn  7920:                       textbook   => 1,
1.1172.2.146.  .13(raeb 7921:-23):                       lti        => 1,
1.985     raeburn  7922:                  );
1.1172.2.9  raeburn  7923:     } elsif ($context eq 'requestauthor') {
                   7924:         %tools = (
                   7925:                       requestauthor => 1,
                   7926:                  );
1.985     raeburn  7927:     } else {
                   7928:         %tools = (
                   7929:                       aboutme   => 1,
                   7930:                       blog      => 1,
1.1172.2.6  raeburn  7931:                       webdav    => 1,
1.985     raeburn  7932:                       portfolio => 1,
1.1172.2.146.  .6(raebu 7933:22):                       timezone  => 1,
1.985     raeburn  7934:                  );
                   7935:     }
1.976     raeburn  7936:     return if (!defined($tools{$tool}));
                   7937: 
1.1172.2.35  raeburn  7938:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7939:         $udom = $env{'user.domain'};
                   7940:         $uname = $env{'user.name'};
                   7941:     }
                   7942: 
1.978     raeburn  7943:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7944:         if ($action ne 'reload') {
1.985     raeburn  7945:             if ($context eq 'requestcourses') {
                   7946:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7947:             } elsif ($context eq 'requestauthor') {
                   7948:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7949:             } else {
                   7950:                 return $env{'environment.availabletools.'.$tool};
                   7951:             }
                   7952:         }
1.976     raeburn  7953:     }
                   7954: 
1.1172.2.9  raeburn  7955:     my ($toolstatus,$inststatus,$envkey);
                   7956:     if ($context eq 'requestauthor') {
                   7957:         $envkey = $context;
                   7958:     } else {
                   7959:         $envkey = $context.'.'.$tool;
                   7960:     }
1.976     raeburn  7961: 
1.985     raeburn  7962:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7963:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7964:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7965:         $inststatus = $env{'environment.inststatus'};
                   7966:     } else {
1.1084    raeburn  7967:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7968:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7969:             $inststatus = $userenvref->{'inststatus'};
                   7970:         } else {
1.1172.2.9  raeburn  7971:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7972:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7973:             $inststatus = $userenv{'inststatus'};
                   7974:         }
1.976     raeburn  7975:     }
                   7976: 
                   7977:     if ($toolstatus ne '') {
                   7978:         if ($toolstatus) {
                   7979:             $access = 1;
                   7980:         } else {
                   7981:             $access = 0;
                   7982:         }
                   7983:         return $access;
                   7984:     }
                   7985: 
1.1084    raeburn  7986:     my ($is_adv,%domdef);
                   7987:     if (ref($is_advref) eq 'HASH') {
                   7988:         $is_adv = $is_advref->{'is_adv'};
                   7989:     } else {
                   7990:         $is_adv = &is_advanced_user($udom,$uname);
                   7991:     }
                   7992:     if (ref($domdefref) eq 'HASH') {
                   7993:         %domdef = %{$domdefref};
                   7994:     } else {
                   7995:         %domdef = &get_domain_defaults($udom);
                   7996:     }
1.976     raeburn  7997:     if (ref($domdef{$tool}) eq 'HASH') {
                   7998:         if ($is_adv) {
                   7999:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   8000:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   8001:                     $access = 1;
                   8002:                 } else {
                   8003:                     $access = 0;
                   8004:                 }
                   8005:                 return $access;
                   8006:             }
                   8007:         }
                   8008:         if ($inststatus ne '') {
                   8009:             my ($hasaccess,$hasnoaccess);
                   8010:             foreach my $affiliation (split(/:/,$inststatus)) {
                   8011:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   8012:                     if ($domdef{$tool}{$affiliation}) {
                   8013:                         $hasaccess = 1;
                   8014:                     } else {
                   8015:                         $hasnoaccess = 1;
                   8016:                     }
                   8017:                 }
                   8018:             }
                   8019:             if ($hasaccess || $hasnoaccess) {
                   8020:                 if ($hasaccess) {
                   8021:                     $access = 1;
                   8022:                 } elsif ($hasnoaccess) {
                   8023:                     $access = 0; 
                   8024:                 }
                   8025:                 return $access;
                   8026:             }
                   8027:         } else {
                   8028:             if ($domdef{$tool}{'default'} ne '') {
                   8029:                 if ($domdef{$tool}{'default'}) {
                   8030:                     $access = 1;
                   8031:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   8032:                     $access = 0;
                   8033:                 }
                   8034:                 return $access;
                   8035:             }
                   8036:         }
                   8037:     } else {
1.1172.2.6  raeburn  8038:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  8039:             $access = 1;
                   8040:         } else {
                   8041:             $access = 0;
                   8042:         }
1.976     raeburn  8043:         return $access;
                   8044:     }
                   8045: }
                   8046: 
1.1050    raeburn  8047: sub is_course_owner {
                   8048:     my ($cdom,$cnum,$udom,$uname) = @_;
                   8049:     if (($udom eq '') || ($uname eq '')) {
                   8050:         $udom = $env{'user.domain'};
                   8051:         $uname = $env{'user.name'};
                   8052:     }
                   8053:     unless (($udom eq '') || ($uname eq '')) {
                   8054:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   8055:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   8056:                 return 1;
                   8057:             } else {
                   8058:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   8059:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   8060:                     return 1;
                   8061:                 }
                   8062:             }
                   8063:         }
                   8064:     }
                   8065:     return;
                   8066: }
                   8067: 
1.976     raeburn  8068: sub is_advanced_user {
                   8069:     my ($udom,$uname) = @_;
1.1085    raeburn  8070:     if ($udom ne '' && $uname ne '') {
                   8071:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  8072:             if (wantarray) {
                   8073:                 return ($env{'user.adv'},$env{'user.author'});
                   8074:             } else {
                   8075:                 return $env{'user.adv'};
                   8076:             }
1.1085    raeburn  8077:         }
                   8078:     }
1.976     raeburn  8079:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   8080:     my %allroles;
1.1128    raeburn  8081:     my ($is_adv,$is_author);
1.976     raeburn  8082:     foreach my $role (keys(%roleshash)) {
                   8083:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   8084:         my $area = '/'.$tdomain.'/'.$trest;
                   8085:         if ($sec ne '') {
                   8086:             $area .= '/'.$sec;
                   8087:         }
                   8088:         if (($area ne '') && ($trole ne '')) {
                   8089:             my $spec=$trole.'.'.$area;
                   8090:             if ($trole =~ /^cr\//) {
                   8091:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   8092:             } elsif ($trole ne 'gr') {
                   8093:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   8094:             }
1.1128    raeburn  8095:             if ($trole eq 'au') {
                   8096:                 $is_author = 1;
                   8097:             }
1.976     raeburn  8098:         }
                   8099:     }
                   8100:     foreach my $role (keys(%allroles)) {
                   8101:         last if ($is_adv);
                   8102:         foreach my $item (split(/:/,$allroles{$role})) {
                   8103:             if ($item ne '') {
                   8104:                 my ($privilege,$restrictions)=split(/&/,$item);
                   8105:                 if ($privilege eq 'adv') {
                   8106:                     $is_adv = 1;
                   8107:                     last;
                   8108:                 }
                   8109:             }
                   8110:         }
                   8111:     }
1.1128    raeburn  8112:     if (wantarray) {
                   8113:         return ($is_adv,$is_author);
                   8114:     }
1.976     raeburn  8115:     return $is_adv;
                   8116: }
1.798     raeburn  8117: 
1.1035    raeburn  8118: sub check_can_request {
1.1172.2.146.  .13(raeb 8119:-23):     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  8120:     my $canreq = 0;
1.1172.2.146.  .13(raeb 8121:-23):     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8122:-23):         $uname = $env{'user.name'};
                   8123:-23):         $udom = $env{'user.domain'};
                   8124:-23):     }
1.1035    raeburn  8125:     my ($types,$typename) = &Apache::loncommon::course_types();
                   8126:     my @options = ('approval','validate','autolimit');
                   8127:     my $optregex = join('|',@options);
                   8128:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   8129:         foreach my $type (@{$types}) {
1.1172.2.146.  .13(raeb 8130:-23):             if (&usertools_access($uname,$udom,$type,undef,
                   8131:-23):                                   'requestcourses')) {
1.1035    raeburn  8132:                 $canreq ++;
1.1036    raeburn  8133:                 if (ref($request_domains) eq 'HASH') {
1.1172.2.146.  .13(raeb 8134:-23):                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  8135:                 }
1.1172.2.146.  .13(raeb 8136:-23):                 if ($dom eq $udom) {
1.1035    raeburn  8137:                     $can_request->{$type} = 1;
                   8138:                 }
                   8139:             }
1.1172.2.146.  .13(raeb 8140:-23):             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   8141:-23):                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  8142:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   8143:                 if (@curr > 0) {
1.1036    raeburn  8144:                     foreach my $item (@curr) {
                   8145:                         if (ref($request_domains) eq 'HASH') {
                   8146:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   8147:                             if ($otherdom ne '') {
                   8148:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   8149:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   8150:                                         push(@{$request_domains->{$type}},$otherdom);
                   8151:                                     }
                   8152:                                 } else {
                   8153:                                     push(@{$request_domains->{$type}},$otherdom);
                   8154:                                 }
                   8155:                             }
                   8156:                         }
                   8157:                     }
1.1172.2.146.  .13(raeb 8158:-23):                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  8159:                         $canreq ++;
1.1035    raeburn  8160:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   8161:                             $can_request->{$type} = 1;
                   8162:                         }
                   8163:                     }
                   8164:                 }
                   8165:             }
                   8166:         }
                   8167:     }
                   8168:     return $canreq;
                   8169: }
                   8170: 
1.341     www      8171: # ---------------------------------------------- Custom access rule evaluation
                   8172: 
                   8173: sub customaccess {
                   8174:     my ($priv,$uri)=@_;
1.807     albertel 8175:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      8176:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 8177:     $udom = &LONCAPA::clean_domain($udom);
                   8178:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      8179:     my $access=0;
1.800     albertel 8180:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 8181: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   8182: 	if ($type eq 'user') {
                   8183: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 8184: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 8185: 		if ($tdom) {
                   8186: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   8187: 		}
1.896     albertel 8188: 		if ($tuname) {
                   8189: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 8190: 		}
                   8191: 		$access=($effect eq 'allow');
                   8192: 		last;
                   8193: 	    }
                   8194: 	} else {
                   8195: 	    if ($role) {
                   8196: 		if ($role ne $urole) { next; }
                   8197: 	    }
                   8198: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   8199: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   8200: 		if ($tdom) {
                   8201: 		    if ($tdom ne $udom) { next; }
                   8202: 		}
                   8203: 		if ($tcrs) {
                   8204: 		    if ($tcrs ne $ucrs) { next; }
                   8205: 		}
                   8206: 		if ($tsec) {
                   8207: 		    if ($tsec ne $usec) { next; }
                   8208: 		}
                   8209: 		$access=($effect eq 'allow');
                   8210: 		last;
                   8211: 	    }
                   8212: 	    if ($realm eq '' && $role eq '') {
                   8213: 		$access=($effect eq 'allow');
                   8214: 	    }
1.402     bowersj2 8215: 	}
1.341     www      8216:     }
                   8217:     return $access;
                   8218: }
                   8219: 
1.103     harris41 8220: # ------------------------------------------------- Check for a user privilege
1.12      www      8221: 
                   8222: sub allowed {
1.1172.2.146.  .1(raebu 8223:22):     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705     albertel 8224:     my $ver_orguri=$uri;
1.439     www      8225:     $uri=&deversion($uri);
1.152     www      8226:     my $orguri=$uri;
1.52      www      8227:     $uri=&declutter($uri);
1.809     raeburn  8228: 
1.810     raeburn  8229:     if ($priv eq 'evb') {
1.1172.2.146.  .3(raebu 8230:22): # Evade communication block restrictions for specified role in a course or domain
1.810     raeburn  8231:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   8232:             return $1;
                   8233:         } else {
                   8234:             return;
                   8235:         }
                   8236:     }
                   8237: 
1.620     albertel 8238:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      8239: # Free bre access to adm and meta resources
1.1172.2.146.  .1(raebu 8240:22):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 8241: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   8242: 	&& ($priv eq 'bre')) {
1.14      www      8243: 	return 'F';
1.159     www      8244:     }
                   8245: 
1.545     banghart 8246: # Free bre access to user's own portfolio contents
1.714     raeburn  8247:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  8248:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  8249: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8250:         my %setters;
1.1172.2.142  raeburn  8251:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   8252:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   8253:         if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  8254:             return 'B';
                   8255:         } else {
                   8256:             return 'F';
                   8257:         }
1.545     banghart 8258:     }
                   8259: 
1.762     raeburn  8260: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8261:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8262:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8263:         if (exists($env{'request.course.id'})) {
                   8264:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8265:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8266:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8267:                 my $courseprivid=$env{'request.course.id'};
                   8268:                 $courseprivid=~s/\_/\//;
                   8269:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8270:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8271:                     return $1; 
1.762     raeburn  8272:                 } else {
                   8273:                     if ($env{'request.course.sec'}) {
                   8274:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8275:                     }
                   8276:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8277:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8278:                         return $2;
                   8279:                     }
1.714     raeburn  8280:                 }
                   8281:             }
                   8282:         }
                   8283:     }
                   8284: 
1.159     www      8285: # Free bre to public access
                   8286: 
                   8287:     if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8288:22):         my $copyright;
                   8289:22):         unless ($uri =~ /ext\.tool/) {
                   8290:22):             $copyright=&metadata($uri,'copyright');
                   8291:22):         }
1.620     albertel 8292: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8293:            return 'F'; 
                   8294:         }
1.238     www      8295:         if ($copyright eq 'priv') {
                   8296:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8297: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8298: 		return '';
                   8299:             }
                   8300:         }
                   8301:         if ($copyright eq 'domain') {
                   8302:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8303: 	    unless (($env{'user.domain'} eq $1) ||
                   8304:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8305: 		return '';
                   8306:             }
1.262     matthew  8307:         }
1.620     albertel 8308:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8309:             # Library role, so allow browsing of resources in this domain.
                   8310:             return 'F';
1.238     www      8311:         }
1.341     www      8312:         if ($copyright eq 'custom') {
                   8313: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8314:         }
1.14      www      8315:     }
1.264     matthew  8316:     # Domain coordinator is trying to create a course
1.620     albertel 8317:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8318:         # uri is the requested domain in this case.
                   8319:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8320:         # a role of dc for the domain in question.
1.620     albertel 8321:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8322:     }
1.29      www      8323: 
1.52      www      8324:     my $thisallowed='';
                   8325:     my $statecond=0;
                   8326:     my $courseprivid='';
                   8327: 
1.1039    raeburn  8328:     my $ownaccess;
1.1043    raeburn  8329:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8330:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8331:         if ($uri eq '') {
                   8332:             $ownaccess = 1;
                   8333:         } else {
                   8334:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8335:                 my $udom = $env{'user.domain'};
                   8336:                 my $uname = $env{'user.name'};
                   8337:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8338:                     $ownaccess = 1;
1.1040    raeburn  8339:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8340:                     unless ($uri =~ m{\.\./}) {
                   8341:                         $ownaccess = 1;
                   8342:                     }
                   8343:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8344:                     my $now = time;
                   8345:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8346:                         my $adom = $1;
                   8347:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8348:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142  raeburn  8349:                                 my ($start,$end) = split(/\./,$env{$key});
                   8350:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  8351:                                     $ownaccess = 1;
                   8352:                                     last;
                   8353:                                 }
                   8354:                             }
                   8355:                         }
                   8356:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8357:                         my $adom = $1;
                   8358:                         my $aname = $2;
1.1042    raeburn  8359:                         foreach my $role ('ca','aa') { 
                   8360:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8361:                                 my ($start,$end) =
1.1172.2.142  raeburn  8362:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8363:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8364:                                     $ownaccess = 1;
                   8365:                                     last;
                   8366:                                 }
1.1039    raeburn  8367:                             }
                   8368:                         }
                   8369:                     }
                   8370:                 }
                   8371:             }
                   8372:         }
                   8373:     }
                   8374: 
1.52      www      8375: # Course
                   8376: 
1.620     albertel 8377:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8378:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8379:             $thisallowed.=$1;
                   8380:         }
1.52      www      8381:     }
1.29      www      8382: 
1.52      www      8383: # Domain
                   8384: 
1.620     albertel 8385:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8386:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8387:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8388:             $thisallowed.=$1;
                   8389:         }
1.12      www      8390:     }
1.52      www      8391: 
1.1141    raeburn  8392: # User who is not author or co-author might still be able to edit
                   8393: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8394:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8395:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8396:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8397:             $thisallowed.=$1;
                   8398:         }
                   8399:     }
                   8400: 
1.52      www      8401: # Course: uri itself is a course
1.66      www      8402:     my $courseuri=$uri;
                   8403:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8404:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8405: 
1.620     albertel 8406:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8407:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8408:         if ($priv eq 'mip') {
                   8409:             my $rem = $1;
                   8410:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8411:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8412:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8413:                 if ($cdom ne '') {
                   8414:                     my %passwdconf = &get_passwdconf($cdom);
                   8415:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8416:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8417:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8418:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8419:                                 unless (@inststatuses) {
                   8420:                                     @inststatuses = ('default');
                   8421:                                 }
                   8422:                                 foreach my $status (@inststatuses) {
                   8423:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8424:                                         $thisallowed.=$rem;
                   8425:                                     }
                   8426:                                 }
                   8427:                             }
                   8428:                         }
                   8429:                     }
                   8430:                 }
                   8431:             }
                   8432:         } else {
                   8433:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8434:                 $thisallowed.=$1;
                   8435:             }
1.1039    raeburn  8436:         }
1.12      www      8437:     }
1.29      www      8438: 
1.665     albertel 8439: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8440: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8441:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8442: 	$thisallowed='';
1.671     raeburn  8443:         my ($match)=&is_on_map($uri);
                   8444:         if ($match) {
                   8445:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8446:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8447:                 my $value = $1;
1.1172.2.146.  .1(raebu 8448:22):                 my $deeplinkblock;
                   8449:22):                 unless ($nodeeplinkcheck) {
                   8450:22):                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8451:22):                 }
                   8452:22):                 if ($deeplinkblock) {
                   8453:22):                     $thisallowed='D';
                   8454:22):                 } elsif ($noblockcheck) {
1.1172.2.65  raeburn  8455:                     $thisallowed.=$value;
1.1162    raeburn  8456:                 } else {
1.1172.2.126  raeburn  8457:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8458:                     if (@blockers > 0) {
                   8459:                         $thisallowed = 'B';
                   8460:                     } else {
                   8461:                         $thisallowed.=$value;
                   8462:                     }
1.1162    raeburn  8463:                 }
1.671     raeburn  8464:             }
                   8465:         } else {
1.705     albertel 8466:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8467:             if ($refuri) {
                   8468:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8469:                     $thisallowed='F';
1.671     raeburn  8470:                 } else {
                   8471:                     $refuri=&declutter($refuri);
                   8472:                     my ($match) = &is_on_map($refuri);
                   8473:                     if ($match) {
1.1172.2.146.  .1(raebu 8474:22):                         my $deeplinkblock;
                   8475:22):                         unless ($nodeeplinkcheck) {
                   8476:22):                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8477:22):                         }
                   8478:22):                         if ($deeplinkblock) {
                   8479:22):                             $thisallowed='D';
                   8480:22):                         } elsif ($noblockcheck) {
1.1162    raeburn  8481:                             $thisallowed='F';
1.1172.2.65  raeburn  8482:                         } else {
1.1172.2.127  raeburn  8483:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8484:                             if (@blockers > 0) {
                   8485:                                 $thisallowed = 'B';
                   8486:                             } else {
                   8487:                                 $thisallowed='F';
                   8488:                             }
1.1162    raeburn  8489:                         }
1.671     raeburn  8490:                     }
1.669     raeburn  8491:                 }
1.671     raeburn  8492:             }
                   8493:         }
1.314     www      8494:     }
1.492     albertel 8495: 
1.766     albertel 8496:     if ($priv eq 'bre'
                   8497: 	&& $thisallowed ne 'F' 
                   8498: 	&& $thisallowed ne '2'
                   8499: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8500: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8501:     }
                   8502:     
1.52      www      8503: # Full access at system, domain or course-wide level? Exit.
1.29      www      8504:     if ($thisallowed=~/F/) {
                   8505: 	return 'F';
                   8506:     }
                   8507: 
1.52      www      8508: # If this is generating or modifying users, exit with special codes
1.29      www      8509: 
1.643     www      8510:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8511: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8512: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8513: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8514: 	    unless ($auname) { return $thisallowed; }
                   8515: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8516: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8517: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8518: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8519: 	}
1.52      www      8520: 	return $thisallowed;
                   8521:     }
                   8522: #
1.103     harris41 8523: # Gathered so far: system, domain and course wide privileges
1.52      www      8524: #
                   8525: # Course: See if uri or referer is an individual resource that is part of 
                   8526: # the course
                   8527: 
1.620     albertel 8528:     if ($env{'request.course.id'}) {
1.232     www      8529: 
1.1172.2.146.  .13(raeb 8530:-23):         if ($priv eq 'bre') {
                   8531:-23):             if (&is_coursetool_logo($uri)) {
                   8532:-23):                 return 'F';
                   8533:-23):             }
                   8534:-23):         }
                   8535:-23): 
1.1172.2.115  raeburn  8536: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8537: 
                   8538:         if ($priv eq 'mip') {
                   8539:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8540:                 return $thisallowed;
                   8541:             } else {
                   8542:                 return '';
                   8543:             }
                   8544:         }
                   8545: 
1.620     albertel 8546:        $courseprivid=$env{'request.course.id'};
                   8547:        if ($env{'request.course.sec'}) {
                   8548:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8549:        }
                   8550:        $courseprivid=~s/\_/\//;
                   8551:        my $checkreferer=1;
1.232     www      8552:        my ($match,$cond)=&is_on_map($uri);
                   8553:        if ($match) {
                   8554:            $statecond=$cond;
1.620     albertel 8555:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8556:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8557:                my $value = $1;
                   8558:                if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8559:22):                    my $deeplinkblock;
                   8560:22):                    unless ($nodeeplinkcheck) {
                   8561:22):                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8562:22):                    }
                   8563:22):                    if ($deeplinkblock) {
                   8564:22):                        $thisallowed = 'D';
                   8565:22):                    } elsif ($noblockcheck) {
1.1162    raeburn  8566:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8567:                    } else {
1.1172.2.126  raeburn  8568:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8569:                        if (@blockers > 0) {
                   8570:                            $thisallowed = 'B';
                   8571:                        } else {
                   8572:                            $thisallowed.=$value;
                   8573:                        }
1.1162    raeburn  8574:                    }
                   8575:                } else {
                   8576:                    $thisallowed.=$value;
                   8577:                }
1.52      www      8578:                $checkreferer=0;
                   8579:            }
1.29      www      8580:        }
1.1172.2.126  raeburn  8581: 
1.148     www      8582:        if ($checkreferer) {
1.620     albertel 8583: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8584:             unless ($refuri) {
1.800     albertel 8585:                 foreach my $key (keys(%env)) {
                   8586: 		    if ($key=~/^httpref\..*\*/) {
                   8587: 			my $pattern=$key;
1.156     www      8588:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8589:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8590:                         $pattern=~s/\//\\\//g;
1.152     www      8591:                         if ($orguri=~/$pattern/) {
1.800     albertel 8592: 			    $refuri=$env{$key};
1.148     www      8593:                         }
                   8594:                     }
1.191     harris41 8595:                 }
1.148     www      8596:             }
1.232     www      8597: 
1.148     www      8598:          if ($refuri) { 
1.152     www      8599: 	  $refuri=&declutter($refuri);
1.232     www      8600:           my ($match,$cond)=&is_on_map($refuri);
                   8601:             if ($match) {
                   8602:               my $refstatecond=$cond;
1.620     albertel 8603:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8604:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8605:                   my $value = $1;
                   8606:                   if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8607:22):                       my $deeplinkblock;
                   8608:22):                       unless ($nodeeplinkcheck) {
                   8609:22):                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8610:22):                       }
                   8611:22):                       if ($deeplinkblock) {
                   8612:22):                           $thisallowed = 'D';
                   8613:22):                       } elsif ($noblockcheck) {
1.1162    raeburn  8614:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8615:                       } else {
1.1172.2.127  raeburn  8616:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8617:                           if (@blockers > 0) {
                   8618:                               $thisallowed = 'B';
                   8619:                           } else {
                   8620:                               $thisallowed.=$value;
                   8621:                           }
1.1162    raeburn  8622:                       }
                   8623:                   } else {
                   8624:                       $thisallowed.=$value;
                   8625:                   }
1.53      www      8626:                   $uri=$refuri;
                   8627:                   $statecond=$refstatecond;
1.52      www      8628:               }
                   8629:           }
1.148     www      8630:         }
1.29      www      8631:        }
1.52      www      8632:    }
1.29      www      8633: 
1.52      www      8634: #
1.103     harris41 8635: # Gathered now: all privileges that could apply, and condition number
1.52      www      8636: # 
                   8637: #
                   8638: # Full or no access?
                   8639: #
1.29      www      8640: 
1.52      www      8641:     if ($thisallowed=~/F/) {
                   8642: 	return 'F';
                   8643:     }
1.29      www      8644: 
1.52      www      8645:     unless ($thisallowed) {
                   8646:         return '';
                   8647:     }
1.29      www      8648: 
1.52      www      8649: # Restrictions exist, deal with them
                   8650: #
                   8651: #   C:according to course preferences
                   8652: #   R:according to resource settings
                   8653: #   L:unless locked
                   8654: #   X:according to user session state
                   8655: #
                   8656: 
                   8657: # Possibly locked functionality, check all courses
1.1172.2.142  raeburn  8658: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      8659: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142  raeburn  8660: # courses, and 2 minutes for current course, in which user has st or ta role
                   8661: # which is neither expired nor a future role (unless current course).
1.52      www      8662: 
1.1172.2.142  raeburn  8663:     my ($needlockcheck,$now,$crsonly);
1.52      www      8664:     if ($thisallowed=~/L/) {
1.1172.2.142  raeburn  8665:         $now = time;
                   8666:         if ($priv eq 'bre') {
                   8667:             if ($uri ne '') {
                   8668:                 if ($orguri =~ m{^/+res/}) {
                   8669:                     if ($uri =~ m{^lib/templates/}) {
                   8670:                         if ($env{'request.course.id'}) {
                   8671:                             $crsonly = 1;
                   8672:                             $needlockcheck = 1;
                   8673:                         }
                   8674:                     } else {
                   8675:                         $needlockcheck = 1;
                   8676:                     }
                   8677:                 } elsif ($env{'request.course.id'}) {
                   8678:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   8679:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   8680:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   8681:                         $crsonly = 1;
                   8682:                     }
                   8683:                     $needlockcheck = 1;
                   8684:                 }
                   8685:             }
                   8686:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   8687:             $needlockcheck = 1;
                   8688:         }
                   8689:     }
                   8690:     if ($needlockcheck) {
                   8691:         foreach my $envkey (keys(%env)) {
1.54      www      8692:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8693:                my $courseid=$2;
                   8694:                my $roleid=$1.'.'.$2;
1.92      www      8695:                $courseid=~s/^\///;
1.1172.2.142  raeburn  8696:                unless ($env{'request.role'} eq $roleid) {
                   8697:                    my ($start,$end) = split(/\./,$env{$envkey});
                   8698:                    next unless (($now >= $start) && (!$end || $end > $now));
                   8699:                }
1.54      www      8700:                my $expiretime=600;
1.620     albertel 8701:                if ($env{'request.role'} eq $roleid) {
1.54      www      8702: 		  $expiretime=120;
                   8703:                }
                   8704: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8705:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8706:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8707: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8708:                }
1.620     albertel 8709:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8710:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8711: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8712:                        &log($env{'user.domain'},$env{'user.name'},
                   8713:                             $env{'user.home'},
1.57      www      8714:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8715:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8716:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8717: 		       return '';
                   8718:                    }
                   8719:                }
1.620     albertel 8720:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8721:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142  raeburn  8722: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 8723:                        &log($env{'user.domain'},$env{'user.name'},
                   8724:                             $env{'user.home'},
1.57      www      8725:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8726:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8727:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8728: 		       return '';
                   8729:                    }
                   8730:                }
                   8731: 	   }
1.29      www      8732:        }
1.52      www      8733:     }
1.1172.2.126  raeburn  8734: 
1.52      www      8735: #
                   8736: # Rest of the restrictions depend on selected course
                   8737: #
                   8738: 
1.620     albertel 8739:     unless ($env{'request.course.id'}) {
1.766     albertel 8740: 	if ($thisallowed eq 'A') {
                   8741: 	    return 'A';
1.814     raeburn  8742:         } elsif ($thisallowed eq 'B') {
                   8743:             return 'B';
1.766     albertel 8744: 	} else {
                   8745: 	    return '1';
                   8746: 	}
1.52      www      8747:     }
1.29      www      8748: 
1.52      www      8749: #
                   8750: # Now user is definitely in a course
                   8751: #
1.53      www      8752: 
                   8753: 
                   8754: # Course preferences
                   8755: 
                   8756:    if ($thisallowed=~/C/) {
1.620     albertel 8757:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8758:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8759:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8760: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8761: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8762: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8763: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8764: 			$env{'request.course.id'});
                   8765: 	   }
1.237     www      8766:            return '';
                   8767:        }
                   8768: 
1.620     albertel 8769:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8770: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8771: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8772: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8773: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8774: 			$env{'request.course.id'});
                   8775: 	   }
1.54      www      8776:            return '';
                   8777:        }
1.53      www      8778:    }
                   8779: 
                   8780: # Resource preferences
                   8781: 
                   8782:    if ($thisallowed=~/R/) {
1.620     albertel 8783:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8784:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8785: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8786: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8787: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8788: 	   }
                   8789: 	   return '';
1.54      www      8790:        }
1.53      www      8791:    }
1.30      www      8792: 
1.1172.2.146.  .1(raebu 8793:22): # Restricted for deeplinked session?
                   8794:22): 
                   8795:22):     if ($env{'request.deeplink.login'}) {
                   8796:22):         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
                   8797:22):             if (!$symb) { $symb=&symbread($uri,1); }
                   8798:22):             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
                   8799:22):                 return '';
                   8800:22):             }
                   8801:22):         }
                   8802:22):     }
                   8803:22): 
1.246     www      8804: # Restricted by state or randomout?
1.30      www      8805: 
1.52      www      8806:    if ($thisallowed=~/X/) {
1.620     albertel 8807:       if ($env{'acc.randomout'}) {
1.579     albertel 8808: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8809:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8810:             return ''; 
                   8811:          }
1.247     www      8812:       }
                   8813:       if (&condval($statecond)) {
1.52      www      8814: 	 return '2';
                   8815:       } else {
                   8816:          return '';
                   8817:       }
                   8818:    }
1.30      www      8819: 
1.766     albertel 8820:     if ($thisallowed eq 'A') {
                   8821: 	return 'A';
1.814     raeburn  8822:     } elsif ($thisallowed eq 'B') {
                   8823:         return 'B';
1.1172.2.146.  .1(raebu 8824:22):     } elsif ($thisallowed eq 'D') {
                   8825:22):         return 'D';
1.766     albertel 8826:     }
1.52      www      8827:    return 'F';
1.232     www      8828: }
1.1162    raeburn  8829: 
1.1172.2.13  raeburn  8830: # ------------------------------------------- Check construction space access
                   8831: 
                   8832: sub constructaccess {
                   8833:     my ($url,$setpriv)=@_;
                   8834: 
                   8835: # We do not allow editing of previous versions of files
                   8836:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8837: 
                   8838: # Get username and domain from URL
                   8839:     my ($ownername,$ownerdomain,$ownerhome);
                   8840: 
                   8841:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8842:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8843: 
                   8844: # The URL does not really point to any authorspace, forget it
                   8845:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8846: 
                   8847: # Now we need to see if the user has access to the authorspace of
                   8848: # $ownername at $ownerdomain
                   8849: 
                   8850:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8851: # Real author for this?
                   8852:        $ownerhome = $env{'user.home'};
                   8853:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8854:           return ($ownername,$ownerdomain,$ownerhome);
                   8855:        }
                   8856:     } else {
                   8857: # Co-author for this?
                   8858:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8859:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8860:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8861:             return ($ownername,$ownerdomain,$ownerhome);
                   8862:         }
                   8863:     }
                   8864: 
                   8865: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8866: # we might as well leave
                   8867:    unless ($setpriv) { return ''; }
                   8868: 
                   8869: # Backdoor access?
                   8870:     my $allowed=&allowed('eco',$ownerdomain);
                   8871: # Nope
                   8872:     unless ($allowed) { return ''; }
                   8873: # Looks like we may have access, but could be locked by the owner of the construction space
                   8874:     if ($allowed eq 'U') {
                   8875:         my %blocked=&get('environment',['domcoord.author'],
                   8876:                          $ownerdomain,$ownername);
                   8877: # Is blocked by owner
                   8878:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8879:     }
                   8880:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8881: # Grant temporary access
                   8882:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8883:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8884:         if (!$update) { $update = $then; }
                   8885:         my $refresh=$env{'user.refresh.time'};
                   8886:         if (!$refresh) { $refresh = $update; }
                   8887:         my $now = time;
                   8888:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8889:                            $now,'ca','constructaccess');
                   8890:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8891:         return($ownername,$ownerdomain,$ownerhome);
                   8892:     }
                   8893: # No business here
                   8894:     return '';
                   8895: }
                   8896: 
1.1172.2.66  raeburn  8897: # ----------------------------------------------------------- Content Blocking
                   8898: 
                   8899: {
                   8900: # Caches for faster Course Contents display where content blocking
                   8901: # is in operation (i.e., interval param set) for timed quiz.
                   8902: #
                   8903: # User for whom data are being temporarily cached.
                   8904: my $cacheduser='';
1.1172.2.126  raeburn  8905: # Course for which data are being temporarily cached.
                   8906: my $cachedcid='';
1.1172.2.66  raeburn  8907: # Cached blockers for this user (a hash of blocking items).
                   8908: my %cachedblockers=();
                   8909: # When the data were last cached.
                   8910: my $cachedlast='';
                   8911: 
                   8912: sub load_all_blockers {
1.1172.2.128  raeburn  8913:     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8914:     if (($uname ne '') && ($udom ne '')) {
                   8915:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126  raeburn  8916:             ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128  raeburn  8917:             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8918:             return;
                   8919:         }
                   8920:     }
                   8921:     $cachedlast=time;
                   8922:     $cacheduser=$uname.':'.$udom;
1.1172.2.126  raeburn  8923:     $cachedcid=$env{'request.course.id'};
1.1172.2.128  raeburn  8924:     %cachedblockers = &get_commblock_resources();
1.1172.2.126  raeburn  8925:     return;
1.1172.2.66  raeburn  8926: }
                   8927: 
1.1162    raeburn  8928: sub get_comm_blocks {
                   8929:     my ($cdom,$cnum) = @_;
                   8930:     if ($cdom eq '' || $cnum eq '') {
                   8931:         return unless ($env{'request.course.id'});
                   8932:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8933:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8934:     }
                   8935:     my %commblocks;
                   8936:     my $hashid=$cdom.'_'.$cnum;
                   8937:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8938:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8939:         %commblocks = %{$blocksref};
                   8940:     } else {
                   8941:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8942:         my $cachetime = 600;
                   8943:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8944:     }
                   8945:     return %commblocks;
                   8946: }
                   8947: 
1.1172.2.66  raeburn  8948: sub get_commblock_resources {
                   8949:     my ($blocks) = @_;
                   8950:     my %blockers = ();
                   8951:     return %blockers unless ($env{'request.course.id'});
1.1172.2.142  raeburn  8952:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8953:     if ($env{'request.course.sec'}) {
                   8954:         $courseurl .= '/'.$env{'request.course.sec'};
                   8955:     }
                   8956:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  8957:     my %commblocks;
                   8958:     if (ref($blocks) eq 'HASH') {
                   8959:         %commblocks = %{$blocks};
                   8960:     } else {
                   8961:         %commblocks = &get_comm_blocks();
                   8962:     }
1.1172.2.66  raeburn  8963:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8964:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8965:     return %blockers unless (ref($navmap));
                   8966:     my $now = time;
1.1162    raeburn  8967:     foreach my $block (keys(%commblocks)) {
                   8968:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8969:             my ($start,$end) = ($1,$2);
                   8970:             if ($start <= $now && $end >= $now) {
                   8971:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8972:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8973:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8974:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8975:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8976:                             }
                   8977:                         }
                   8978:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8979:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8980:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8981:                             }
                   8982:                         }
                   8983:                     }
                   8984:                 }
                   8985:             }
                   8986:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8987:             my $item = $1;
                   8988:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8989:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142  raeburn  8990:                     my (@interval,$mapname);
1.1172.2.66  raeburn  8991:                     my $type = 'map';
                   8992:                     if ($item eq 'course') {
                   8993:                         $type = 'course';
                   8994:                         @interval=&EXT("resource.0.interval");
                   8995:                     } else {
                   8996:                         if ($item =~ /___\d+___/) {
                   8997:                             $type = 'resource';
                   8998:                             @interval=&EXT("resource.0.interval",$item);
1.1162    raeburn  8999:                         } else {
1.1172.2.142  raeburn  9000:                             $mapname = &deversion($item);
                   9001:                             if (ref($navmap)) {
                   9002:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
                   9003:                                 @interval = ($timelimit,'map');
1.1162    raeburn  9004:                             }
                   9005:                         }
1.1172.2.66  raeburn  9006:                     }
1.1172.2.146.  .1(raebu 9007:22):                     if ($interval[0] =~ /^(\d+)/) {
                   9008:22):                         my $timelimit = $1;
1.1172.2.66  raeburn  9009:                         my $first_access;
                   9010:                         if ($type eq 'resource') {
                   9011:                             $first_access=&get_first_access($interval[1],$item);
                   9012:                         } elsif ($type eq 'map') {
                   9013:                             $first_access=&get_first_access($interval[1],undef,$item);
                   9014:                         } else {
                   9015:                             $first_access=&get_first_access($interval[1]);
                   9016:                         }
                   9017:                         if ($first_access) {
1.1172.2.146.  .1(raebu 9018:22):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  9019:                             if ($timesup > $now) {
                   9020:                                 my $activeblock;
1.1172.2.142  raeburn  9021:                                 if ($type eq 'resource') {
                   9022:                                     if (ref($navmap)) {
                   9023:                                         my $res = $navmap->getBySymb($item);
                   9024:                                         if ($res->answerable()) {
                   9025:                                             $activeblock = 1;
                   9026:                                         }
                   9027:                                     }
                   9028:                                 } elsif ($type eq 'map') {
                   9029:                                     my $mapsymb = &symbread($mapname,1);
                   9030:                                     if (($mapsymb) && (ref($navmap))) {
                   9031:                                         my $mapres = $navmap->getBySymb($mapsymb);
                   9032:                                         if (ref($mapres)) {
                   9033:                                             my $first = $mapres->map_start();
                   9034:                                             my $finish = $mapres->map_finish();
                   9035:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   9036:                                             if (ref($it)) {
                   9037:                                                 my $res;
                   9038:                                                 while ($res = $it->next(undef,1)) {
                   9039:                                                     next unless (ref($res));
                   9040:                                                     my $symb = $res->symb();
                   9041:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
                   9042:                                                     @interval=&EXT("resource.0.interval",$symb);
                   9043:                                                     if ($interval[1] eq 'map') {
                   9044:                                                         if ($res->answerable()) {
                   9045:                                                             $activeblock = 1;
                   9046:                                                             last;
                   9047:                                                         }
                   9048:                                                     }
                   9049:                                                 }
                   9050:                                             }
                   9051:                                         }
1.1172.2.66  raeburn  9052:                                     }
                   9053:                                 }
                   9054:                                 if ($activeblock) {
                   9055:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   9056:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   9057:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   9058:                                          }
                   9059:                                     }
                   9060:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   9061:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   9062:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  9063:                                         }
1.1162    raeburn  9064:                                     }
                   9065:                                 }
                   9066:                             }
                   9067:                         }
                   9068:                     }
                   9069:                 }
                   9070:             }
                   9071:         }
                   9072:     }
1.1172.2.66  raeburn  9073:     return %blockers;
1.1162    raeburn  9074: }
                   9075: 
1.1172.2.66  raeburn  9076: sub has_comm_blocking {
1.1172.2.128  raeburn  9077:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  9078:     my @blockers;
                   9079:     return unless ($env{'request.course.id'});
                   9080:     return unless ($priv eq 'bre');
                   9081:     return if ($env{'request.state'} eq 'construct');
1.1172.2.142  raeburn  9082:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   9083:     if ($env{'request.course.sec'}) {
                   9084:         $courseurl .= '/'.$env{'request.course.sec'};
                   9085:     }
                   9086:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128  raeburn  9087:     my %blockinfo;
                   9088:     if (ref($blocks) eq 'HASH') {
                   9089:         %blockinfo = &get_commblock_resources($blocks);
                   9090:     } else {
                   9091:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   9092:         %blockinfo = %cachedblockers;
                   9093:     }
                   9094:     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  9095:     my (%possibles,@symbs);
                   9096:     if (!$symb) {
1.1172.2.128  raeburn  9097:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  9098:     }
1.1172.2.66  raeburn  9099:     if ($symb) {
                   9100:         @symbs = ($symb);
                   9101:     } elsif (keys(%possibles)) {
                   9102:         @symbs = keys(%possibles);
                   9103:     }
                   9104:     my $noblock;
                   9105:     foreach my $symb (@symbs) {
                   9106:         last if ($noblock);
                   9107:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128  raeburn  9108:         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  9109:             if ($block =~ /^firstaccess____(.+)$/) {
                   9110:                 my $item = $1;
1.1172.2.126  raeburn  9111:                 unless ($blocked) {
                   9112:                     if (($item eq $map) || ($item eq $symb)) {
                   9113:                         $noblock = 1;
                   9114:                         last;
                   9115:                     }
1.1172.2.66  raeburn  9116:                 }
1.1162    raeburn  9117:             }
1.1172.2.128  raeburn  9118:             if (ref($blockinfo{$block}) eq 'HASH') {
                   9119:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   9120:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  9121:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9122:                             push(@blockers,$block);
                   9123:                         }
                   9124:                     }
                   9125:                 }
1.1172.2.128  raeburn  9126:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   9127:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126  raeburn  9128:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9129:                             push(@blockers,$block);
                   9130:                         }
1.1172.2.66  raeburn  9131:                     }
                   9132:                 }
1.1162    raeburn  9133:             }
                   9134:         }
                   9135:     }
1.1172.2.126  raeburn  9136:     unless ($noblock) {
                   9137:         return @blockers;
                   9138:     }
                   9139:     return;
1.1172.2.66  raeburn  9140: }
1.1162    raeburn  9141: }
                   9142: 
1.1172.2.146.  .1(raebu 9143:22): sub deeplink_check {
                   9144:22):     my ($priv,$symb,$uri) = @_;
                   9145:22):     return unless ($env{'request.course.id'});
                   9146:22):     return unless ($priv eq 'bre');
                   9147:22):     return if ($env{'request.state'} eq 'construct');
                   9148:22):     return if ($env{'request.role.adv'});
                   9149:22):     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9150:22):     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9151:22):     my (%possibles,@symbs);
                   9152:22):     if (!$symb) {
                   9153:22):         $symb = &symbread($uri,1,1,1,\%possibles);
                   9154:22):     }
                   9155:22):     if ($symb) {
                   9156:22):         @symbs = ($symb);
                   9157:22):     } elsif (keys(%possibles)) {
                   9158:22):         @symbs = keys(%possibles);
                   9159:22):     }
                   9160:22): 
                   9161:22):     my ($deeplink_symb,$allow);
                   9162:22):     if ($env{'request.deeplink.login'}) {
                   9163:22):         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
                   9164:22):     }
                   9165:22):     foreach my $symb (@symbs) {
                   9166:22):         last if ($allow);
                   9167:22):         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   9168:22):         if ($deeplink eq '') {
                   9169:22):             $allow = 1;
                   9170:22):         } else {
                   9171:22):             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
                   9172:22):             if ($state ne 'only') {
                   9173:22):                 $allow = 1;
                   9174:22):             } else {
                   9175:22):                 my $check_deeplink_entry;
                   9176:22):                 if ($protect ne 'none') {
                   9177:22):                     my ($acctype,$item) = split(/:/,$protect);
                   9178:22):                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
                   9179:22):                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
                   9180:22):                             $check_deeplink_entry = 1
                   9181:22):                         }
                   9182:22):                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
                   9183:22):                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
                   9184:22):                             $check_deeplink_entry = 1;
                   9185:22):                         }
                   9186:22):                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   9187:22):                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   9188:22):                             $check_deeplink_entry = 1;
                   9189:22):                         }
                   9190:22):                     }
                   9191:22):                 }
                   9192:22):                 if (($protect eq 'none') || ($check_deeplink_entry)) {
                   9193:22):                     if ($scope eq 'res') {
                   9194:22):                         if ($symb eq $deeplink_symb) {
                   9195:22):                             $allow = 1;
                   9196:22):                         }
                   9197:22):                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
                   9198:22):                         my ($map_from_symb,$map_from_login);
                   9199:22):                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
                   9200:22):                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9201:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
                   9202:22):                         } else {
                   9203:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
                   9204:22):                         }
                   9205:22):                         if (($map_from_symb) && ($map_from_login)) {
                   9206:22):                             if ($map_from_symb eq $map_from_login) {
                   9207:22):                                 $allow = 1;
                   9208:22):                             } elsif ($scope eq 'rec') {
                   9209:22):                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
                   9210:22):                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
                   9211:22):                                     $allow = 1;
                   9212:22):                                 }
                   9213:22):                             }
                   9214:22):                         }
                   9215:22):                     }
                   9216:22):                 }
                   9217:22):             }
                   9218:22):         }
                   9219:22):     }
                   9220:22):     return if ($allow);
                   9221:22):     return 1;
                   9222:22): }
                   9223:22): 
1.1172.2.66  raeburn  9224: # -------------------------------- Deversion and split uri into path an filename
                   9225: 
1.1133    foxr     9226: #
1.1172.2.66  raeburn  9227: #   Removes the version from a URI and
1.1133    foxr     9228: #   splits it in to its filename and path to the filename.
                   9229: #   Seems like File::Basename could have done this more clearly.
                   9230: #   Parameters:
                   9231: #      $uri   - input URI
                   9232: #   Returns:
                   9233: #     Two element list consisting of 
                   9234: #     $pathname  - the URI up to and excluding the trailing /
                   9235: #     $filename  - The part of the URI following the last /
                   9236: #  NOTE:
                   9237: #    Another realization of this is simply:
                   9238: #    use File::Basename;
                   9239: #    ...
                   9240: #    $uri = shift;
                   9241: #    $filename = basename($uri);
                   9242: #    $path     = dirname($uri);
                   9243: #    return ($filename, $path);
                   9244: #
                   9245: #     The implementation below is probably faster however.
                   9246: #
1.710     albertel 9247: sub split_uri_for_cond {
                   9248:     my $uri=&deversion(&declutter(shift));
                   9249:     my @uriparts=split(/\//,$uri);
                   9250:     my $filename=pop(@uriparts);
                   9251:     my $pathname=join('/',@uriparts);
                   9252:     return ($pathname,$filename);
                   9253: }
1.232     www      9254: # --------------------------------------------------- Is a resource on the map?
                   9255: 
                   9256: sub is_on_map {
1.710     albertel 9257:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 9258:     #Trying to find the conditional for the file
1.620     albertel 9259:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 9260: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      9261:     if ($match) {
1.289     bowersj2 9262: 	return (1,$1);
                   9263:     } else {
1.434     www      9264: 	return (0,0);
1.289     bowersj2 9265:     }
1.12      www      9266: }
                   9267: 
1.427     www      9268: # --------------------------------------------------------- Get symb from alias
                   9269: 
                   9270: sub get_symb_from_alias {
                   9271:     my $symb=shift;
                   9272:     my ($map,$resid,$url)=&decode_symb($symb);
                   9273: # Already is a symb
                   9274:     if ($url) { return $symb; }
                   9275: # Must be an alias
                   9276:     my $aliassymb='';
                   9277:     my %bighash;
1.620     albertel 9278:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      9279:                             &GDBM_READER(),0640)) {
                   9280:         my $rid=$bighash{'mapalias_'.$symb};
                   9281: 	if ($rid) {
                   9282: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 9283: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   9284: 				    $resid,$bighash{'src_'.$rid});
1.427     www      9285: 	}
                   9286:         untie %bighash;
                   9287:     }
                   9288:     return $aliassymb;
                   9289: }
                   9290: 
1.12      www      9291: # ----------------------------------------------------------------- Define Role
                   9292: 
                   9293: sub definerole {
                   9294:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  9295:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9296:     foreach my $role (split(':',$sysrole)) {
                   9297: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9298:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9299:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9300: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9301:                return "refused:s:$crole&$cqual"; 
                   9302:             }
                   9303:         }
1.191     harris41 9304:     }
1.800     albertel 9305:     foreach my $role (split(':',$domrole)) {
                   9306: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9307:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9308:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9309: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9310:                return "refused:d:$crole&$cqual"; 
                   9311:             }
                   9312:         }
1.191     harris41 9313:     }
1.800     albertel 9314:     foreach my $role (split(':',$courole)) {
                   9315: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9316:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9317:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9318: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9319:                return "refused:c:$crole&$cqual"; 
                   9320:             }
                   9321:         }
1.191     harris41 9322:     }
1.1172.2.84  raeburn  9323:     my $uhome;
                   9324:     if (($uname ne '') && ($udom ne '')) {
                   9325:         $uhome = &homeserver($uname,$udom);
                   9326:         return $uhome if ($uhome eq 'no_host');
                   9327:     } else {
                   9328:         $uname = $env{'user.name'};
                   9329:         $udom = $env{'user.domain'};
                   9330:         $uhome = $env{'user.home'};
                   9331:     }
1.620     albertel 9332:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  9333:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9334:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  9335:     return reply($command,$uhome);
1.12      www      9336:   } else {
                   9337:     return 'refused';
                   9338:   }
1.105     harris41 9339: }
                   9340: 
                   9341: # ---------------- Make a metadata query against the network of library servers
                   9342: 
                   9343: sub metadata_query {
1.1172.2.33  raeburn  9344:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9345:     my %rhash;
1.845     albertel 9346:     my %libserv = &all_library();
1.244     matthew  9347:     my @server_list = (defined($server_array) ? @$server_array
                   9348:                                               : keys(%libserv) );
                   9349:     for my $server (@server_list) {
1.1172.2.33  raeburn  9350:         my $domains = '';
                   9351:         if (ref($domains_hash) eq 'HASH') {
                   9352:             $domains = $domains_hash->{$server};    
                   9353:         }
1.118     harris41 9354: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  9355: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9356: 	    $rhash{$server}=$reply;
                   9357: 	}
                   9358: 	else {
                   9359: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  9360: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9361: 			     $server);
                   9362: 	    $rhash{$server}=$reply;
                   9363: 	}
1.112     harris41 9364:     }
1.118     harris41 9365:     return \%rhash;
1.240     www      9366: }
                   9367: 
                   9368: # ----------------------------------------- Send log queries and wait for reply
                   9369: 
                   9370: sub log_query {
                   9371:     my ($uname,$udom,$query,%filters)=@_;
                   9372:     my $uhome=&homeserver($uname,$udom);
                   9373:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9374:     my $uhost=&hostname($uhome);
1.800     albertel 9375:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9376:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9377:                        $uhome);
1.479     albertel 9378:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9379:     return get_query_reply($queryid);
                   9380: }
                   9381: 
1.818     raeburn  9382: # -------------------------- Update MySQL table for portfolio file
                   9383: 
                   9384: sub update_portfolio_table {
1.821     raeburn  9385:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9386:     if ($group ne '') {
                   9387:         $file_name =~s /^\Q$group\E//;
                   9388:     }
1.818     raeburn  9389:     my $homeserver = &homeserver($uname,$udom);
                   9390:     my $queryid=
1.821     raeburn  9391:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9392:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9393:     my $reply = &get_query_reply($queryid);
                   9394:     return $reply;
                   9395: }
                   9396: 
1.899     raeburn  9397: # -------------------------- Update MySQL allusers table
                   9398: 
                   9399: sub update_allusers_table {
                   9400:     my ($uname,$udom,$names) = @_;
                   9401:     my $homeserver = &homeserver($uname,$udom);
                   9402:     my $queryid=
                   9403:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9404:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9405:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9406:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9407:                'generation='.&escape($names->{'generation'}).'%%'.
                   9408:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9409:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9410:     return;
1.899     raeburn  9411: }
                   9412: 
1.508     raeburn  9413: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9414: 
                   9415: sub fetch_enrollment_query {
1.511     raeburn  9416:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  9417:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9418:     my $maxtries = 1;
1.508     raeburn  9419:     if ($context eq 'automated') {
                   9420:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  9421:         $sleep = 2;
                   9422:         $loopmax = 100;
1.547     raeburn  9423:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9424:     } else {
                   9425:         $homeserver = &homeserver($cnum,$dom);
                   9426:     }
1.838     albertel 9427:     my $host=&hostname($homeserver);
1.506     raeburn  9428:     my $cmd = '';
1.1000    raeburn  9429:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9430:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9431:     }
                   9432:     $cmd =~ s/%%$//;
                   9433:     $cmd = &escape($cmd);
                   9434:     my $query = 'fetchenrollment';
1.620     albertel 9435:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9436:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9437:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9438:         return 'error: '.$queryid;
                   9439:     }
1.1172.2.93  raeburn  9440:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9441:     my $tries = 1;
                   9442:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  9443:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9444:         $tries ++;
                   9445:     }
1.526     raeburn  9446:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9447:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9448:     } else {
1.901     albertel 9449:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  9450:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9451:             foreach my $line (@responses) {
                   9452:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9453:                 $$replyref{$key} = $value;
                   9454:             }
                   9455:         } else {
1.1117    foxr     9456:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9457:             foreach my $line (@responses) {
                   9458:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9459:                 $$replyref{$key} = $value;
                   9460:                 if ($value > 0) {
1.800     albertel 9461:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9462:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9463:                         my $destname = $pathname.'/'.$filename;
                   9464:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9465:                         if ($xml_classlist =~ /^error/) {
                   9466:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9467:                         } else {
1.1172.2.96  raeburn  9468:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9469:                                 print FILE &unescape($xml_classlist);
                   9470:                                 close(FILE);
1.526     raeburn  9471:                             } else {
                   9472:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9473:                             }
                   9474:                         }
                   9475:                     }
                   9476:                 }
                   9477:             }
                   9478:         }
                   9479:         return 'ok';
                   9480:     }
                   9481:     return 'error';
                   9482: }
                   9483: 
1.242     www      9484: sub get_query_reply {
1.1172.2.79  raeburn  9485:     my ($queryid,$sleep,$loopmax) = @_;
                   9486:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9487:         $sleep = 0.2;
                   9488:     }
                   9489:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9490:         $loopmax = 100;
                   9491:     }
1.1117    foxr     9492:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9493:     my $reply='';
1.1172.2.79  raeburn  9494:     for (1..$loopmax) {
                   9495: 	sleep($sleep);
1.240     www      9496:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  9497: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9498: 		$reply = join('',<$fh>);
                   9499: 		close($fh);
1.240     www      9500: 	   } else { return 'error: reply_file_error'; }
1.242     www      9501:            return &unescape($reply);
                   9502: 	}
1.240     www      9503:     }
1.242     www      9504:     return 'timeout:'.$queryid;
1.240     www      9505: }
                   9506: 
                   9507: sub courselog_query {
1.241     www      9508: #
                   9509: # possible filters:
                   9510: # url: url or symb
                   9511: # username
                   9512: # domain
                   9513: # action: view, submit, grade
                   9514: # start: timestamp
                   9515: # end: timestamp
                   9516: #
1.240     www      9517:     my (%filters)=@_;
1.620     albertel 9518:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9519:     if ($filters{'url'}) {
                   9520: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9521:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9522:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9523:     }
1.620     albertel 9524:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9525:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9526:     return &log_query($cname,$cdom,'courselog',%filters);
                   9527: }
                   9528: 
                   9529: sub userlog_query {
1.858     raeburn  9530: #
                   9531: # possible filters:
                   9532: # action: log check role
                   9533: # start: timestamp
                   9534: # end: timestamp
                   9535: #
1.240     www      9536:     my ($uname,$udom,%filters)=@_;
                   9537:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9538: }
                   9539: 
1.506     raeburn  9540: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9541: 
                   9542: sub auto_run {
1.508     raeburn  9543:     my ($cnum,$cdom) = @_;
1.876     raeburn  9544:     my $response = 0;
                   9545:     my $settings;
                   9546:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9547:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9548:         $settings = $domconfig{'autoenroll'};
                   9549:         if ($settings->{'run'} eq '1') {
                   9550:             $response = 1;
                   9551:         }
                   9552:     } else {
1.934     raeburn  9553:         my $homeserver;
                   9554:         if (&is_course($cdom,$cnum)) {
                   9555:             $homeserver = &homeserver($cnum,$cdom);
                   9556:         } else {
                   9557:             $homeserver = &domain($cdom,'primary');
                   9558:         }
                   9559:         if ($homeserver ne 'no_host') {
                   9560:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9561:         }
1.876     raeburn  9562:     }
1.506     raeburn  9563:     return $response;
                   9564: }
1.776     albertel 9565: 
1.506     raeburn  9566: sub auto_get_sections {
1.508     raeburn  9567:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9568:     my $homeserver;
                   9569:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9570:         $homeserver = &homeserver($cnum,$cdom);
                   9571:     }
                   9572:     if (!defined($homeserver)) { 
                   9573:         if ($cdom =~ /^$match_domain$/) {
                   9574:             $homeserver = &domain($cdom,'primary');
                   9575:         }
                   9576:     }
                   9577:     my @secs;
                   9578:     if (defined($homeserver)) {
                   9579:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9580:         unless ($response eq 'refused') {
                   9581:             @secs = split(/:/,$response);
                   9582:         }
1.506     raeburn  9583:     }
                   9584:     return @secs;
                   9585: }
1.776     albertel 9586: 
1.506     raeburn  9587: sub auto_new_course {
1.1099    raeburn  9588:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9589:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9590:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9591:     return $response;
                   9592: }
1.776     albertel 9593: 
1.506     raeburn  9594: sub auto_validate_courseID {
1.508     raeburn  9595:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9596:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9597:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9598:     return $response;
                   9599: }
1.776     albertel 9600: 
1.1007    raeburn  9601: sub auto_validate_instcode {
1.1020    raeburn  9602:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9603:     my ($homeserver,$response);
                   9604:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9605:         $homeserver = &homeserver($cnum,$cdom);
                   9606:     }
                   9607:     if (!defined($homeserver)) {
                   9608:         if ($cdom =~ /^$match_domain$/) {
                   9609:             $homeserver = &domain($cdom,'primary');
                   9610:         }
                   9611:     }
1.1065    raeburn  9612:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9613:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9614:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9615:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9616: }
                   9617: 
1.1172.2.141  raeburn  9618: sub auto_validate_inst_crosslist {
                   9619:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   9620:     my ($homeserver,$response);
                   9621:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9622:         $homeserver = &homeserver($cnum,$cdom);
                   9623:     }
                   9624:     if (!defined($homeserver)) {
                   9625:         if ($cdom =~ /^$match_domain$/) {
                   9626:             $homeserver = &domain($cdom,'primary');
                   9627:         }
                   9628:     }
                   9629:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   9630:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   9631:                          &escape($instcode).':'.&escape($inst_xlist).':'.
                   9632:                          &escape($coowner),$homeserver);
                   9633:     }
                   9634:     return $response;
                   9635: }
                   9636: 
1.506     raeburn  9637: sub auto_create_password {
1.873     raeburn  9638:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9639:     my ($homeserver,$response);
1.506     raeburn  9640:     my $create_passwd = 0;
                   9641:     my $authchk = '';
1.873     raeburn  9642:     if ($udom =~ /^$match_domain$/) {
                   9643:         $homeserver = &domain($udom,'primary');
                   9644:     }
                   9645:     if ($homeserver eq '') {
                   9646:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9647:             $homeserver = &homeserver($cnum,$cdom);
                   9648:         }
                   9649:     }
                   9650:     if ($homeserver eq '') {
                   9651:         $authchk = 'nodomain';
1.506     raeburn  9652:     } else {
1.873     raeburn  9653:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9654:         if ($response eq 'refused') {
                   9655:             $authchk = 'refused';
                   9656:         } else {
1.901     albertel 9657:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9658:         }
1.506     raeburn  9659:     }
                   9660:     return ($authparam,$create_passwd,$authchk);
                   9661: }
                   9662: 
1.706     raeburn  9663: sub auto_photo_permission {
                   9664:     my ($cnum,$cdom,$students) = @_;
                   9665:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9666:     my ($outcome,$perm_reqd,$conditions) = 
                   9667: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9668:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9669: 	return (undef,undef);
                   9670:     }
1.706     raeburn  9671:     return ($outcome,$perm_reqd,$conditions);
                   9672: }
                   9673: 
                   9674: sub auto_checkphotos {
                   9675:     my ($uname,$udom,$pid) = @_;
                   9676:     my $homeserver = &homeserver($uname,$udom);
                   9677:     my ($result,$resulttype);
                   9678:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9679: 				   &escape($uname).':'.&escape($pid),
                   9680: 				   $homeserver));
1.709     albertel 9681:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9682: 	return (undef,undef);
                   9683:     }
1.706     raeburn  9684:     if ($outcome) {
                   9685:         ($result,$resulttype) = split(/:/,$outcome);
                   9686:     } 
                   9687:     return ($result,$resulttype);
                   9688: }
                   9689: 
                   9690: sub auto_photochoice {
                   9691:     my ($cnum,$cdom) = @_;
                   9692:     my $homeserver = &homeserver($cnum,$cdom);
                   9693:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9694: 						       &escape($cdom),
                   9695: 						       $homeserver)));
1.709     albertel 9696:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9697: 	return (undef,undef);
                   9698:     }
1.706     raeburn  9699:     return ($update,$comment);
                   9700: }
                   9701: 
                   9702: sub auto_photoupdate {
                   9703:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9704:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9705:     my $host=&hostname($homeserver);
1.706     raeburn  9706:     my $cmd = '';
                   9707:     my $maxtries = 1;
1.800     albertel 9708:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9709:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9710:     }
                   9711:     $cmd =~ s/%%$//;
                   9712:     $cmd = &escape($cmd);
                   9713:     my $query = 'institutionalphotos';
                   9714:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9715:     unless ($queryid=~/^\Q$host\E\_/) {
                   9716:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9717:         return 'error: '.$queryid;
                   9718:     }
                   9719:     my $reply = &get_query_reply($queryid);
                   9720:     my $tries = 1;
                   9721:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9722:         $reply = &get_query_reply($queryid);
                   9723:         $tries ++;
                   9724:     }
                   9725:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9726:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9727:     } else {
                   9728:         my @responses = split(/:/,$reply);
                   9729:         my $outcome = shift(@responses); 
                   9730:         foreach my $item (@responses) {
                   9731:             my ($key,$value) = split(/=/,$item);
                   9732:             $$photo{$key} = $value;
                   9733:         }
                   9734:         return $outcome;
                   9735:     }
                   9736:     return 'error';
                   9737: }
                   9738: 
1.521     raeburn  9739: sub auto_instcode_format {
1.793     albertel 9740:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9741: 	$cat_order) = @_;
1.521     raeburn  9742:     my $courses = '';
1.772     raeburn  9743:     my @homeservers;
1.521     raeburn  9744:     if ($caller eq 'global') {
1.841     albertel 9745: 	my %servers = &get_servers($codedom,'library');
                   9746: 	foreach my $tryserver (keys(%servers)) {
                   9747: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9748: 		push(@homeservers,$tryserver);
                   9749: 	    }
1.584     raeburn  9750:         }
1.1022    raeburn  9751:     } elsif ($caller eq 'requests') {
                   9752:         if ($codedom =~ /^$match_domain$/) {
                   9753:             my $chome = &domain($codedom,'primary');
                   9754:             unless ($chome eq 'no_host') {
                   9755:                 push(@homeservers,$chome);
                   9756:             }
                   9757:         }
1.521     raeburn  9758:     } else {
1.772     raeburn  9759:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9760:     }
1.793     albertel 9761:     foreach my $code (keys(%{$instcodes})) {
                   9762:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9763:     }
                   9764:     chop($courses);
1.772     raeburn  9765:     my $ok_response = 0;
                   9766:     my $response;
                   9767:     while (@homeservers > 0 && $ok_response == 0) {
                   9768:         my $server = shift(@homeservers); 
                   9769:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9770:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9771:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9772: 		split(/:/,$response);
1.772     raeburn  9773:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9774:             push(@{$codetitles},&str2array($codetitles_str));
                   9775:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9776:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9777:             $ok_response = 1;
                   9778:         }
                   9779:     }
                   9780:     if ($ok_response) {
1.521     raeburn  9781:         return 'ok';
1.772     raeburn  9782:     } else {
                   9783:         return $response;
1.521     raeburn  9784:     }
                   9785: }
                   9786: 
1.792     raeburn  9787: sub auto_instcode_defaults {
                   9788:     my ($domain,$returnhash,$code_order) = @_;
                   9789:     my @homeservers;
1.841     albertel 9790: 
                   9791:     my %servers = &get_servers($domain,'library');
                   9792:     foreach my $tryserver (keys(%servers)) {
                   9793: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9794: 	    push(@homeservers,$tryserver);
                   9795: 	}
1.792     raeburn  9796:     }
1.841     albertel 9797: 
1.792     raeburn  9798:     my $response;
1.841     albertel 9799:     foreach my $server (@homeservers) {
1.792     raeburn  9800:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9801:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9802: 	
                   9803: 	foreach my $pair (split(/\&/,$response)) {
                   9804: 	    my ($name,$value)=split(/\=/,$pair);
                   9805: 	    if ($name eq 'code_order') {
                   9806: 		@{$code_order} = split(/\&/,&unescape($value));
                   9807: 	    } else {
                   9808: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9809: 	    }
                   9810: 	}
                   9811: 	return 'ok';
1.792     raeburn  9812:     }
1.841     albertel 9813: 
                   9814:     return $response;
1.1003    raeburn  9815: }
                   9816: 
                   9817: sub auto_possible_instcodes {
1.1007    raeburn  9818:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9819:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9820:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9821:         return;
                   9822:     }
1.1003    raeburn  9823:     my (@homeservers,$uhome);
                   9824:     if (defined(&domain($domain,'primary'))) {
                   9825:         $uhome=&domain($domain,'primary');
                   9826:         push(@homeservers,&domain($domain,'primary'));
                   9827:     } else {
                   9828:         my %servers = &get_servers($domain,'library');
                   9829:         foreach my $tryserver (keys(%servers)) {
                   9830:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9831:                 push(@homeservers,$tryserver);
                   9832:             }
                   9833:         }
                   9834:     }
                   9835:     my $response;
                   9836:     foreach my $server (@homeservers) {
                   9837:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9838:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9839:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9840:             split(':',$response);
                   9841:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9842:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9843:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9844:             my ($name,$value)=split('=',$item);
                   9845:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9846:         }
                   9847:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9848:             my ($name,$value)=split('=',$item);
                   9849:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9850:         }
                   9851:         return 'ok';
                   9852:     }
                   9853:     return $response;
                   9854: }
1.792     raeburn  9855: 
1.1010    raeburn  9856: sub auto_courserequest_checks {
                   9857:     my ($dom) = @_;
1.1020    raeburn  9858:     my ($homeserver,%validations);
                   9859:     if ($dom =~ /^$match_domain$/) {
                   9860:         $homeserver = &domain($dom,'primary');
                   9861:     }
                   9862:     unless ($homeserver eq 'no_host') {
                   9863:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9864:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9865:             my @items = split(/&/,$response);
                   9866:             foreach my $item (@items) {
                   9867:                 my ($key,$value) = split('=',$item);
                   9868:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9869:             }
                   9870:         }
                   9871:     }
1.1010    raeburn  9872:     return %validations; 
                   9873: }
                   9874: 
1.1020    raeburn  9875: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9876:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9877:     my ($homeserver,$response);
                   9878:     if ($dom =~ /^$match_domain$/) {
                   9879:         $homeserver = &domain($dom,'primary');
                   9880:     }
1.1172.2.43  raeburn  9881:     unless ($homeserver eq 'no_host') {
                   9882:         my $customdata;
                   9883:         if (ref($custominfo) eq 'HASH') {
                   9884:             $customdata = &freeze_escape($custominfo);
                   9885:         }
1.1020    raeburn  9886:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9887:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9888:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9889:                                     $customdata,$homeserver));
1.1020    raeburn  9890:     }
                   9891:     return $response;
                   9892: }
                   9893: 
1.777     albertel 9894: sub auto_validate_class_sec {
1.918     raeburn  9895:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9896:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9897:     my $ownerlist;
                   9898:     if (ref($owners) eq 'ARRAY') {
                   9899:         $ownerlist = join(',',@{$owners});
                   9900:     } else {
                   9901:         $ownerlist = $owners;
                   9902:     }
1.773     raeburn  9903:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9904:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9905:     return $response;
                   9906: }
                   9907: 
1.1172.2.141  raeburn  9908: sub auto_instsec_reformat {
                   9909:     my ($cdom,$action,$instsecref) = @_;
                   9910:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   9911:     my @homeservers;
                   9912:     if (defined(&domain($cdom,'primary'))) {
                   9913:         push(@homeservers,&domain($cdom,'primary'));
                   9914:     } else {
                   9915:         my %servers = &get_servers($cdom,'library');
                   9916:         foreach my $tryserver (keys(%servers)) {
                   9917:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9918:                 push(@homeservers,$tryserver);
                   9919:             }
                   9920:         }
                   9921:     }
                   9922:     my $response;
                   9923:     my %reformatted = %{$instsecref};
                   9924:     foreach my $server (@homeservers) {
                   9925:         if (ref($instsecref) eq 'HASH') {
                   9926:             my $info = &freeze_escape($instsecref);
                   9927:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   9928:                                 $action.':'.$info,$server);
                   9929:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   9930:             my @items = split(/&/,$response);
                   9931:             foreach my $item (@items) {
                   9932:                 my ($key,$value) = split(/=/,$item);
                   9933:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   9934:             }
                   9935:         }
                   9936:     }
                   9937:     return %reformatted;
                   9938: }
                   9939: 
1.1172.2.94  raeburn  9940: sub auto_validate_instclasses {
                   9941:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9942:     my ($homeserver,%validations);
                   9943:     $homeserver = &homeserver($cnum,$cdom);
                   9944:     unless ($homeserver eq 'no_host') {
                   9945:         my $ownerlist;
                   9946:         if (ref($owners) eq 'ARRAY') {
                   9947:             $ownerlist = join(',',@{$owners});
                   9948:         } else {
                   9949:             $ownerlist = $owners;
                   9950:         }
                   9951:         if (ref($classesref) eq 'HASH') {
                   9952:             my $classes = &freeze_escape($classesref);
                   9953:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9954:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9955:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9956:                 my @items = split(/&/,$response);
                   9957:                 foreach my $item (@items) {
                   9958:                     my ($key,$value) = split('=',$item);
                   9959:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9960:                 }
                   9961:             }
                   9962:         }
                   9963:     }
                   9964:     return %validations;
                   9965: }
                   9966: 
1.1172.2.38  raeburn  9967: sub auto_crsreq_update {
                   9968:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9969:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9970:     my ($homeserver,%crsreqresponse);
                   9971:     if ($cdom =~ /^$match_domain$/) {
                   9972:         $homeserver = &domain($cdom,'primary');
                   9973:     }
                   9974:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9975:         my $info;
                   9976:         if (ref($inbound) eq 'HASH') {
                   9977:             $info = &freeze_escape($inbound);
                   9978:         }
                   9979:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9980:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9981:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9982:                             &escape($title).':'.&escape($code).':'.
                   9983:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9984:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9985:             my @items = split(/&/,$response);
                   9986:             foreach my $item (@items) {
                   9987:                 my ($key,$value) = split('=',$item);
                   9988:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9989:             }
                   9990:         }
                   9991:     }
                   9992:     return \%crsreqresponse;
                   9993: }
                   9994: 
1.1172.2.78  raeburn  9995: sub auto_export_grades {
                   9996:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9997:     my ($homeserver,%exportresponse);
                   9998:     if ($cdom =~ /^$match_domain$/) {
                   9999:         $homeserver = &domain($cdom,'primary');
                   10000:     }
                   10001:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   10002:         my $info;
                   10003:         if (ref($inforef) eq 'HASH') {
                   10004:             $info = &freeze_escape($inforef);
                   10005:         }
                   10006:         if (ref($gradesref) eq 'HASH') {
                   10007:             my $grades = &freeze_escape($gradesref);
                   10008:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   10009:                                 $info.':'.$grades,$homeserver);
                   10010:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   10011:                 my @items = split(/&/,$response);
                   10012:                 foreach my $item (@items) {
                   10013:                     my ($key,$value) = split('=',$item);
                   10014:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   10015:                 }
                   10016:             }
                   10017:         }
                   10018:     }
                   10019:     return \%exportresponse;
                   10020: }
                   10021: 
1.1172.2.68  raeburn  10022: sub check_instcode_cloning {
                   10023:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   10024:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   10025:         return;
                   10026:     }
                   10027:     my $canclone;
                   10028:     if (@{$code_order} > 0) {
                   10029:         my $instcoderegexp ='^';
                   10030:         my @clonecodes = split(/\&/,$cloner);
                   10031:         foreach my $item (@{$code_order}) {
                   10032:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   10033:                 foreach my $pair (@clonecodes) {
                   10034:                     my ($key,$val) = split(/\=/,$pair,2);
                   10035:                     $val = &unescape($val);
                   10036:                     if ($key eq $item) {
                   10037:                         $instcoderegexp .= '('.$val.')';
                   10038:                         last;
                   10039:                     }
                   10040:                 }
                   10041:             } else {
                   10042:                 $instcoderegexp .= $codedefaults->{$item};
                   10043:             }
                   10044:         }
                   10045:         $instcoderegexp .= '$';
                   10046:         my (@from,@to);
                   10047:         eval {
                   10048:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10049:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10050:         };
                   10051:         if ((@from > 0) && (@to > 0)) {
                   10052:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10053:             if (!@diffs) {
                   10054:                 $canclone = 1;
                   10055:             }
                   10056:         }
                   10057:     }
                   10058:     return $canclone;
                   10059: }
                   10060: 
                   10061: sub default_instcode_cloning {
                   10062:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   10063:     my (%codedefaults,@code_order,$canclone);
                   10064:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   10065:         %codedefaults = %{$codedefaultsref};
                   10066:         @code_order = @{$codeorderref};
                   10067:     } elsif ($clonedom) {
                   10068:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   10069:     }
                   10070:     if (($domdefclone) && (@code_order)) {
                   10071:         my @clonecodes = split(/\+/,$domdefclone);
                   10072:         my $instcoderegexp ='^';
                   10073:         foreach my $item (@code_order) {
                   10074:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   10075:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   10076:             } else {
                   10077:                 $instcoderegexp .= $codedefaults{$item};
                   10078:             }
                   10079:         }
                   10080:         $instcoderegexp .= '$';
                   10081:         my (@from,@to);
                   10082:         eval {
                   10083:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10084:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10085:         };
                   10086:         if ((@from > 0) && (@to > 0)) {
                   10087:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10088:             if (!@diffs) {
                   10089:                 $canclone = 1;
                   10090:             }
                   10091:         }
                   10092:     }
                   10093:     return $canclone;
                   10094: }
                   10095: 
1.679     raeburn  10096: # ------------------------------------------------------- Course Group routines
                   10097: 
                   10098: sub get_coursegroups {
1.809     raeburn  10099:     my ($cdom,$cnum,$group,$namespace) = @_;
                   10100:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  10101: }
                   10102: 
1.679     raeburn  10103: sub modify_coursegroup {
                   10104:     my ($cdom,$cnum,$groupsettings) = @_;
                   10105:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   10106: }
                   10107: 
1.809     raeburn  10108: sub toggle_coursegroup_status {
                   10109:     my ($cdom,$cnum,$group,$action) = @_;
                   10110:     my ($from_namespace,$to_namespace);
                   10111:     if ($action eq 'delete') {
                   10112:         $from_namespace = 'coursegroups';
                   10113:         $to_namespace = 'deleted_groups';
                   10114:     } else {
                   10115:         $from_namespace = 'deleted_groups';
                   10116:         $to_namespace = 'coursegroups';
                   10117:     }
                   10118:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  10119:     if (my $tmp = &error(%curr_group)) {
                   10120:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   10121:         return ('read error',$tmp);
                   10122:     } else {
                   10123:         my %savedsettings = %curr_group; 
1.809     raeburn  10124:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  10125:         my $deloutcome;
                   10126:         if ($result eq 'ok') {
1.809     raeburn  10127:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  10128:         } else {
                   10129:             return ('write error',$result);
                   10130:         }
                   10131:         if ($deloutcome eq 'ok') {
                   10132:             return 'ok';
                   10133:         } else {
                   10134:             return ('delete error',$deloutcome);
                   10135:         }
                   10136:     }
                   10137: }
                   10138: 
1.679     raeburn  10139: sub modify_group_roles {
1.957     raeburn  10140:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  10141:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   10142:     my $role = 'gr/'.&escape($userprivs);
                   10143:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  10144:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  10145:     if ($result eq 'ok') {
                   10146:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   10147:     }
1.679     raeburn  10148:     return $result;
                   10149: }
                   10150: 
                   10151: sub modify_coursegroup_membership {
                   10152:     my ($cdom,$cnum,$membership) = @_;
                   10153:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   10154:     return $result;
                   10155: }
                   10156: 
1.682     raeburn  10157: sub get_active_groups {
                   10158:     my ($udom,$uname,$cdom,$cnum) = @_;
                   10159:     my $now = time;
                   10160:     my %groups = ();
                   10161:     foreach my $key (keys(%env)) {
1.811     albertel 10162:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  10163:             my ($start,$end) = split(/\./,$env{$key});
                   10164:             if (($end!=0) && ($end<$now)) { next; }
                   10165:             if (($start!=0) && ($start>$now)) { next; }
                   10166:             if ($1 eq $cdom && $2 eq $cnum) {
                   10167:                 $groups{$3} = $env{$key} ;
                   10168:             }
                   10169:         }
                   10170:     }
                   10171:     return %groups;
                   10172: }
                   10173: 
1.683     raeburn  10174: sub get_group_membership {
                   10175:     my ($cdom,$cnum,$group) = @_;
                   10176:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   10177: }
                   10178: 
                   10179: sub get_users_groups {
                   10180:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  10181:     my @usersgroups;
1.683     raeburn  10182:     my $cachetime=1800;
                   10183: 
                   10184:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  10185:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   10186:     if (defined($cached)) {
1.734     albertel 10187:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  10188:     } else {  
                   10189:         $grouplist = '';
1.816     raeburn  10190:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  10191:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  10192:         my $access_end = $env{'course.'.$courseid.
                   10193:                               '.default_enrollment_end_date'};
                   10194:         my $now = time;
                   10195:         foreach my $key (keys(%roleshash)) {
                   10196:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   10197:                 my $group = $1;
                   10198:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   10199:                     my $start = $2;
                   10200:                     my $end = $1;
                   10201:                     if ($start == -1) { next; } # deleted from group
                   10202:                     if (($start!=0) && ($start>$now)) { next; }
                   10203:                     if (($end!=0) && ($end<$now)) {
                   10204:                         if ($access_end && $access_end < $now) {
                   10205:                             if ($access_end - $end < 86400) {
                   10206:                                 push(@usersgroups,$group);
1.733     raeburn  10207:                             }
                   10208:                         }
1.817     raeburn  10209:                         next;
1.733     raeburn  10210:                     }
1.817     raeburn  10211:                     push(@usersgroups,$group);
1.683     raeburn  10212:                 }
                   10213:             }
                   10214:         }
1.817     raeburn  10215:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   10216:         $grouplist = join(':',@usersgroups);
                   10217:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  10218:     }
1.733     raeburn  10219:     return @usersgroups;
1.683     raeburn  10220: }
                   10221: 
                   10222: sub devalidate_getgroups_cache {
                   10223:     my ($udom,$uname,$cdom,$cnum)=@_;
                   10224:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 10225: 
1.683     raeburn  10226:     my $hashid="$udom:$uname:$courseid";
                   10227:     &devalidate_cache_new('getgroups',$hashid);
                   10228: }
                   10229: 
1.12      www      10230: # ------------------------------------------------------------------ Plain Text
                   10231: 
                   10232: sub plaintext {
1.988     raeburn  10233:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  10234:     if ($short =~ m{^cr/}) {
1.758     albertel 10235: 	return (split('/',$short))[-1];
                   10236:     }
1.742     raeburn  10237:     if (!defined($cid)) {
                   10238:         $cid = $env{'request.course.id'};
                   10239:     }
                   10240:     my %rolenames = (
1.1008    raeburn  10241:                       Course    => 'std',
                   10242:                       Community => 'alt1',
1.742     raeburn  10243:                     );
1.1037    raeburn  10244:     if ($cid ne '') {
                   10245:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   10246:             unless ($forcedefault) {
                   10247:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   10248:                 &Apache::lonlocal::mt_escape(\$roletext);
                   10249:                 return &Apache::lonlocal::mt($roletext);
                   10250:             }
                   10251:         }
                   10252:     }
                   10253:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   10254:         (defined($rolenames{$type})) && 
                   10255:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  10256:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  10257:     } elsif ($cid ne '') {
                   10258:         my $crstype = $env{'course.'.$cid.'.type'};
                   10259:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   10260:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   10261:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   10262:         }
1.742     raeburn  10263:     }
1.1037    raeburn  10264:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      10265: }
                   10266: 
                   10267: # ----------------------------------------------------------------- Assign Role
                   10268: 
                   10269: sub assignrole {
1.957     raeburn  10270:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   10271:         $context)=@_;
1.21      www      10272:     my $mrole;
                   10273:     if ($role =~ /^cr\//) {
1.393     www      10274:         my $cwosec=$url;
1.811     albertel 10275:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      10276: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  10277:            my $refused = 1;
                   10278:            if ($context eq 'requestcourses') {
                   10279:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   10280:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   10281:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   10282:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10283:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10284:                            if ($crsenv{'internal.courseowner'} eq
                   10285:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   10286:                                $refused = '';
                   10287:                            }
                   10288:                        }
                   10289:                    }
                   10290:                }
                   10291:            }
                   10292:            if ($refused) {
                   10293:                &logthis('Refused custom assignrole: '.
                   10294:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   10295:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   10296:                return 'refused';
                   10297:            }
1.104     www      10298:         }
1.21      www      10299:         $mrole='cr';
1.678     raeburn  10300:     } elsif ($role =~ /^gr\//) {
                   10301:         my $cwogrp=$url;
1.811     albertel 10302:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  10303:         unless (&allowed('mdg',$cwogrp)) {
                   10304:             &logthis('Refused group assignrole: '.
                   10305:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   10306:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   10307:             return 'refused';
                   10308:         }
                   10309:         $mrole='gr';
1.21      www      10310:     } else {
1.82      www      10311:         my $cwosec=$url;
1.811     albertel 10312:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  10313:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   10314:             my $refused;
                   10315:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   10316:                 if (!(&allowed('c'.$role,$url))) {
                   10317:                     $refused = 1;
                   10318:                 }
                   10319:             } else {
                   10320:                 $refused = 1;
                   10321:             }
1.947     raeburn  10322:             if ($refused) {
1.1045    raeburn  10323:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10324:                 if (!$selfenroll && $context eq 'course') {
                   10325:                     my %crsenv;
                   10326:                     if ($role eq 'cc' || $role eq 'co') {
                   10327:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10328:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   10329:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   10330:                                 if ($crsenv{'internal.courseowner'} eq 
                   10331:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10332:                                     $refused = '';
                   10333:                                 }
                   10334:                             }
                   10335:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   10336:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   10337:                                 if ($crsenv{'internal.courseowner'} eq 
                   10338:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10339:                                     $refused = '';
                   10340:                                 }
                   10341:                             }
                   10342:                         }
                   10343:                     }
1.1172.2.146.  .13(raeb 10344:-23):                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   10345:-23):                     if ($role eq 'st') {
                   10346:-23):                         $refused = '';
                   10347:-23):                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
                   10348:-23):                         $refused = '';
                   10349:-23):                     }
1.1017    raeburn  10350:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10351:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10352:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10353:                         my $wrongcc;
                   10354:                         if ($cnum =~ /^$match_community$/) {
                   10355:                             $wrongcc = 1 if ($role eq 'cc');
                   10356:                         } else {
                   10357:                             $wrongcc = 1 if ($role eq 'co');
                   10358:                         }
                   10359:                         unless ($wrongcc) {
                   10360:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10361:                             if ($crsenv{'internal.courseowner'} eq 
                   10362:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10363:                                 $refused = '';
                   10364:                             }
1.1017    raeburn  10365:                         }
                   10366:                     }
1.1172.2.9  raeburn  10367:                 } elsif ($context eq 'requestauthor') {
                   10368:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   10369:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10370:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10371:                             $refused = '';
                   10372:                         } else {
                   10373:                             my %domdefaults = &get_domain_defaults($udom);
                   10374:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10375:                                 my $checkbystatus;
                   10376:                                 if ($env{'user.adv'}) {
                   10377:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10378:                                     if ($disposition eq 'automatic') {
                   10379:                                         $refused = '';
                   10380:                                     } elsif ($disposition eq '') {
                   10381:                                         $checkbystatus = 1;
                   10382:                                     }
                   10383:                                 } else {
                   10384:                                     $checkbystatus = 1;
                   10385:                                 }
                   10386:                                 if ($checkbystatus) {
                   10387:                                     if ($env{'environment.inststatus'}) {
                   10388:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10389:                                         foreach my $type (@inststatuses) {
                   10390:                                             if (($type ne '') &&
                   10391:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10392:                                                 $refused = '';
                   10393:                                             }
                   10394:                                         }
                   10395:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10396:                                         $refused = '';
                   10397:                                     }
                   10398:                                 }
                   10399:                             }
                   10400:                         }
                   10401:                     }
1.1017    raeburn  10402:                 }
                   10403:                 if ($refused) {
1.947     raeburn  10404:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10405:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10406: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10407:                     return 'refused';
                   10408:                 }
1.932     raeburn  10409:             }
1.1131    raeburn  10410:         } elsif ($role eq 'au') {
                   10411:             if ($url ne '/'.$udom.'/') {
                   10412:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10413:                          ' to assign author role for '.$uname.':'.$udom.
                   10414:                          ' in domain: '.$url.' refused (wrong domain).');
                   10415:                 return 'refused';
                   10416:             }
1.104     www      10417:         }
1.21      www      10418:         $mrole=$role;
                   10419:     }
1.620     albertel 10420:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10421:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10422:     if ($end) { $command.='_'.$end; }
1.21      www      10423:     if ($start) {
                   10424: 	if ($end) { 
1.81      www      10425:            $command.='_'.$start; 
1.21      www      10426:         } else {
1.81      www      10427:            $command.='_0_'.$start;
1.21      www      10428:         }
                   10429:     }
1.739     raeburn  10430:     my $origstart = $start;
                   10431:     my $origend = $end;
1.957     raeburn  10432:     my $delflag;
1.357     www      10433: # actually delete
                   10434:     if ($deleteflag) {
1.373     www      10435: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10436: # modify command to delete the role
1.620     albertel 10437:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10438:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10439: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10440: # set start and finish to negative values for userrolelog
                   10441:            $start=-1;
                   10442:            $end=-1;
1.957     raeburn  10443:            $delflag = 1;
1.357     www      10444:         }
                   10445:     }
                   10446: # send command
1.349     www      10447:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      10448: # log new user role if status is ok
1.349     www      10449:     if ($answer eq 'ok') {
1.663     raeburn  10450: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  10451:         if (($role eq 'cc') || ($role eq 'in') ||
                   10452:             ($role eq 'ep') || ($role eq 'ad') ||
                   10453:             ($role eq 'ta') || ($role eq 'st') ||
                   10454:             ($role=~/^cr/) || ($role eq 'gr') ||
                   10455:             ($role eq 'co')) {
1.1172.2.13  raeburn  10456: # for course roles, perform group memberships changes triggered by role change.
                   10457:             unless ($role =~ /^gr/) {
                   10458:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10459:                                                  $origstart,$selfenroll,$context);
                   10460:             }
1.1172.2.9  raeburn  10461:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10462:                            $selfenroll,$context);
                   10463:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  10464:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10465:                  ($role eq 'da')) {
1.1172.2.9  raeburn  10466:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10467:                            $context);
                   10468:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10469:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10470:                              $context);
                   10471:         }
1.1053    raeburn  10472:         if ($role eq 'cc') {
                   10473:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10474:         }
1.349     www      10475:     }
                   10476:     return $answer;
1.169     harris41 10477: }
                   10478: 
1.1053    raeburn  10479: sub autoupdate_coowners {
                   10480:     my ($url,$end,$start,$uname,$udom) = @_;
                   10481:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10482:     if (($cdom ne '') && ($cnum ne '')) {
                   10483:         my $now = time;
                   10484:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10485:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10486:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10487:             my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141  raeburn  10488:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  10489:             if ($instcode ne '') {
1.1056    raeburn  10490:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10491:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10492:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10493:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141  raeburn  10494:                         unless ($result eq 'valid') {
                   10495:                             if ($xlists ne '') {
                   10496:                                 foreach my $xlist (split(',',$xlists)) {
                   10497:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   10498:                                     $result =
                   10499:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   10500:                                                                       $inst_crosslist,$uname.':'.$udom);
                   10501:                                     last if ($result eq 'valid');
                   10502:                                 }
                   10503:                             }
                   10504:                         }
1.1056    raeburn  10505:                         if ($result eq 'valid') {
                   10506:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10507:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10508:                                     push(@newcoowners,$coowner);
                   10509:                                 }
                   10510:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10511:                                     push(@newcoowners,$uname.':'.$udom);
                   10512:                                 }
                   10513:                                 @newcoowners = sort(@newcoowners);
                   10514:                             } else {
                   10515:                                 push(@newcoowners,$uname.':'.$udom);
                   10516:                             }
1.1172.2.141  raeburn  10517:                         } elsif ($coursehash{'internal.co-owners'}) {
                   10518:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10519:                                 unless ($coowner eq $uname.':'.$udom) {
                   10520:                                     push(@newcoowners,$coowner);
1.1053    raeburn  10521:                                 }
                   10522:                             }
1.1172.2.141  raeburn  10523:                             unless (@newcoowners > 0) {
                   10524:                                 $delcoowners = 1;
                   10525:                                 $coowners = '';
                   10526:                             }
1.1053    raeburn  10527:                         }
                   10528:                         if (@newcoowners || $delcoowners) {
                   10529:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10530:                                             $delcoowners,@newcoowners);
                   10531:                         }
                   10532:                     }
                   10533:                 }
                   10534:             }
                   10535:         }
                   10536:     }
                   10537: }
                   10538: 
                   10539: sub store_coowners {
                   10540:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10541:     my $cid = $cdom.'_'.$cnum;
                   10542:     my ($coowners,$delresult,$putresult);
                   10543:     if (@newcoowners) {
                   10544:         $coowners = join(',',@newcoowners);
                   10545:         my %coownershash = (
                   10546:                             'internal.co-owners' => $coowners,
                   10547:                            );
                   10548:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10549:         if ($putresult eq 'ok') {
                   10550:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10551:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10552:             }
                   10553:         }
                   10554:     }
                   10555:     if ($delcoowners) {
                   10556:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10557:         if ($delresult eq 'ok') {
                   10558:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10559:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10560:             }
                   10561:         }
                   10562:     }
                   10563:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10564:         my %crsinfo =
                   10565:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10566:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10567:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10568:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10569:         }
                   10570:     }
                   10571: }
                   10572: 
1.169     harris41 10573: # -------------------------------------------------- Modify user authentication
1.197     www      10574: # Overrides without validation
                   10575: 
1.169     harris41 10576: sub modifyuserauth {
                   10577:     my ($udom,$uname,$umode,$upass)=@_;
                   10578:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  10579:     my $allowed;
                   10580:     if (&allowed('mau',$udom)) {
                   10581:         $allowed = 1;
                   10582:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10583:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10584:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10585:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10586:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10587:         if (($cdom ne '') && ($cnum ne '')) {
                   10588:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10589:             if ($is_owner) {
                   10590:                 $allowed = 1;
                   10591:             }
                   10592:         }
                   10593:     }
                   10594:     unless ($allowed) { return 'refused'; }
1.197     www      10595:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10596:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10597:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10598:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10599: 		     &escape($upass),$uhome);
1.1172.2.134  raeburn  10600:     my $ip = &get_requestor_ip();
1.620     albertel 10601:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10602:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134  raeburn  10603:          '(Remote '.$ip.'): '.$reply);
1.197     www      10604:     &log($udom,,$uname,$uhome,
1.620     albertel 10605:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10606:                                      $env{'user.name'}.', '.$umode.
1.1172.2.134  raeburn  10607:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10608:     unless ($reply eq 'ok') {
1.197     www      10609:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10610: 	return 'error: '.$reply;
                   10611:     }   
1.170     harris41 10612:     return 'ok';
1.80      www      10613: }
                   10614: 
1.81      www      10615: # --------------------------------------------------------------- Modify a user
1.80      www      10616: 
1.81      www      10617: sub modifyuser {
1.206     matthew  10618:     my ($udom,    $uname, $uid,
                   10619:         $umode,   $upass, $first,
                   10620:         $middle,  $last,  $gene,
1.1058    raeburn  10621:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10622:     $udom= &LONCAPA::clean_domain($udom);
                   10623:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10624:     my $showcandelete = 'none';
                   10625:     if (ref($candelete) eq 'ARRAY') {
                   10626:         if (@{$candelete} > 0) {
                   10627:             $showcandelete = join(', ',@{$candelete});
                   10628:         }
                   10629:     }
1.81      www      10630:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10631:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10632: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10633:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10634:                                      ' desiredhome not specified'). 
1.620     albertel 10635:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10636:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10637:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10638:     my $newuser;
                   10639:     if ($uhome eq 'no_host') {
                   10640:         $newuser = 1;
1.1172.2.146.  .13(raeb 10641:-23):         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   10642:-23):                 ($umode eq 'lti')) {
                   10643:-23):             return 'error: more information needed to create new user';
                   10644:-23):         }
1.1075    raeburn  10645:     }
1.80      www      10646: # ----------------------------------------------------------------- Create User
1.406     albertel 10647:     if (($uhome eq 'no_host') && 
1.1172.2.146.  .13(raeb 10648:-23): 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      10649:         my $unhome='';
1.844     albertel 10650:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10651:             $unhome = $desiredhome;
1.620     albertel 10652: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10653: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10654:         } else { # load balancing routine for determining $unhome
1.81      www      10655:             my $loadm=10000000;
1.841     albertel 10656: 	    my %servers = &get_servers($udom,'library');
                   10657: 	    foreach my $tryserver (keys(%servers)) {
                   10658: 		my $answer=reply('load',$tryserver);
                   10659: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10660: 		    $loadm=$answer;
                   10661: 		    $unhome=$tryserver;
                   10662: 		}
1.80      www      10663: 	    }
                   10664:         }
                   10665:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10666: 	    return 'error: unable to find a home server for '.$uname.
                   10667:                    ' in domain '.$udom;
1.80      www      10668:         }
                   10669:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10670:                          &escape($upass),$unhome);
                   10671: 	unless ($reply eq 'ok') {
                   10672:             return 'error: '.$reply;
                   10673:         }   
1.230     stredwic 10674:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10675:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10676: 	    return 'error: unable verify users home machine.';
1.80      www      10677:         }
1.209     matthew  10678:     }   # End of creation of new user
1.80      www      10679: # ---------------------------------------------------------------------- Add ID
                   10680:     if ($uid) {
                   10681:        $uid=~tr/A-Z/a-z/;
                   10682:        my %uidhash=&idrget($udom,$uname);
1.196     www      10683:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10684:          && (!$forceid)) {
1.80      www      10685: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10686: 	      return 'error: user id "'.$uid.'" does not match '.
                   10687:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10688:           }
                   10689:        } else {
                   10690: 	  &idput($udom,($uname => $uid));
                   10691:        }
                   10692:     }
                   10693: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10694:     my @tmp=&get('environment',
1.899     raeburn  10695: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10696:                     'permanentemail','inststatus'],
1.134     albertel 10697: 		   $udom,$uname);
1.1075    raeburn  10698:     my (%names,%oldnames);
1.313     matthew  10699:     if ($tmp[0] =~ m/^error:.*/) { 
                   10700:         %names=(); 
                   10701:     } else {
                   10702:         %names = @tmp;
1.1075    raeburn  10703:         %oldnames = %names;
1.313     matthew  10704:     }
1.388     www      10705: #
1.1058    raeburn  10706: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10707: # of users did not contain them), do not overwrite existing values
                   10708: # unless field is in $candelete array ref.  
                   10709: #
                   10710: 
                   10711:     my @fields = ('firstname','middlename','lastname','generation',
                   10712:                   'permanentemail','id');
                   10713:     my %newvalues;
                   10714:     if (ref($candelete) eq 'ARRAY') {
                   10715:         foreach my $field (@fields) {
                   10716:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10717:                 if ($field eq 'firstname') {
                   10718:                     $names{$field} = $first;
                   10719:                 } elsif ($field eq 'middlename') {
                   10720:                     $names{$field} = $middle;
                   10721:                 } elsif ($field eq 'lastname') {
                   10722:                     $names{$field} = $last;
                   10723:                 } elsif ($field eq 'generation') { 
                   10724:                     $names{$field} = $gene;
                   10725:                 } elsif ($field eq 'permanentemail') {
                   10726:                     $names{$field} = $email;
                   10727:                 } elsif ($field eq 'id') {
                   10728:                     $names{$field}  = $uid;
                   10729:                 }
                   10730:             }
                   10731:         }
                   10732:     }
1.388     www      10733:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10734:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10735:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10736:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10737:     if ($email) {
                   10738:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10739:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10740:     }
1.899     raeburn  10741:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10742:     if (defined($inststatus)) {
                   10743:         $names{'inststatus'} = '';
                   10744:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10745:         if (ref($usertypes) eq 'HASH') {
                   10746:             my @okstatuses; 
                   10747:             foreach my $item (split(/:/,$inststatus)) {
                   10748:                 if (defined($usertypes->{$item})) {
                   10749:                     push(@okstatuses,$item);  
                   10750:                 }
                   10751:             }
                   10752:             if (@okstatuses) {
                   10753:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10754:             }
                   10755:         }
                   10756:     }
1.1075    raeburn  10757:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10758:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10759:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10760:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10761:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10762:     } else {
                   10763:         $logmsg .= ' during self creation';
                   10764:     }
1.1075    raeburn  10765:     my $changed;
                   10766:     if ($newuser) {
                   10767:         $changed = 1;
                   10768:     } else {
                   10769:         foreach my $field (@fields) {
                   10770:             if ($names{$field} ne $oldnames{$field}) {
                   10771:                 $changed = 1;
                   10772:                 last;
                   10773:             }
                   10774:         }
                   10775:     }
                   10776:     unless ($changed) {
                   10777:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10778:         &logthis($logmsg);
                   10779:         return 'ok';
                   10780:     }
                   10781:     my $reply = &put('environment', \%names, $udom,$uname);
                   10782:     if ($reply ne 'ok') { 
                   10783:         return 'error: '.$reply;
                   10784:     }
1.1087    raeburn  10785:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10786:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10787:     }
1.1075    raeburn  10788:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10789:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10790:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10791:     &logthis($logmsg);
1.134     albertel 10792:     return 'ok';
1.80      www      10793: }
                   10794: 
1.81      www      10795: # -------------------------------------------------------------- Modify student
1.80      www      10796: 
1.81      www      10797: sub modifystudent {
                   10798:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10799:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10800:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10801:     if (!$cid) {
1.620     albertel 10802: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10803: 	    return 'not_in_class';
                   10804: 	}
1.80      www      10805:     }
                   10806: # --------------------------------------------------------------- Make the user
1.81      www      10807:     my $reply=&modifyuser
1.209     matthew  10808: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10809:          $desiredhome,$email,$inststatus);
1.80      www      10810:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10811:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10812:     # student's environment
1.297     matthew  10813:     $uid = undef if (!$forceid);
1.455     albertel 10814:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10815: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10816:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10817:     return $reply;
                   10818: }
                   10819: 
                   10820: sub modify_student_enrollment {
1.1172.2.23  raeburn  10821:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10822:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10823:     my ($cdom,$cnum,$chome);
                   10824:     if (!$cid) {
1.620     albertel 10825: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10826: 	    return 'not_in_class';
                   10827: 	}
1.620     albertel 10828: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10829: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10830:     } else {
                   10831: 	($cdom,$cnum)=split(/_/,$cid);
                   10832:     }
1.620     albertel 10833:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10834:     if (!$chome) {
1.457     raeburn  10835: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10836:     }
1.455     albertel 10837:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10838:     # Make sure the user exists
1.81      www      10839:     my $uhome=&homeserver($uname,$udom);
                   10840:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10841: 	return 'error: no such user';
                   10842:     }
1.297     matthew  10843:     # Get student data if we were not given enough information
                   10844:     if (!defined($first)  || $first  eq '' || 
                   10845:         !defined($last)   || $last   eq '' || 
                   10846:         !defined($uid)    || $uid    eq '' || 
                   10847:         !defined($middle) || $middle eq '' || 
                   10848:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10849:         # They did not supply us with enough data to enroll the student, so
                   10850:         # we need to pick up more information.
1.297     matthew  10851:         my %tmp = &get('environment',
1.294     matthew  10852:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10853:                        ,$udom,$uname);
                   10854: 
1.800     albertel 10855:         #foreach my $key (keys(%tmp)) {
                   10856:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10857:         #}
1.294     matthew  10858:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10859:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10860:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10861:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10862:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10863:     }
1.556     albertel 10864:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10865:     my $user = "$uname:$udom";
                   10866:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10867:     my $reply=cput('classlist',
1.1148    raeburn  10868: 		   {$user => 
1.1172.2.76  raeburn  10869: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10870: 		   $cdom,$cnum);
1.1148    raeburn  10871:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10872:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10873:     } else { 
1.81      www      10874: 	return 'error: '.$reply;
                   10875:     }
1.297     matthew  10876:     # Add student role to user
1.83      www      10877:     my $uurl='/'.$cid;
1.81      www      10878:     $uurl=~s/\_/\//g;
                   10879:     if ($usec) {
                   10880: 	$uurl.='/'.$usec;
                   10881:     }
1.1148    raeburn  10882:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10883:                              $selfenroll,$context);
                   10884:     if ($result ne 'ok') {
                   10885:         if ($old_entry{$user} ne '') {
                   10886:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10887:         } else {
                   10888:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10889:         }
                   10890:     }
                   10891:     return $result; 
1.21      www      10892: }
                   10893: 
1.556     albertel 10894: sub format_name {
                   10895:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10896:     my $name;
                   10897:     if ($first ne 'lastname') {
                   10898: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10899:     } else {
                   10900: 	if ($lastname=~/\S/) {
                   10901: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10902: 	    $name=~s/\s+,/,/;
                   10903: 	} else {
                   10904: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10905: 	}
                   10906:     }
                   10907:     $name=~s/^\s+//;
                   10908:     $name=~s/\s+$//;
                   10909:     $name=~s/\s+/ /g;
                   10910:     return $name;
                   10911: }
                   10912: 
1.84      www      10913: # ------------------------------------------------- Write to course preferences
                   10914: 
                   10915: sub writecoursepref {
                   10916:     my ($courseid,%prefs)=@_;
                   10917:     $courseid=~s/^\///;
                   10918:     $courseid=~s/\_/\//g;
                   10919:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10920:     my $chome=homeserver($cnum,$cdomain);
                   10921:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10922: 	return 'error: no such course';
                   10923:     }
                   10924:     my $cstring='';
1.800     albertel 10925:     foreach my $pref (keys(%prefs)) {
                   10926: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10927:     }
1.84      www      10928:     $cstring=~s/\&$//;
                   10929:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10930: }
                   10931: 
                   10932: # ---------------------------------------------------------- Make/modify course
                   10933: 
                   10934: sub createcourse {
1.741     raeburn  10935:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.146.  .1(raebu 10936:22):         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10937:     $url=&declutter($url);
                   10938:     my $cid='';
1.1028    raeburn  10939:     if ($context eq 'requestcourses') {
                   10940:         my $can_create = 0;
                   10941:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10942:         if ($udom eq $ownerdom) {
1.1172.2.146.  .1(raebu 10943:22):             my $reload;
                   10944:22):             if (($callercontext eq 'auto') &&
                   10945:22):                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10946:22):                 $reload = 'reload';
                   10947:22):             }
                   10948:22):             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10949:                                   $context)) {
                   10950:                 $can_create = 1;
                   10951:             }
                   10952:         } else {
                   10953:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10954:                                            $category);
                   10955:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10956:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10957:                 if (@curr > 0) {
                   10958:                     my @options = qw(approval validate autolimit);
                   10959:                     my $optregex = join('|',@options);
                   10960:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10961:                         $can_create = 1;
                   10962:                     }
                   10963:                 }
                   10964:             }
                   10965:         }
                   10966:         if ($can_create) {
                   10967:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10968:                 unless (&allowed('ccc',$udom)) {
                   10969:                     return 'refused'; 
                   10970:                 }
1.1017    raeburn  10971:             }
                   10972:         } else {
                   10973:             return 'refused';
                   10974:         }
1.1028    raeburn  10975:     } elsif (!&allowed('ccc',$udom)) {
                   10976:         return 'refused';
1.84      www      10977:     }
1.1011    raeburn  10978: # --------------------------------------------------------------- Get Unique ID
                   10979:     my $uname;
                   10980:     if ($cnum =~ /^$match_courseid$/) {
                   10981:         my $chome=&homeserver($cnum,$udom,'true');
                   10982:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10983:             $uname = $cnum;
                   10984:         } else {
1.1038    raeburn  10985:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10986:         }
                   10987:     } else {
1.1038    raeburn  10988:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10989:     }
                   10990:     return $uname if ($uname =~ /^error/);
                   10991: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10992:     if (!defined($course_server)) {
                   10993:         if (defined(&domain($udom,'primary'))) {
                   10994:             $course_server = &domain($udom,'primary');
                   10995:         } else {
                   10996:             $course_server = $env{'user.home'}; 
                   10997:         }
                   10998:     }
                   10999:     my %host_servers =
                   11000:         &Apache::lonnet::get_servers($udom,'library');
                   11001:     unless ($host_servers{$course_server}) {
                   11002:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  11003:     }
1.84      www      11004: # ------------------------------------------------------------- Make the course
                   11005:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  11006:                       $course_server);
1.84      www      11007:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  11008:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      11009:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   11010: 	return 'error: no such course';
                   11011:     }
1.271     www      11012: # ----------------------------------------------------------------- Course made
1.516     raeburn  11013: # log existence
1.1029    raeburn  11014:     my $now = time;
1.918     raeburn  11015:     my $newcourse = {
                   11016:                     $udom.'_'.$uname => {
1.921     raeburn  11017:                                      description => $description,
                   11018:                                      inst_code   => $inst_code,
                   11019:                                      owner       => $course_owner,
                   11020:                                      type        => $crstype,
1.1029    raeburn  11021:                                      creator     => $env{'user.name'}.':'.
                   11022:                                                     $env{'user.domain'},
                   11023:                                      created     => $now,
                   11024:                                      context     => $context,
1.918     raeburn  11025:                                                 },
                   11026:                     };
1.921     raeburn  11027:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      11028: # set toplevel url
1.271     www      11029:     my $topurl=$url;
                   11030:     unless ($nonstandard) {
                   11031: # ------------------------------------------ For standard courses, make top url
                   11032:         my $mapurl=&clutter($url);
1.278     www      11033:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 11034:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      11035: <map>
                   11036: <resource id="1" type="start"></resource>
                   11037: <resource id="2" src="$mapurl"></resource>
                   11038: <resource id="3" type="finish"></resource>
                   11039: <link index="1" from="1" to="2"></link>
                   11040: <link index="2" from="2" to="3"></link>
                   11041: </map>
                   11042: ENDINITMAP
                   11043:         $topurl=&declutter(
1.638     albertel 11044:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      11045:                           );
                   11046:     }
                   11047: # ----------------------------------------------------------- Write preferences
1.84      www      11048:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  11049:                      ('description'              => $description,
                   11050:                       'url'                      => $topurl,
                   11051:                       'internal.creator'         => $env{'user.name'}.':'.
                   11052:                                                     $env{'user.domain'},
                   11053:                       'internal.created'         => $now,
                   11054:                       'internal.creationcontext' => $context)
                   11055:                     );
1.84      www      11056:     return '/'.$udom.'/'.$uname;
                   11057: }
                   11058: 
1.1011    raeburn  11059: # ------------------------------------------------------------------- Create ID
                   11060: sub generate_coursenum {
1.1038    raeburn  11061:     my ($udom,$crstype) = @_;
1.1011    raeburn  11062:     my $domdesc = &domain($udom);
                   11063:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  11064:     my $first;
                   11065:     if ($crstype eq 'Community') {
                   11066:         $first = '0';
                   11067:     } else {
                   11068:         $first = int(1+rand(9)); 
                   11069:     } 
                   11070:     my $uname=$first.
1.1011    raeburn  11071:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11072:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11073:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11074: # ----------------------------------------------- Make sure that does not exist
                   11075:     my $uhome=&homeserver($uname,$udom,'true');
                   11076:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  11077:         if ($crstype eq 'Community') {
                   11078:             $first = '0';
                   11079:         } else {
                   11080:             $first = int(1+rand(9));
                   11081:         }
                   11082:         $uname=$first.
1.1011    raeburn  11083:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11084:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11085:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11086:         $uhome=&homeserver($uname,$udom,'true');
                   11087:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   11088:             return 'error: unable to generate unique course-ID';
                   11089:         }
                   11090:     }
                   11091:     return $uname;
                   11092: }
                   11093: 
1.813     albertel 11094: sub is_course {
1.1167    droeschl 11095:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   11096:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  11097:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   11098:     my $uhome=&homeserver($cnum,$cdom);
                   11099:     my $iscourse;
                   11100:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   11101:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   11102:     } else {
                   11103:         my $hashid = $cdom.':'.$cnum;
                   11104:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   11105:         unless (defined($cached)) {
                   11106:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   11107:                                         $cnum,undef,undef,'.');
                   11108:             $iscourse = 0;
                   11109:             if (exists($courses{$cdom.'_'.$cnum})) {
                   11110:                 $iscourse = 1;
                   11111:             }
                   11112:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   11113:         }
                   11114:     }
                   11115:     return unless($iscourse);
1.1167    droeschl 11116:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 11117: }
                   11118: 
1.1015    raeburn  11119: sub store_userdata {
                   11120:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  11121:     my $result;
1.1016    raeburn  11122:     if ($datakey ne '') {
1.1013    raeburn  11123:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  11124:             if ($udom eq '' || $uname eq '') {
                   11125:                 $udom = $env{'user.domain'};
                   11126:                 $uname = $env{'user.name'};
                   11127:             }
                   11128:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  11129:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   11130:                 $result = 'error: no_host';
                   11131:             } else {
1.1172.2.138  raeburn  11132:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  11133:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   11134: 
                   11135:                 my $namevalue='';
                   11136:                 foreach my $key (keys(%{$storehash})) {
                   11137:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   11138:                 }
                   11139:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  11140:                 unless ($namespace eq 'courserequests') {
                   11141:                     $datakey = &escape($datakey);
                   11142:                 }
1.1105    raeburn  11143:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   11144:                                   $namevalue,$uhome);
1.1013    raeburn  11145:             }
                   11146:         } else {
                   11147:             $result = 'error: data to store was not a hash reference'; 
                   11148:         }
                   11149:     } else {
                   11150:         $result= 'error: invalid requestkey'; 
                   11151:     }
                   11152:     return $result;
                   11153: }
                   11154: 
1.21      www      11155: # ---------------------------------------------------------- Assign Custom Role
                   11156: 
                   11157: sub assigncustomrole {
1.957     raeburn  11158:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11159:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  11160:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      11161: }
                   11162: 
                   11163: # ----------------------------------------------------------------- Revoke Role
                   11164: 
                   11165: sub revokerole {
1.957     raeburn  11166:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11167:     my $now=time;
1.965     raeburn  11168:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      11169: }
                   11170: 
                   11171: # ---------------------------------------------------------- Revoke Custom Role
                   11172: 
                   11173: sub revokecustomrole {
1.957     raeburn  11174:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11175:     my $now=time;
1.357     www      11176:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  11177:            $deleteflag,$selfenroll,$context);
1.17      www      11178: }
                   11179: 
1.533     banghart 11180: # ------------------------------------------------------------ Disk usage
1.535     albertel 11181: sub diskusage {
1.955     raeburn  11182:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   11183:     $directorypath =~ s/\/$//;
                   11184:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   11185:                        .&escape($getpropath).':'.&escape($uname).':'
                   11186:                        .&escape($udom),homeserver($uname,$udom));
                   11187:     if ($listing eq 'unknown_cmd') {
                   11188:         if ($getpropath) {
                   11189:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   11190:         }
                   11191:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   11192:     }
1.514     albertel 11193:     return $listing;
1.512     banghart 11194: }
                   11195: 
1.566     banghart 11196: sub is_locked {
1.1096    raeburn  11197:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 11198:     my @check;
                   11199:     my $is_locked;
1.1093    raeburn  11200:     push (@check,$file_name);
1.613     albertel 11201:     my %locked = &get('file_permissions',\@check,
1.620     albertel 11202: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 11203:     my ($tmp)=keys(%locked);
                   11204:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  11205:     
1.566     banghart 11206:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  11207:         $is_locked = 'false';
                   11208:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  11209:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  11210:                $is_locked = 'true';
1.1096    raeburn  11211:                if (ref($which) eq 'ARRAY') {
                   11212:                    push(@{$which},$entry);
                   11213:                } else {
                   11214:                    last;
                   11215:                }
1.745     raeburn  11216:            }
                   11217:        }
1.566     banghart 11218:     } else {
                   11219:         $is_locked = 'false';
                   11220:     }
1.1093    raeburn  11221:     return $is_locked;
1.566     banghart 11222: }
                   11223: 
1.759     albertel 11224: sub declutter_portfile {
                   11225:     my ($file) = @_;
1.833     albertel 11226:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 11227:     return $file;
                   11228: }
                   11229: 
1.559     banghart 11230: # ------------------------------------------------------------- Mark as Read Only
                   11231: 
                   11232: sub mark_as_readonly {
                   11233:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 11234:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11235:     my ($tmp)=keys(%current_permissions);
                   11236:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 11237:     foreach my $file (@{$files}) {
1.759     albertel 11238: 	$file = &declutter_portfile($file);
1.561     banghart 11239:         push(@{$current_permissions{$file}},$what);
1.559     banghart 11240:     }
1.613     albertel 11241:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11242:     return;
                   11243: }
                   11244: 
1.572     banghart 11245: # ------------------------------------------------------------Save Selected Files
                   11246: 
                   11247: sub save_selected_files {
                   11248:     my ($user, $path, @files) = @_;
                   11249:     my $filename = $user."savedfiles";
1.573     banghart 11250:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  11251:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 11252:     foreach my $file (@files) {
1.620     albertel 11253:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 11254:     }
                   11255:     foreach my $file (@other_files) {
1.574     banghart 11256:         print (OUT $file."\n");
1.572     banghart 11257:     }
1.574     banghart 11258:     close (OUT);
1.572     banghart 11259:     return 'ok';
                   11260: }
                   11261: 
1.574     banghart 11262: sub clear_selected_files {
                   11263:     my ($user) = @_;
                   11264:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  11265:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 11266:     print (OUT undef);
                   11267:     close (OUT);
                   11268:     return ("ok");    
                   11269: }
                   11270: 
1.572     banghart 11271: sub files_in_path {
                   11272:     my ($user, $path) = @_;
                   11273:     my $filename = $user."savedfiles";
                   11274:     my %return_files;
1.1172.2.96  raeburn  11275:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 11276:     while (my $line_in = <IN>) {
1.574     banghart 11277:         chomp ($line_in);
                   11278:         my @paths_and_file = split (m!/!, $line_in);
                   11279:         my $file_part = pop (@paths_and_file);
                   11280:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 11281:         $path_part.='/';
                   11282:         my $path_and_file = $path_part.$file_part;
                   11283:         if ($path_part eq $path) {
                   11284:             $return_files{$file_part}= 'selected';
                   11285:         }
                   11286:     }
1.574     banghart 11287:     close (IN);
                   11288:     return (\%return_files);
1.572     banghart 11289: }
                   11290: 
                   11291: # called in portfolio select mode, to show files selected NOT in current directory
                   11292: sub files_not_in_path {
                   11293:     my ($user, $path) = @_;
                   11294:     my $filename = $user."savedfiles";
                   11295:     my @return_files;
                   11296:     my $path_part;
1.1172.2.96  raeburn  11297:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 11298:     while (my $line = <IN>) {
1.572     banghart 11299:         #ok, I know it's clunky, but I want it to work
1.800     albertel 11300:         my @paths_and_file = split(m|/|, $line);
                   11301:         my $file_part = pop(@paths_and_file);
                   11302:         chomp($file_part);
                   11303:         my $path_part = join('/', @paths_and_file);
1.572     banghart 11304:         $path_part .= '/';
                   11305:         my $path_and_file = $path_part.$file_part;
                   11306:         if ($path_part ne $path) {
1.800     albertel 11307:             push(@return_files, ($path_and_file));
1.572     banghart 11308:         }
                   11309:     }
1.800     albertel 11310:     close(OUT);
1.574     banghart 11311:     return (@return_files);
1.572     banghart 11312: }
                   11313: 
1.745     raeburn  11314: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11315: 
1.745     raeburn  11316: sub get_portfile_permissions {
                   11317:     my ($domain,$user) = @_;
1.613     albertel 11318:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11319:     my ($tmp)=keys(%current_permissions);
                   11320:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11321:     return \%current_permissions;
                   11322: }
                   11323: 
                   11324: #---------------------------------------------Get portfolio file access controls
                   11325: 
1.749     raeburn  11326: sub get_access_controls {
1.745     raeburn  11327:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11328:     my %access;
                   11329:     my $real_file = $file;
                   11330:     $file =~ s/\.meta$//;
1.745     raeburn  11331:     if (defined($file)) {
1.749     raeburn  11332:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11333:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11334:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11335:             }
                   11336:         }
1.745     raeburn  11337:     } else {
1.749     raeburn  11338:         foreach my $key (keys(%{$current_permissions})) {
                   11339:             if ($key =~ /\0accesscontrol$/) {
                   11340:                 if (defined($group)) {
                   11341:                     if ($key !~ m-^\Q$group\E/-) {
                   11342:                         next;
                   11343:                     }
                   11344:                 }
                   11345:                 my ($fullpath) = split(/\0/,$key);
                   11346:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11347:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11348:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11349:                     }
                   11350:                 }
                   11351:             }
                   11352:         }
                   11353:     }
                   11354:     return %access;
                   11355: }
                   11356: 
                   11357: sub modify_access_controls {
                   11358:     my ($file_name,$changes,$domain,$user)=@_;
                   11359:     my ($outcome,$deloutcome);
                   11360:     my %store_permissions;
                   11361:     my %new_values;
                   11362:     my %new_control;
                   11363:     my %translation;
                   11364:     my @deletions = ();
                   11365:     my $now = time;
                   11366:     if (exists($$changes{'activate'})) {
                   11367:         if (ref($$changes{'activate'}) eq 'HASH') {
                   11368:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   11369:             my $numnew = scalar(@newitems);
                   11370:             for (my $i=0; $i<$numnew; $i++) {
                   11371:                 my $newkey = $newitems[$i];
                   11372:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  11373:                 if ($newkey =~ /^\d+:/) { 
                   11374:                     $newkey =~ s/^(\d+)/$newid/;
                   11375:                     $translation{$1} = $newid;
                   11376:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   11377:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   11378:                     $translation{$1} = $newid;
                   11379:                 }
1.749     raeburn  11380:                 $new_values{$file_name."\0".$newkey} = 
                   11381:                                           $$changes{'activate'}{$newitems[$i]};
                   11382:                 $new_control{$newkey} = $now;
                   11383:             }
                   11384:         }
                   11385:     }
                   11386:     my %todelete;
                   11387:     my %changed_items;
                   11388:     foreach my $action ('delete','update') {
                   11389:         if (exists($$changes{$action})) {
                   11390:             if (ref($$changes{$action}) eq 'HASH') {
                   11391:                 foreach my $key (keys(%{$$changes{$action}})) {
                   11392:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   11393:                     if ($action eq 'delete') { 
                   11394:                         $todelete{$itemnum} = 1;
                   11395:                     } else {
                   11396:                         $changed_items{$itemnum} = $key;
                   11397:                     }
                   11398:                 }
1.745     raeburn  11399:             }
                   11400:         }
1.749     raeburn  11401:     }
                   11402:     # get lock on access controls for file.
                   11403:     my $lockhash = {
                   11404:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   11405:                                                        ':'.$env{'user.domain'},
                   11406:                    }; 
                   11407:     my $tries = 0;
                   11408:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11409:    
1.1172.2.79  raeburn  11410:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  11411:         $tries ++;
1.1172.2.79  raeburn  11412:         sleep(0.1);
1.749     raeburn  11413:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11414:     }
                   11415:     if ($gotlock eq 'ok') {
                   11416:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   11417:         my ($tmp)=keys(%curr_permissions);
                   11418:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   11419:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   11420:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   11421:             if (ref($curr_controls) eq 'HASH') {
                   11422:                 foreach my $control_item (keys(%{$curr_controls})) {
                   11423:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   11424:                     if (defined($todelete{$itemnum})) {
                   11425:                         push(@deletions,$file_name."\0".$control_item);
                   11426:                     } else {
                   11427:                         if (defined($changed_items{$itemnum})) {
                   11428:                             $new_control{$changed_items{$itemnum}} = $now;
                   11429:                             push(@deletions,$file_name."\0".$control_item);
                   11430:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   11431:                         } else {
                   11432:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   11433:                         }
                   11434:                     }
1.745     raeburn  11435:                 }
                   11436:             }
                   11437:         }
1.970     raeburn  11438:         my ($group);
                   11439:         if (&is_course($domain,$user)) {
                   11440:             ($group,my $file) = split(/\//,$file_name,2);
                   11441:         }
1.749     raeburn  11442:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   11443:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   11444:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   11445:         #  remove lock
                   11446:         my @del_lock = ($file_name."\0".'locked_access_records');
                   11447:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  11448:         my $sqlresult =
1.970     raeburn  11449:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  11450:                                     $group);
1.749     raeburn  11451:     } else {
                   11452:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  11453:     }
1.749     raeburn  11454:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  11455: }
                   11456: 
1.827     raeburn  11457: sub make_public_indefinitely {
                   11458:     my ($requrl) = @_;
                   11459:     my $now = time;
                   11460:     my $action = 'activate';
                   11461:     my $aclnum = 0;
                   11462:     if (&is_portfolio_url($requrl)) {
                   11463:         my (undef,$udom,$unum,$file_name,$group) =
                   11464:             &parse_portfolio_url($requrl);
                   11465:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   11466:         my %access_controls = &get_access_controls($current_perms,
                   11467:                                                    $group,$file_name);
                   11468:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11469:             my ($num,$scope,$end,$start) = 
                   11470:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   11471:             if ($scope eq 'public') {
                   11472:                 if ($start <= $now && $end == 0) {
                   11473:                     $action = 'none';
                   11474:                 } else {
                   11475:                     $action = 'update';
                   11476:                     $aclnum = $num;
                   11477:                 }
                   11478:                 last;
                   11479:             }
                   11480:         }
                   11481:         if ($action eq 'none') {
                   11482:              return 'ok';
                   11483:         } else {
                   11484:             my %changes;
                   11485:             my $newend = 0;
                   11486:             my $newstart = $now;
                   11487:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   11488:             $changes{$action}{$newkey} = {
                   11489:                 type => 'public',
                   11490:                 time => {
                   11491:                     start => $newstart,
                   11492:                     end   => $newend,
                   11493:                 },
                   11494:             };
                   11495:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11496:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   11497:             return $outcome;
                   11498:         }
                   11499:     } else {
                   11500:         return 'invalid';
                   11501:     }
                   11502: }
                   11503: 
1.745     raeburn  11504: #------------------------------------------------------Get Marked as Read Only
                   11505: 
                   11506: sub get_marked_as_readonly {
                   11507:     my ($domain,$user,$what,$group) = @_;
                   11508:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11509:     my @readonly_files;
1.629     banghart 11510:     my $cmp1=$what;
                   11511:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11512:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11513:         if (defined($group)) {
                   11514:             if ($file_name !~ m-^\Q$group\E/-) {
                   11515:                 next;
                   11516:             }
                   11517:         }
1.561     banghart 11518:         if (ref($value) eq "ARRAY"){
                   11519:             foreach my $stored_what (@{$value}) {
1.629     banghart 11520:                 my $cmp2=$stored_what;
1.759     albertel 11521:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11522:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11523:                 }
1.629     banghart 11524:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11525:                     push(@readonly_files, $file_name);
1.745     raeburn  11526:                     last;
1.563     banghart 11527:                 } elsif (!defined($what)) {
                   11528:                     push(@readonly_files, $file_name);
1.745     raeburn  11529:                     last;
1.561     banghart 11530:                 }
                   11531:             }
1.745     raeburn  11532:         }
1.561     banghart 11533:     }
                   11534:     return @readonly_files;
                   11535: }
1.577     banghart 11536: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11537: 
1.577     banghart 11538: sub get_marked_as_readonly_hash {
1.745     raeburn  11539:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11540:     my %readonly_files;
1.745     raeburn  11541:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11542:         if (defined($group)) {
                   11543:             if ($file_name !~ m-^\Q$group\E/-) {
                   11544:                 next;
                   11545:             }
                   11546:         }
1.577     banghart 11547:         if (ref($value) eq "ARRAY"){
                   11548:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11549:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11550:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11551:                         if ($lock_descriptor eq 'graded') {
                   11552:                             $readonly_files{$file_name} = 'graded';
                   11553:                         } elsif ($lock_descriptor eq 'handback') {
                   11554:                             $readonly_files{$file_name} = 'handback';
                   11555:                         } else {
                   11556:                             if (!exists($readonly_files{$file_name})) {
                   11557:                                 $readonly_files{$file_name} = 'locked';
                   11558:                             }
                   11559:                         }
1.745     raeburn  11560:                     }
1.750     banghart 11561:                 } 
1.577     banghart 11562:             }
                   11563:         } 
                   11564:     }
                   11565:     return %readonly_files;
                   11566: }
1.559     banghart 11567: # ------------------------------------------------------------ Unmark as Read Only
                   11568: 
                   11569: sub unmark_as_readonly {
1.629     banghart 11570:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11571:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11572:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11573:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11574:     my $symb_crs = $what;
                   11575:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11576:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11577:     my ($tmp)=keys(%current_permissions);
                   11578:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11579:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11580:     foreach my $file (@readonly_files) {
1.759     albertel 11581: 	my $clean_file = &declutter_portfile($file);
                   11582: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11583: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11584:         my @new_locks;
                   11585:         my @del_keys;
                   11586:         if (ref($current_locks) eq "ARRAY"){
                   11587:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11588:                 my $compare=$locker;
1.749     raeburn  11589:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11590:                     $compare=join('',@{$locker});
1.746     raeburn  11591:                     if ($compare ne $symb_crs) {
                   11592:                         push(@new_locks, $locker);
                   11593:                     }
1.563     banghart 11594:                 }
                   11595:             }
1.650     albertel 11596:             if (scalar(@new_locks) > 0) {
1.563     banghart 11597:                 $current_permissions{$file} = \@new_locks;
                   11598:             } else {
                   11599:                 push(@del_keys, $file);
1.613     albertel 11600:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11601:                 delete($current_permissions{$file});
1.563     banghart 11602:             }
                   11603:         }
1.561     banghart 11604:     }
1.613     albertel 11605:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11606:     return;
                   11607: }
1.512     banghart 11608: 
1.17      www      11609: # ------------------------------------------------------------ Directory lister
                   11610: 
                   11611: sub dirlist {
1.955     raeburn  11612:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11613:     $uri=~s/^\///;
                   11614:     $uri=~s/\/$//;
1.253     stredwic 11615:     my ($udom, $uname);
1.955     raeburn  11616:     if ($getuserdir) {
1.253     stredwic 11617:         $udom = $userdomain;
                   11618:         $uname = $username;
1.955     raeburn  11619:     } else {
                   11620:         (undef,$udom,$uname)=split(/\//,$uri);
                   11621:         if(defined($userdomain)) {
                   11622:             $udom = $userdomain;
                   11623:         }
                   11624:         if(defined($username)) {
                   11625:             $uname = $username;
                   11626:         }
1.253     stredwic 11627:     }
1.955     raeburn  11628:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11629: 
1.955     raeburn  11630:     $dirRoot = $perlvar{'lonDocRoot'};
                   11631:     if (defined($getpropath)) {
                   11632:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11633:         $dirRoot =~ s/\/$//;
1.955     raeburn  11634:     } elsif (defined($getuserdir)) {
                   11635:         my $subdir=$uname.'__';
                   11636:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11637:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11638:                    ."/$udom/$subdir/$uname";
                   11639:     } elsif (defined($alternateRoot)) {
                   11640:         $dirRoot = $alternateRoot;
1.751     banghart 11641:     }
1.253     stredwic 11642: 
                   11643:     if($udom) {
                   11644:         if($uname) {
1.1135    raeburn  11645:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11646:             if ($uhome eq 'no_host') {
                   11647:                 return ([],'no_host');
                   11648:             }
1.955     raeburn  11649:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11650:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11651:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11652:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11653:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11654:             } else {
                   11655:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11656:             }
1.605     matthew  11657:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11658:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11659:                 @listing_results = split(/:/,$listing);
                   11660:             } else {
                   11661:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11662:             }
1.1135    raeburn  11663:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11664:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11665:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11666:                 return ([],$listing);
                   11667:             } else {
                   11668:                 return (\@listing_results);
1.1135    raeburn  11669:             }
1.955     raeburn  11670:         } elsif(!$alternateRoot) {
1.1136    raeburn  11671:             my (%allusers,%listerror);
1.841     albertel 11672: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11673:  	    foreach my $tryserver (keys(%servers)) {
                   11674:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11675:                                   &escape($udom),$tryserver);
                   11676:                 if ($listing eq 'unknown_cmd') {
                   11677: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11678: 				      $udom, $tryserver);
                   11679:                 } else {
                   11680:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11681:                 }
1.841     albertel 11682: 		if ($listing eq 'unknown_cmd') {
                   11683: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11684: 				      $udom, $tryserver);
                   11685: 		    @listing_results = split(/:/,$listing);
                   11686: 		} else {
                   11687: 		    @listing_results =
                   11688: 			map { &unescape($_); } split(/:/,$listing);
                   11689: 		}
1.1136    raeburn  11690:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11691:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11692:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11693:                     $listerror{$tryserver} = $listing;
                   11694:                 } else {
1.841     albertel 11695: 		    foreach my $line (@listing_results) {
                   11696: 			my ($entry) = split(/&/,$line,2);
                   11697: 			$allusers{$entry} = 1;
                   11698: 		    }
                   11699: 		}
1.253     stredwic 11700:             }
1.1136    raeburn  11701:             my @alluserslist=();
1.800     albertel 11702:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11703:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11704:             }
1.1172.2.80  raeburn  11705:             if (!%listerror) {
                   11706:                 # no errors
                   11707:                 return (\@alluserslist);
                   11708:             } elsif (scalar(keys(%servers)) == 1) {
                   11709:                 # one library server, one error
                   11710:                 my ($key) = keys(%listerror);
                   11711:                 return (\@alluserslist, $listerror{$key});
                   11712:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11713:                 # con_lost indicates that we might miss data from at least one
                   11714:                 # library server
                   11715:                 return (\@alluserslist, 'con_lost');
                   11716:             } else {
                   11717:                 # multiple library servers and no con_lost -> data should be
                   11718:                 # complete.
                   11719:                 return (\@alluserslist);
                   11720:             }
                   11721: 
1.253     stredwic 11722:         } else {
1.1136    raeburn  11723:             return ([],'missing username');
1.253     stredwic 11724:         }
1.955     raeburn  11725:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11726:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11727:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11728:         return (\@all_domains);
1.955     raeburn  11729:     } else {
1.1136    raeburn  11730:         return ([],'missing domain');
1.275     stredwic 11731:     }
                   11732: }
                   11733: 
                   11734: # --------------------------------------------- GetFileTimestamp
                   11735: # This function utilizes dirlist and returns the date stamp for
                   11736: # when it was last modified.  It will also return an error of -1
                   11737: # if an error occurs
                   11738: 
                   11739: sub GetFileTimestamp {
1.955     raeburn  11740:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11741:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11742:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11743:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11744:                                     undef,$getuserdir);
                   11745:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11746:         return -1;
                   11747:     }
                   11748:     if (ref($fileref) eq 'ARRAY') {
                   11749:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11750:         # @stats contains first the filename, then the stat output
                   11751:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11752:     } else {
                   11753:         return -1;
1.253     stredwic 11754:     }
1.26      www      11755: }
                   11756: 
1.712     albertel 11757: sub stat_file {
                   11758:     my ($uri) = @_;
1.787     albertel 11759:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11760: 
1.955     raeburn  11761:     my ($udom,$uname,$file);
1.712     albertel 11762:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11763: 	($udom,$uname,$file) =
1.811     albertel 11764: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11765: 	$file = 'userfiles/'.$file;
                   11766:     }
                   11767:     if ($uri =~ m-^/res/-) {
                   11768: 	($udom,$uname) = 
1.807     albertel 11769: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11770: 	$file = $uri;
                   11771:     }
                   11772: 
                   11773:     if (!$udom || !$uname || !$file) {
                   11774: 	# unable to handle the uri
                   11775: 	return ();
                   11776:     }
1.956     raeburn  11777:     my $getpropath;
                   11778:     if ($file =~ /^userfiles\//) {
                   11779:         $getpropath = 1;
                   11780:     }
1.1136    raeburn  11781:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11782:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11783:         return ();
                   11784:     } else {
                   11785:         if (ref($listref) eq 'ARRAY') {
                   11786:             my @stats = split('&',$listref->[0]);
                   11787: 	    shift(@stats); #filename is first
                   11788: 	    return @stats;
                   11789:         }
1.712     albertel 11790:     }
                   11791:     return ();
                   11792: }
                   11793: 
1.26      www      11794: # -------------------------------------------------------- Value of a Condition
                   11795: 
1.713     albertel 11796: # gets the value of a specific preevaluated condition
                   11797: #    stored in the string  $env{user.state.<cid>}
                   11798: # or looks up a condition reference in the bighash and if if hasn't
                   11799: # already been evaluated recurses into docondval to get the value of
                   11800: # the condition, then memoizing it to 
                   11801: #   $env{user.state.<cid>.<condition>}
1.40      www      11802: sub directcondval {
                   11803:     my $number=shift;
1.620     albertel 11804:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11805: 	&Apache::lonuserstate::evalstate();
                   11806:     }
1.713     albertel 11807:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11808: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11809:     } elsif ($number =~ /^_/) {
                   11810: 	my $sub_condition;
                   11811: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11812: 		&GDBM_READER(),0640)) {
                   11813: 	    $sub_condition=$bighash{'conditions'.$number};
                   11814: 	    untie(%bighash);
                   11815: 	}
                   11816: 	my $value = &docondval($sub_condition);
1.949     raeburn  11817: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11818: 	return $value;
                   11819:     }
1.620     albertel 11820:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11821:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11822:     } else {
                   11823:        return 2;
                   11824:     }
                   11825: }
                   11826: 
1.713     albertel 11827: # get the collection of conditions for this resource
1.26      www      11828: sub condval {
                   11829:     my $condidx=shift;
1.54      www      11830:     my $allpathcond='';
1.713     albertel 11831:     foreach my $cond (split(/\|/,$condidx)) {
                   11832: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11833: 	    $allpathcond.=
                   11834: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11835: 	}
1.191     harris41 11836:     }
1.54      www      11837:     $allpathcond=~s/\|$//;
1.713     albertel 11838:     return &docondval($allpathcond);
                   11839: }
                   11840: 
                   11841: #evaluates an expression of conditions
                   11842: sub docondval {
                   11843:     my ($allpathcond) = @_;
                   11844:     my $result=0;
                   11845:     if ($env{'request.course.id'}
                   11846: 	&& defined($allpathcond)) {
                   11847: 	my $operand='|';
                   11848: 	my @stack;
                   11849: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11850: 	    if ($chunk eq '(') {
                   11851: 		push @stack,($operand,$result);
                   11852: 	    } elsif ($chunk eq ')') {
                   11853: 		my $before=pop @stack;
                   11854: 		if (pop @stack eq '&') {
                   11855: 		    $result=$result>$before?$before:$result;
                   11856: 		} else {
                   11857: 		    $result=$result>$before?$result:$before;
                   11858: 		}
                   11859: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11860: 		$operand=$chunk;
                   11861: 	    } else {
                   11862: 		my $new=directcondval($chunk);
                   11863: 		if ($operand eq '&') {
                   11864: 		    $result=$result>$new?$new:$result;
                   11865: 		} else {
                   11866: 		    $result=$result>$new?$result:$new;
                   11867: 		}
                   11868: 	    }
                   11869: 	}
1.26      www      11870:     }
                   11871:     return $result;
1.421     albertel 11872: }
                   11873: 
                   11874: # ---------------------------------------------------- Devalidate courseresdata
                   11875: 
                   11876: sub devalidatecourseresdata {
                   11877:     my ($coursenum,$coursedomain)=@_;
                   11878:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11879:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11880: }
                   11881: 
1.763     www      11882: 
1.200     www      11883: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11884: #
                   11885: #  Parameters:
                   11886: #      $coursenum    - Number of the course.
                   11887: #      $coursedomain - Domain at which the course was created.
                   11888: #  Returns:
                   11889: #     A hash of the course parameters along (I think) with timestamps
                   11890: #     and version info.
1.877     foxr     11891: 
1.624     albertel 11892: sub get_courseresdata {
                   11893:     my ($coursenum,$coursedomain)=@_;
1.200     www      11894:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11895:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11896:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11897:     my %dumpreply;
1.417     albertel 11898:     unless (defined($cached)) {
1.624     albertel 11899: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11900: 	$result=\%dumpreply;
1.251     albertel 11901: 	my ($tmp) = keys(%dumpreply);
                   11902: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11903: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11904: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11905: 	    return $tmp;
1.416     albertel 11906: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11907: 	    $result=undef;
1.599     albertel 11908: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11909: 	}
                   11910:     }
1.624     albertel 11911:     return $result;
                   11912: }
                   11913: 
1.633     albertel 11914: sub devalidateuserresdata {
                   11915:     my ($uname,$udom)=@_;
                   11916:     my $hashid="$udom:$uname";
                   11917:     &devalidate_cache_new('userres',$hashid);
                   11918: }
                   11919: 
1.624     albertel 11920: sub get_userresdata {
                   11921:     my ($uname,$udom)=@_;
                   11922:     #most student don\'t have any data set, check if there is some data
                   11923:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11924: 
                   11925:     my $hashid="$udom:$uname";
                   11926:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11927:     if (!defined($cached)) {
                   11928: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11929: 	$result=\%resourcedata;
                   11930: 	&do_cache_new('userres',$hashid,$result,600);
                   11931:     }
                   11932:     my ($tmp)=keys(%$result);
                   11933:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11934: 	return $result;
                   11935:     }
                   11936:     #error 2 occurs when the .db doesn't exist
                   11937:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11938:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11939: 	    &logthis("<font color=\"blue\">WARNING:".
                   11940: 		     " Trying to get resource data for ".
                   11941: 		     $uname." at ".$udom.": ".
                   11942: 		     $tmp."</font>");
                   11943:         }
1.624     albertel 11944:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11945: 	#&EXT_cache_set($udom,$uname);
                   11946: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11947: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11948:     }
                   11949:     return $tmp;
                   11950: }
1.879     foxr     11951: #----------------------------------------------- resdata - return resource data
                   11952: #  Purpose:
                   11953: #    Return resource data for either users or for a course.
                   11954: #  Parameters:
                   11955: #     $name      - Course/user name.
                   11956: #     $domain    - Name of the domain the user/course is registered on.
                   11957: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11958: #     @which     - Array of names of resources desired.
                   11959: #  Returns:
                   11960: #     The value of the first reasource in @which that is found in the
                   11961: #     resource hash.
                   11962: #  Exceptional Conditions:
                   11963: #     If the $type passed in is not valid (not the string 'course' or 
                   11964: #     'user', an undefined  reference is returned.
                   11965: #     If none of the resources are found, an undef is returned
1.624     albertel 11966: sub resdata {
                   11967:     my ($name,$domain,$type,@which)=@_;
                   11968:     my $result;
                   11969:     if ($type eq 'course') {
                   11970: 	$result=&get_courseresdata($name,$domain);
                   11971:     } elsif ($type eq 'user') {
                   11972: 	$result=&get_userresdata($name,$domain);
                   11973:     }
                   11974:     if (!ref($result)) { return $result; }    
1.251     albertel 11975:     foreach my $item (@which) {
1.927     albertel 11976: 	if (defined($result->{$item->[0]})) {
                   11977: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11978: 	}
1.250     albertel 11979:     }
1.291     albertel 11980:     return undef;
1.200     www      11981: }
                   11982: 
1.1172.2.146.  .1(raebu 11983:22): sub get_domain_lti {
                   11984:22):     my ($cdom,$context) = @_;
          .4(raebu 11985:22):     my ($name,$cachename,%lti);
          .1(raebu 11986:22):     if ($context eq 'consumer') {
                   11987:22):         $name = 'ltitools';
                   11988:22):     } elsif ($context eq 'provider') {
                   11989:22):         $name = 'lti';
          .4(raebu 11990:22):     } elsif ($context eq 'linkprot') {
                   11991:22):         $name = 'ltisec';
          .1(raebu 11992:22):     } else {
                   11993:22):         return %lti;
                   11994:22):     }
          .4(raebu 11995:22):     if ($context eq 'linkprot') {
                   11996:22):         $cachename = $context;
                   11997:22):     } else {
                   11998:22):         $cachename = $name;
                   11999:22):     }
                   12000:22):     my ($result,$cached)=&is_cached_new($cachename,$cdom);
          .1(raebu 12001:22):     if (defined($cached)) {
                   12002:22):         if (ref($result) eq 'HASH') {
                   12003:22):             %lti = %{$result};
                   12004:22):         }
                   12005:22):     } else {
                   12006:22):         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   12007:22):         if (ref($domconfig{$name}) eq 'HASH') {
          .4(raebu 12008:22):             if ($context eq 'linkprot') {
                   12009:22):                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
                   12010:22):                     %lti = %{$domconfig{$name}{'linkprot'}};
                   12011:22):                 }
                   12012:22):             } else {
                   12013:22):                 %lti = %{$domconfig{$name}};
                   12014:22):             }
          .1(raebu 12015:22):         }
                   12016:22):         my $cachetime = 24*60*60;
          .4(raebu 12017:22):         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
          .1(raebu 12018:22):     }
                   12019:22):     return %lti;
                   12020:22): }
                   12021:22): 
                   12022:22): sub get_course_lti {
          .13(raeb 12023:-23):     my ($cnum,$cdom,$context) = @_;
                   12024:-23):     my ($name,$cachename,%lti);
                   12025:-23):     if ($context eq 'consumer') {
                   12026:-23):         $name = 'ltitools';
                   12027:-23):         $cachename = 'courseltitools';
                   12028:-23):     } elsif ($context eq 'provider') {
                   12029:-23):         $name = 'lti';
                   12030:-23):         $cachename = 'courselti';
                   12031:-23):     } else {
                   12032:-23):         return %lti;
                   12033:-23):     }
          .1(raebu 12034:22):     my $hashid=$cdom.'_'.$cnum;
          .13(raeb 12035:-23):     my ($result,$cached)=&is_cached_new($cachename,$hashid);
          .1(raebu 12036:22):     if (defined($cached)) {
                   12037:22):         if (ref($result) eq 'HASH') {
          .13(raeb 12038:-23):             %lti = %{$result};
          .1(raebu 12039:22):         }
                   12040:22):     } else {
          .13(raeb 12041:-23):         %lti = &dump($name,$cdom,$cnum,undef,undef,undef,1);
          .1(raebu 12042:22):         my $cachetime = 24*60*60;
          .13(raeb 12043:-23):         &do_cache_new($cachename,$hashid,\%lti,$cachetime);
          .1(raebu 12044:22):     }
          .13(raeb 12045:-23):     return %lti;
          .1(raebu 12046:22): }
                   12047:22): 
          .3(raebu 12048:22): sub courselti_itemid {
                   12049:22):     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
                   12050:22):     my ($chome,$itemid);
                   12051:22):     $chome = &homeserver($cnum,$cdom);
                   12052:22):     return if ($chome eq 'no_host');
                   12053:22):     if (ref($params) eq 'HASH') {
                   12054:22):         my $rep;
                   12055:22):         if (grep { $_ eq $chome } current_machine_ids()) {
                   12056:22):             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
                   12057:22):         } else {
                   12058:22):             my $escurl = &escape($url);
                   12059:22):             my $escmethod = &escape($method);
                   12060:22):             my $items = &freeze_escape($params);
                   12061:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
                   12062:22):         }
                   12063:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   12064:22):                 ($rep eq 'unknown_cmd')) {
                   12065:22):             $itemid = $rep;
                   12066:22):         }
                   12067:22):     }
                   12068:22):     return $itemid;
                   12069:22): }
                   12070:22): 
                   12071:22): sub domainlti_itemid {
                   12072:22):     my ($cdom,$url,$method,$params,$context) = @_;
                   12073:22):     my ($primary_id,$itemid);
                   12074:22):     $primary_id = &domain($cdom,'primary');
                   12075:22):     return if ($primary_id eq '');
                   12076:22):     if (ref($params) eq 'HASH') {
                   12077:22):         my $rep;
                   12078:22):         if (grep { $_ eq $primary_id } current_machine_ids()) {
                   12079:22):             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
                   12080:22):         } else {
                   12081:22):             my $cnum = '';
                   12082:22):             my $escurl = &escape($url);
                   12083:22):             my $escmethod = &escape($method);
                   12084:22):             my $items = &freeze_escape($params);
                   12085:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
                   12086:22):         }
                   12087:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   12088:22):                 ($rep eq 'unknown_cmd')) {
                   12089:22):             $itemid = $rep;
                   12090:22):         }
                   12091:22):     }
                   12092:22):     return $itemid;
                   12093:22): }
                   12094:22): 
          .9(raebu 12095:23): sub count_supptools {
                   12096:23):     my ($cnum,$cdom,$ignorecache,$reload)=@_;
1.1172.2.31  raeburn  12097:     my $hashid=$cnum.':'.$cdom;
1.1172.2.146.  .9(raebu 12098:23):     my ($numexttools,$cached);
1.1172.2.31  raeburn  12099:     unless ($ignorecache) {
1.1172.2.146.  .9(raebu 12100:23):         ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
1.1172.2.31  raeburn  12101:     }
                   12102:     unless (defined($cached)) {
                   12103:         my $chome=&homeserver($cnum,$cdom);
1.1172.2.146.  .9(raebu 12104:23):         $numexttools = 0;
1.1172.2.31  raeburn  12105:         unless ($chome eq 'no_host') {
1.1172.2.146.  .9(raebu 12106:23):             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
                   12107:23):             if (ref($supplemental) eq 'HASH') {
                   12108:23):                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   12109:23):                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
                   12110:23):                         if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   12111:23):                             $numexttools ++;
                   12112:23):                         }
                   12113:23):                     }
                   12114:23):                 }
                   12115:23):             }
1.1172.2.31  raeburn  12116:         }
1.1172.2.146.  .9(raebu 12117:23):         &do_cache_new('supptools',$hashid,$numexttools,600);
1.1172.2.31  raeburn  12118:     }
1.1172.2.146.  .9(raebu 12119:23):     return $numexttools;
                   12120:23): }
                   12121:23): 
                   12122:23): sub has_unhidden_suppfiles {
                   12123:23):     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   12124:23):     my $hashid=$cnum.':'.$cdom;
                   12125:23):     my ($showsupp,$cached);
                   12126:23):     unless ($ignorecache) {
                   12127:23):         ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
                   12128:23):     }
                   12129:23):     unless (defined($cached)) {
                   12130:23):         my $chome=&homeserver($cnum,$cdom);
                   12131:23):         unless ($chome eq 'no_host') {
                   12132:23):             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
                   12133:23):             if (ref($supplemental) eq 'HASH') {
                   12134:23):                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   12135:23):                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
                   12136:23):                         next if ($key =~ /\.sequence$/);
                   12137:23):                         if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
                   12138:23):                             foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
                   12139:23):                                 unless ($supplemental->{'hidden'}->{$id}) {
                   12140:23):                                     $showsupp = 1;
                   12141:23):                                     last;
                   12142:23):                                 }
                   12143:23):                             }
                   12144:23):                         }
                   12145:23):                         last if ($showsupp);
                   12146:23):                     }
                   12147:23):                 }
                   12148:23):             }
                   12149:23):         }
                   12150:23):         &do_cache_new('showsupp',$hashid,$showsupp,600);
                   12151:23):     }
                   12152:23):     return $showsupp;
1.1172.2.31  raeburn  12153: }
                   12154: 
1.379     matthew  12155: #
                   12156: # EXT resource caching routines
                   12157: #
                   12158: 
1.1172.2.146.  .1(raebu 12159:22): {
                   12160:22): # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   12161:22): #
                   12162:22): # The course for which we cache
                   12163:22): my $cachedmapkey='';
                   12164:22): # The cached recursive maps for this course
                   12165:22): my %cachedmaps=();
                   12166:22): # When this was last done
                   12167:22): my $cachedmaptime='';
                   12168:22): 
1.379     matthew  12169: sub clear_EXT_cache_status {
1.383     albertel 12170:     &delenv('cache.EXT.');
1.379     matthew  12171: }
                   12172: 
                   12173: sub EXT_cache_status {
                   12174:     my ($target_domain,$target_user) = @_;
1.383     albertel 12175:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 12176:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  12177:         # We know already the user has no data
                   12178:         return 1;
                   12179:     } else {
                   12180:         return 0;
                   12181:     }
                   12182: }
                   12183: 
                   12184: sub EXT_cache_set {
                   12185:     my ($target_domain,$target_user) = @_;
1.383     albertel 12186:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  12187:     #&appenv({$cachename => time});
1.379     matthew  12188: }
                   12189: 
1.28      www      12190: # --------------------------------------------------------- Value of a Variable
1.58      www      12191: sub EXT {
1.715     albertel 12192: 
1.1172.2.28  raeburn  12193:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      12194:     unless ($varname) { return ''; }
1.218     albertel 12195:     #get real user name/domain, courseid and symb
                   12196:     my $courseid;
1.359     albertel 12197:     my $publicuser;
1.427     www      12198:     if ($symbparm) {
                   12199: 	$symbparm=&get_symb_from_alias($symbparm);
                   12200:     }
1.218     albertel 12201:     if (!($uname && $udom)) {
1.790     albertel 12202:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 12203:       if (!$symbparm) {	$symbparm=$cursymb; }
                   12204:     } else {
1.620     albertel 12205: 	$courseid=$env{'request.course.id'};
1.218     albertel 12206:     }
1.48      www      12207:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   12208:     my $rest;
1.320     albertel 12209:     if (defined($therest[0])) {
1.48      www      12210:        $rest=join('.',@therest);
                   12211:     } else {
                   12212:        $rest='';
                   12213:     }
1.320     albertel 12214: 
1.57      www      12215:     my $qualifierrest=$qualifier;
                   12216:     if ($rest) { $qualifierrest.='.'.$rest; }
                   12217:     my $spacequalifierrest=$space;
                   12218:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      12219:     if ($realm eq 'user') {
1.48      www      12220: # --------------------------------------------------------------- user.resource
                   12221: 	if ($space eq 'resource') {
1.651     albertel 12222: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   12223: 		  || defined($Apache::lonhomework::parsing_a_task))
                   12224: 		 &&
1.1172.2.142  raeburn  12225: 		 ($symbparm eq &symbread()) ) {
1.744     albertel 12226: 		# if we are in the middle of processing the resource the
                   12227: 		# get the value we are planning on committing
                   12228:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   12229:                     return $Apache::lonhomework::results{$qualifierrest};
                   12230:                 } else {
                   12231:                     return $Apache::lonhomework::history{$qualifierrest};
                   12232:                 }
1.335     albertel 12233: 	    } else {
1.359     albertel 12234: 		my %restored;
1.620     albertel 12235: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 12236: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   12237: 		} else {
                   12238: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   12239: 		}
1.335     albertel 12240: 		return $restored{$qualifierrest};
                   12241: 	    }
1.48      www      12242: # ----------------------------------------------------------------- user.access
                   12243:         } elsif ($space eq 'access') {
1.218     albertel 12244: 	    # FIXME - not supporting calls for a specific user
1.48      www      12245:             return &allowed($qualifier,$rest);
                   12246: # ------------------------------------------ user.preferences, user.environment
                   12247:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 12248: 	    if (($uname eq $env{'user.name'}) &&
                   12249: 		($udom eq $env{'user.domain'})) {
                   12250: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 12251: 	    } else {
1.359     albertel 12252: 		my %returnhash;
                   12253: 		if (!$publicuser) {
                   12254: 		    %returnhash=&userenvironment($udom,$uname,
                   12255: 						 $qualifierrest);
                   12256: 		}
1.218     albertel 12257: 		return $returnhash{$qualifierrest};
                   12258: 	    }
1.48      www      12259: # ----------------------------------------------------------------- user.course
                   12260:         } elsif ($space eq 'course') {
1.218     albertel 12261: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12262:             return $env{join('.',('request.course',$qualifier))};
1.48      www      12263: # ------------------------------------------------------------------- user.role
                   12264:         } elsif ($space eq 'role') {
1.218     albertel 12265: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12266:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      12267:             if ($qualifier eq 'value') {
                   12268: 		return $role;
                   12269:             } elsif ($qualifier eq 'extent') {
                   12270:                 return $where;
                   12271:             }
                   12272: # ----------------------------------------------------------------- user.domain
                   12273:         } elsif ($space eq 'domain') {
1.218     albertel 12274:             return $udom;
1.48      www      12275: # ------------------------------------------------------------------- user.name
                   12276:         } elsif ($space eq 'name') {
1.218     albertel 12277:             return $uname;
1.48      www      12278: # ---------------------------------------------------- Any other user namespace
1.29      www      12279:         } else {
1.359     albertel 12280: 	    my %reply;
                   12281: 	    if (!$publicuser) {
                   12282: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   12283: 	    }
                   12284: 	    return $reply{$qualifierrest};
1.48      www      12285:         }
1.236     www      12286:     } elsif ($realm eq 'query') {
                   12287: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 12288:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   12289: 						[$spacequalifierrest]);
1.620     albertel 12290: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      12291:    } elsif ($realm eq 'request') {
1.48      www      12292: # ------------------------------------------------------------- request.browser
                   12293:         if ($space eq 'browser') {
1.1145    bisitz   12294:             return $env{'browser.'.$qualifier};
1.57      www      12295: # ------------------------------------------------------------ request.filename
                   12296:         } else {
1.620     albertel 12297:             return $env{'request.'.$spacequalifierrest};
1.29      www      12298:         }
1.28      www      12299:     } elsif ($realm eq 'course') {
1.48      www      12300: # ---------------------------------------------------------- course.description
1.620     albertel 12301:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      12302:     } elsif ($realm eq 'resource') {
1.165     www      12303: 
1.620     albertel 12304: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 12305: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   12306: 	}
1.693     albertel 12307: 
1.1172.2.30  raeburn  12308:         if ($qualifier eq '') {
                   12309: 	    if ($space eq 'title') {
                   12310: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   12311: 	        return &gettitle($symbparm);
                   12312: 	    }
1.693     albertel 12313: 	
1.1172.2.30  raeburn  12314: 	    if ($space eq 'map') {
                   12315: 	        my ($map) = &decode_symb($symbparm);
                   12316: 	        return &symbread($map);
                   12317: 	    }
                   12318:             if ($space eq 'maptitle') {
                   12319:                 my ($map) = &decode_symb($symbparm);
                   12320:                 return &gettitle($map);
                   12321:             }
                   12322: 	    if ($space eq 'filename') {
                   12323: 	        if ($symbparm) {
                   12324: 		    return &clutter((&decode_symb($symbparm))[2]);
                   12325: 	        }
                   12326: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 12327: 	    }
1.1172.2.30  raeburn  12328: 
                   12329:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   12330:                 if ($space eq 'visibleparts') {
                   12331:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   12332:                     my $item;
                   12333:                     if (ref($navmap)) {
                   12334:                         my $res = $navmap->getBySymb($symbparm);
                   12335:                         my $parts = $res->parts();
                   12336:                         if (ref($parts) eq 'ARRAY') {
                   12337:                             $item = join(',',@{$parts});
                   12338:                         }
                   12339:                         undef($navmap);
                   12340:                     }
                   12341:                     return $item;
                   12342:                 }
                   12343:             }
                   12344:         }
1.693     albertel 12345: 
                   12346: 	my ($section, $group, @groups);
1.593     albertel 12347: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  12348:         if (($courseid eq '') && ($cid)) {
                   12349:             $courseid = $cid;
                   12350:         }
                   12351: 	if (($symbparm && $courseid) && 
                   12352: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      12353: 
1.218     albertel 12354: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      12355: 
1.60      www      12356: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 12357: 	    my $symbp=$symbparm;
1.735     albertel 12358: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 12359: 
                   12360: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   12361: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   12362: 
1.620     albertel 12363: 	    if (($env{'user.name'} eq $uname) &&
                   12364: 		($env{'user.domain'} eq $udom)) {
                   12365: 		$section=$env{'request.course.sec'};
1.733     raeburn  12366:                 @groups = split(/:/,$env{'request.course.groups'});  
                   12367:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 12368: 	    } else {
1.539     albertel 12369: 		if (! defined($usection)) {
1.551     albertel 12370: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 12371: 		} else {
                   12372: 		    $section = $usection;
                   12373: 		}
1.733     raeburn  12374:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12375: 	    }
                   12376: 
                   12377: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12378: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   12379: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12380: 
1.593     albertel 12381: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12382: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 12383: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12384: 
1.60      www      12385: # ----------------------------------------------------------- first, check user
1.624     albertel 12386: 
                   12387: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 12388: 				       ([$courselevelr,'resource'],
                   12389: 					[$courselevelm,'map'     ],
                   12390: 					[$courselevel, 'course'  ]));
1.931     albertel 12391: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12392: 
1.594     albertel 12393: # ------------------------------------------------ second, check some of course
1.684     raeburn  12394:             my $coursereply;
1.691     raeburn  12395:             if (@groups > 0) {
                   12396:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   12397:                                        $mapparm,$spacequalifierrest);
1.927     albertel 12398:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  12399:             }
1.96      www      12400: 
1.684     raeburn  12401: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12402: 				  $env{'course.'.$courseid.'.domain'},
                   12403: 				  'course',
                   12404: 				  ([$seclevelr,   'resource'],
                   12405: 				   [$seclevelm,   'map'     ],
                   12406: 				   [$seclevel,    'course'  ],
                   12407: 				   [$courselevelr,'resource']));
                   12408: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12409: 
1.60      www      12410: # ------------------------------------------------------ third, check map parms
1.218     albertel 12411: 	    my %parmhash=();
                   12412: 	    my $thisparm='';
                   12413: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12414: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12415: 		    &GDBM_READER(),0640)) {
1.218     albertel 12416: 		$thisparm=$parmhash{$symbparm};
                   12417: 		untie(%parmhash);
                   12418: 	    }
1.927     albertel 12419: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12420: 	}
1.594     albertel 12421: # ------------------------------------------ fourth, look in resource metadata
1.71      www      12422: 
1.1172.2.146.  .13(raeb 12423:-23):         my $what = $spacequalifierrest;
                   12424:-23):         $what=~s/\./\_/;
                   12425:-23):         my $filename;
1.282     albertel 12426: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12427: 	if ($symbparm) {
1.409     www      12428: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12429: 	} else {
1.620     albertel 12430: 	    $filename=$env{'request.filename'};
1.282     albertel 12431: 	}
1.1172.2.146.  .13(raeb 12432:-23):         my $toolsymb;
                   12433:-23):         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   12434:-23):             $toolsymb = $symbparm;
                   12435:-23):         }
                   12436:-23): 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 12437: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1172.2.146.  .13(raeb 12438:-23): 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 12439: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12440: 
1.1172.2.146.  .13(raeb 12441:-23): # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 12442: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12443: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12444: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12445: 				     $env{'course.'.$courseid.'.domain'},
                   12446: 				     'course',
1.927     albertel 12447: 				     ([$courselevelm,'map'   ],
                   12448: 				      [$courselevel, 'course']));
                   12449: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12450: 	}
1.145     www      12451: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12452: 	unless ($space eq '0') {
1.336     albertel 12453: 	    my @parts=split(/_/,$space);
                   12454: 	    my $id=pop(@parts);
                   12455: 	    my $part=join('_',@parts);
                   12456: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12457: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12458: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12459: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12460: 	}
1.395     albertel 12461: 	if ($recurse) { return undef; }
1.1172.2.146.  .13(raeb 12462:-23): 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 12463: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12464: # ---------------------------------------------------- Any other user namespace
                   12465:     } elsif ($realm eq 'environment') {
                   12466: # ----------------------------------------------------------------- environment
1.620     albertel 12467: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12468: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12469: 	} else {
1.770     albertel 12470: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12471: 		return '';
                   12472: 	    }
1.219     albertel 12473: 	    my %returnhash=&userenvironment($udom,$uname,
                   12474: 					    $spacequalifierrest);
                   12475: 	    return $returnhash{$spacequalifierrest};
                   12476: 	}
1.28      www      12477:     } elsif ($realm eq 'system') {
1.48      www      12478: # ----------------------------------------------------------------- system.time
                   12479: 	if ($space eq 'time') {
                   12480: 	    return time;
                   12481:         }
1.696     albertel 12482:     } elsif ($realm eq 'server') {
                   12483: # ----------------------------------------------------------------- system.time
                   12484: 	if ($space eq 'name') {
                   12485: 	    return $ENV{'SERVER_NAME'};
                   12486:         }
1.1172.2.146.  .1(raebu 12487:22):     } elsif ($realm eq 'client') {
                   12488:22):         if ($space eq 'remote_addr') {
                   12489:22):             return &get_requestor_ip();
                   12490:22):         }
1.28      www      12491:     }
1.48      www      12492:     return '';
1.61      www      12493: }
                   12494: 
1.927     albertel 12495: sub get_reply {
                   12496:     my ($reply_value) = @_;
1.940     raeburn  12497:     if (ref($reply_value) eq 'ARRAY') {
                   12498:         if (wantarray) {
                   12499: 	    return @$reply_value;
                   12500:         }
                   12501:         return $reply_value->[0];
                   12502:     } else {
                   12503:         return $reply_value;
1.927     albertel 12504:     }
                   12505: }
                   12506: 
1.691     raeburn  12507: sub check_group_parms {
                   12508:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   12509:     my @groupitems = ();
                   12510:     my $resultitem;
1.927     albertel 12511:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  12512:     foreach my $group (@{$groups}) {
                   12513:         foreach my $level (@levels) {
1.927     albertel 12514:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12515:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12516:         }
                   12517:     }
                   12518:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12519:                             $env{'course.'.$courseid.'.domain'},
                   12520:                                      'course',@groupitems);
                   12521:     return $coursereply;
                   12522: }
                   12523: 
1.1172.2.146.  .1(raebu 12524:22): sub get_map_hierarchy {
                   12525:22):     my ($mapname,$courseid) = @_;
                   12526:22):     my @recurseup = ();
                   12527:22):     if ($mapname) {
                   12528:22):         if (($cachedmapkey eq $courseid) &&
                   12529:22):             (abs($cachedmaptime-time)<5)) {
                   12530:22):             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12531:22):                 return @{$cachedmaps{$mapname}};
                   12532:22):             }
                   12533:22):         }
                   12534:22):         my $navmap = Apache::lonnavmaps::navmap->new();
                   12535:22):         if (ref($navmap)) {
                   12536:22):             @recurseup = $navmap->recurseup_maps($mapname);
                   12537:22):             undef($navmap);
                   12538:22):             $cachedmaps{$mapname} = \@recurseup;
                   12539:22):             $cachedmaptime=time;
                   12540:22):             $cachedmapkey=$courseid;
                   12541:22):         }
                   12542:22):     }
                   12543:22):     return @recurseup;
                   12544:22): }
                   12545:22): 
          .2(raebu 12546:22): }
          .1(raebu 12547:22): 
1.691     raeburn  12548: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12549:     my ($courseid,@groups) = @_;
                   12550:     @groups = sort(@groups);
1.691     raeburn  12551:     return @groups;
                   12552: }
                   12553: 
1.395     albertel 12554: sub packages_tab_default {
1.1172.2.146.  .13(raeb 12555:-23):     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 12556:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12557: 
                   12558:     my (@extension,@specifics,$do_default);
1.1172.2.146.  .13(raeb 12559:-23):     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 12560: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12561: 	if ($pack_type eq 'default') {
                   12562: 	    $do_default=1;
                   12563: 	} elsif ($pack_type eq 'extension') {
                   12564: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12565: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12566: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12567: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12568: 	}
                   12569:     }
                   12570:     # first look for a package that matches the requested part id
                   12571:     foreach my $package (@specifics) {
                   12572: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12573: 	next if ($pack_part ne $part);
                   12574: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12575: 	    return $packagetab{"$pack_type&$name&default"};
                   12576: 	}
                   12577:     }
                   12578:     # look for any possible matching non extension_ package
                   12579:     foreach my $package (@specifics) {
                   12580: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12581: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12582: 	    return $packagetab{"$pack_type&$name&default"};
                   12583: 	}
1.585     albertel 12584: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12585: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12586: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12587: 	}
                   12588:     }
1.738     albertel 12589:     # look for any posible extension_ match
                   12590:     foreach my $package (@extension) {
                   12591: 	my ($package,$pack_type)=@{$package};
                   12592: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12593: 	    return $packagetab{"$pack_type&$name&default"};
                   12594: 	}
                   12595: 	if (defined($packagetab{$package."&$name&default"})) {
                   12596: 	    return $packagetab{$package."&$name&default"};
                   12597: 	}
                   12598:     }
                   12599:     # look for a global default setting
                   12600:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12601: 	return $packagetab{"default&$name&default"};
                   12602:     }
1.395     albertel 12603:     return undef;
                   12604: }
                   12605: 
1.334     albertel 12606: sub add_prefix_and_part {
                   12607:     my ($prefix,$part)=@_;
                   12608:     my $keyroot;
                   12609:     if (defined($prefix) && $prefix !~ /^__/) {
                   12610: 	# prefix that has a part already
                   12611: 	$keyroot=$prefix;
                   12612:     } elsif (defined($prefix)) {
                   12613: 	# prefix that is missing a part
                   12614: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12615:     } else {
                   12616: 	# no prefix at all
                   12617: 	if (defined($part)) { $keyroot='_'.$part; }
                   12618:     }
                   12619:     return $keyroot;
                   12620: }
                   12621: 
1.71      www      12622: # ---------------------------------------------------------------- Get metadata
                   12623: 
1.599     albertel 12624: my %metaentry;
1.1070    www      12625: my %importedpartids;
1.1172.2.99  raeburn  12626: my %importedrespids;
1.71      www      12627: sub metadata {
1.1172.2.146.  .13(raeb 12628:-23):     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      12629:     $uri=&declutter($uri);
1.288     albertel 12630:     # if it is a non metadata possible uri return quickly
1.529     albertel 12631:     if (($uri eq '') || 
                   12632: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.146.  .1(raebu 12633:22): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12634:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12635: 	return undef;
                   12636:     }
1.1172.2.49  raeburn  12637:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12638: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12639: 	return undef;
1.288     albertel 12640:     }
1.73      www      12641:     my $filename=$uri;
                   12642:     $uri=~s/\.meta$//;
1.172     www      12643: #
                   12644: # Is the metadata already cached?
1.177     www      12645: # Look at timestamp of caching
1.172     www      12646: # Everything is cached by the main uri, libraries are never directly cached
                   12647: #
1.428     albertel 12648:     if (!defined($liburi)) {
1.599     albertel 12649: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12650: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12651:     }
1.1172.2.146.  .13(raeb 12652:-23): 
                   12653:-23): #
                   12654:-23): # If the uri is for an external tool the file from
                   12655:-23): # which metadata should be retrieved depends on whether
                   12656:-23): # the tool had been configured to be gradable (set in the Course
                   12657:-23): # Editor or Resource Editor).
                   12658:-23): #
                   12659:-23): # If a valid symb has been included as the third arg in the call
                   12660:-23): # to &metadata() that can be used to retrieve the value of
                   12661:-23): # parameter_0_gradable set for the resource, and included in the
                   12662:-23): # uploaded map containing the tool. The value is retrieved via
                   12663:-23): # &EXT(), if a valid symb is available.  Otherwise the value of
                   12664:-23): # gradable in the exttool_$marker.db file for the tool instance
                   12665:-23): # is retrieved via &get().
                   12666:-23): #
                   12667:-23): # When lonuserstate::traceroute() calls lonnet::EXT() for
                   12668:-23): # hiddenresource and encrypturl (during course initialization)
                   12669:-23): # the map-level parameter for resource.0.gradable included in the
                   12670:-23): # uploaded map containing the tool will not yet have been stored
                   12671:-23): # in the user_course_parms.db file for the user's session, so in
                   12672:-23): # this case fall back to retrieving gradable status from the
                   12673:-23): # exttool_$marker.db file.
                   12674:-23): #
                   12675:-23): # In order to avoid an infinite loop, &metadata() will return
                   12676:-23): # before a call to &EXT(), if the uri is for an external tool
                   12677:-23): # and the $what for which metadata is being requested is
                   12678:-23): # parameter_0_gradable or 0_gradable.
                   12679:-23): #
                   12680:-23): 
                   12681:-23):     if ($uri =~ /ext\.tool$/) {
                   12682:-23):         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   12683:-23):             return;
                   12684:-23):         } else {
                   12685:-23):             my ($checked,$use_passback);
                   12686:-23):             if ($toolsymb ne '') {
                   12687:-23):                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
                   12688:-23):                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
                   12689:-23):                     $checked = 1;
                   12690:-23):                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   12691:-23):                         $use_passback = 1;
                   12692:-23):                     }
                   12693:-23):                 }
                   12694:-23):             }
                   12695:-23):             unless ($checked) {
                   12696:-23):                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   12697:-23):                 $marker=~s/\D//g;
                   12698:-23):                 if ($marker) {
                   12699:-23):                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   12700:-23):                     $use_passback = $toolsettings{'gradable'};
                   12701:-23):                 }
                   12702:-23):             }
                   12703:-23):             if ($use_passback) {
                   12704:-23):                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   12705:-23):             } else {
                   12706:-23):                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   12707:-23):             }
                   12708:-23):         }
                   12709:-23):     }
                   12710:-23): 
1.428     albertel 12711:     {
1.1069    www      12712: # Imported parts would go here
1.1172.2.99  raeburn  12713:         my @origfiletagids=();
1.1069    www      12714:         my $importedparts=0;
1.1172.2.99  raeburn  12715: 
                   12716: # Imported responseids would go here
                   12717:         my $importedresponses=0;
1.172     www      12718: #
                   12719: # Is this a recursive call for a library?
                   12720: #
1.599     albertel 12721: #	if (! exists($metacache{$uri})) {
                   12722: #	    $metacache{$uri}={};
                   12723: #	}
1.924     albertel 12724: 	my $cachetime = 60*60;
1.171     www      12725:         if ($liburi) {
                   12726: 	    $liburi=&declutter($liburi);
                   12727:             $filename=$liburi;
1.401     bowersj2 12728:         } else {
1.599     albertel 12729: 	    &devalidate_cache_new('meta',$uri);
                   12730: 	    undef(%metaentry);
1.401     bowersj2 12731: 	}
1.140     www      12732:         my %metathesekeys=();
1.73      www      12733:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12734: 	my $metastring;
1.1140    www      12735: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12736: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12737: 	    $metastring = 
1.929     albertel 12738: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12739: 					  ('grade_target' => 'meta'));
                   12740: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12741: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12742:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12743: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12744: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12745: 	    $metastring=&getfile($file);
1.489     albertel 12746: 	}
1.208     albertel 12747:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12748:         my $token;
1.140     www      12749:         undef %metathesekeys;
1.71      www      12750:         while ($token=$parser->get_token) {
1.339     albertel 12751: 	    if ($token->[0] eq 'S') {
                   12752: 		if (defined($token->[2]->{'package'})) {
1.172     www      12753: #
                   12754: # This is a package - get package info
                   12755: #
1.339     albertel 12756: 		    my $package=$token->[2]->{'package'};
                   12757: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12758: 		    if (defined($token->[2]->{'id'})) { 
                   12759: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12760: 		    }
1.599     albertel 12761: 		    if ($metaentry{':packages'}) {
                   12762: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12763: 		    } else {
1.599     albertel 12764: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12765: 		    }
1.736     albertel 12766: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12767: 			my $part=$keyroot;
                   12768: 			$part=~s/^\_//;
1.736     albertel 12769: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12770: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12771: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12772: 			    # ignore package.tab specified default values
                   12773:                             # here &package_tab_default() will fetch those
                   12774: 			    if ($subp eq 'default') { next; }
1.736     albertel 12775: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12776: 			    my $unikey;
                   12777: 			    if ($pack =~ /_0$/) {
                   12778: 				$unikey='parameter_0_'.$name;
                   12779: 				$part=0;
                   12780: 			    } else {
                   12781: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12782: 			    }
1.339     albertel 12783: 			    if ($subp eq 'display') {
                   12784: 				$value.=' [Part: '.$part.']';
                   12785: 			    }
1.599     albertel 12786: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12787: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12788: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12789: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12790: 			    }
1.599     albertel 12791: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12792: 				$metaentry{':'.$unikey}=
                   12793: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12794: 			    }
1.339     albertel 12795: 			}
                   12796: 		    }
                   12797: 		} else {
1.172     www      12798: #
                   12799: # This is not a package - some other kind of start tag
1.339     albertel 12800: #
                   12801: 		    my $entry=$token->[1];
1.1068    www      12802: 		    my $unikey='';
1.175     www      12803: 
1.339     albertel 12804: 		    if ($entry eq 'import') {
1.175     www      12805: #
                   12806: # Importing a library here
1.339     albertel 12807: #
1.1067    www      12808:                         my $location=$parser->get_text('/import');
                   12809:                         my $dir=$filename;
                   12810:                         $dir=~s|[^/]*$||;
                   12811:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  12812: 
                   12813:                         my $importid=$token->[2]->{'id'};
1.1068    www      12814:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  12815: #
                   12816: # Check metadata for imported file to
                   12817: # see if it contained response items
                   12818: #
                   12819:                         my %currmetaentry = %metaentry;
                   12820:                         my $libresponseorder = &metadata($location,'responseorder');
                   12821:                         my $origfile;
                   12822:                         if ($libresponseorder ne '') {
                   12823:                             if ($#origfiletagids<0) {
                   12824:                                 undef(%importedrespids);
                   12825:                                 undef(%importedpartids);
                   12826:                             }
                   12827:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   12828:                             if (@{$importedrespids{$importid}} > 0) {
                   12829:                                 $importedresponses = 1;
                   12830: # We need to get the original file and the imported file to get the response order correct
                   12831: # Load and inspect original file
                   12832:                                 if ($#origfiletagids<0) {
                   12833:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12834:                                     $origfile=&getfile($origfilelocation);
                   12835:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12836:                                 }
                   12837:                             }
                   12838:                         }
                   12839: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12840: # hash populated for imported library file
                   12841:                         %metaentry = %currmetaentry;
                   12842:                         undef(%currmetaentry);
1.1068    www      12843:                         if ($importmode eq 'problem') {
1.1069    www      12844: # Import as problem/response
1.1068    www      12845:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12846:                         } elsif ($importmode eq 'part') {
                   12847: # Import as part(s)
1.1069    www      12848:                            $importedparts=1;
                   12849: # We need to get the original file and the imported file to get the part order correct
                   12850: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  12851: # Load and inspect original file if we didn't do that already
                   12852:                            if ($#origfiletagids<0) {
                   12853:                                undef(%importedrespids);
                   12854:                                undef(%importedpartids);
                   12855:                                if ($origfile eq '') {
                   12856:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12857:                                    $origfile=&getfile($origfilelocation);
                   12858:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12859:                                }
1.1070    www      12860:                            }
                   12861: 
1.1069    www      12862: # Load and inspect imported file
                   12863:                            my $impfile=&getfile($location);
                   12864:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12865:                            if ($#impfilepartids>=0) {
                   12866: # This problem had parts
1.1070    www      12867:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12868:                            } else {
                   12869: # Importing by turning a single problem into a problem part
                   12870: # It gets the import-tags ID as part-ID
                   12871:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12872:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12873:                            }
1.1068    www      12874:                         } else {
                   12875: # Normal import
                   12876:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12877:                            if (defined($token->[2]->{'id'})) {
                   12878:                               $unikey.='_'.$token->[2]->{'id'};
                   12879:                            }
1.1067    www      12880:                         }
                   12881: 
1.339     albertel 12882: 			if ($depthcount<20) {
1.736     albertel 12883: 			    my $metadata = 
1.1172.2.146.  .13(raeb 12884:-23): 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12885: 					  $depthcount+1);
                   12886: 			    foreach my $meta (split(',',$metadata)) {
                   12887: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12888: 				$metathesekeys{$meta}=1;
1.339     albertel 12889: 			    }
1.1068    www      12890: 			
                   12891:                         }
1.1067    www      12892: 		    } else {
                   12893: #
                   12894: # Not importing, some other kind of non-package, non-library start tag
                   12895: # 
                   12896:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12897:                         if (defined($token->[2]->{'id'})) {
                   12898:                             $unikey.='_'.$token->[2]->{'id'};
                   12899:                         }
1.339     albertel 12900: 			if (defined($token->[2]->{'name'})) { 
                   12901: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12902: 			}
                   12903: 			$metathesekeys{$unikey}=1;
1.736     albertel 12904: 			foreach my $param (@{$token->[3]}) {
                   12905: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12906: 				$token->[2]->{$param};
1.339     albertel 12907: 			}
                   12908: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12909: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12910: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12911: 		 # only ws inside the tag, and not in default, so use default
                   12912: 		 # as value
1.599     albertel 12913: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12914: 			} elsif ( $internaltext =~ /\S/ ) {
                   12915: 		  # something interesting inside the tag
                   12916: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12917: 			} else {
1.908     albertel 12918: 		  # no interesting values, don't set a default
1.339     albertel 12919: 			}
1.172     www      12920: # end of not-a-package not-a-library import
1.339     albertel 12921: 		    }
1.172     www      12922: # end of not-a-package start tag
1.339     albertel 12923: 		}
1.172     www      12924: # the next is the end of "start tag"
1.339     albertel 12925: 	    }
                   12926: 	}
1.483     albertel 12927: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12928: 	$extension = lc($extension);
                   12929: 	if ($extension eq 'htm') { $extension='html'; }
                   12930: 
1.737     albertel 12931: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12932: 	    #no specific packages #how's our extension
                   12933: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12934: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12935: 					 \%metathesekeys);
                   12936: 	}
1.883     albertel 12937: 
                   12938: 	if (!exists($metaentry{':packages'})
                   12939: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12940: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12941: 		#no specific packages well let's get default then
                   12942: 		if ($key!~/^default&/) { next; }
1.488     albertel 12943: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12944: 					     \%metathesekeys);
                   12945: 	    }
                   12946: 	}
1.338     www      12947: # are there custom rights to evaluate
1.599     albertel 12948: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12949: 
1.338     www      12950:     #
                   12951:     # Importing a rights file here
1.339     albertel 12952:     #
                   12953: 	    unless ($depthcount) {
1.599     albertel 12954: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12955: 		my $dir=$filename;
                   12956: 		$dir=~s|[^/]*$||;
                   12957: 		$location=&filelocation($dir,$location);
1.736     albertel 12958: 		my $rights_metadata =
1.1172.2.146.  .13(raeb 12959:-23): 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 12960: 			      $depthcount+1);
                   12961: 		foreach my $rights (split(',',$rights_metadata)) {
                   12962: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12963: 		    $metathesekeys{$rights}=1;
1.339     albertel 12964: 		}
                   12965: 	    }
                   12966: 	}
1.737     albertel 12967: 	# uniqifiy package listing
                   12968: 	my %seen;
                   12969: 	my @uniq_packages =
                   12970: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12971: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12972: 
1.1172.2.99  raeburn  12973:         if (($importedresponses) || ($importedparts)) {
                   12974:             if ($importedparts) {
1.1070    www      12975: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12976:                 $metaentry{':partorder'}='';
                   12977:                 $metathesekeys{'partorder'}=1;
                   12978:             }
                   12979:             if ($importedresponses) {
                   12980: # We had imported responses and need to rebuild responseorder
                   12981:                 $metaentry{':responseorder'}='';
                   12982:                 $metathesekeys{'responseorder'}=1;
                   12983:             }
                   12984:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12985:                 my $origid = $origfiletagids[$index+1];
                   12986:                 if ($origfiletagids[$index] eq 'part') {
                   12987: # Original part, part of the problem
                   12988:                     if ($importedparts) {
                   12989:                         $metaentry{':partorder'}.=','.$origid;
                   12990:                     }
                   12991:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12992:                     if ($importedparts) {
                   12993: # We have imported parts at this position
                   12994:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12995:                     }
                   12996:                     if ($importedresponses) {
                   12997: # We have imported responses at this position
                   12998:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12999:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   13000:                         }
                   13001:                     }
                   13002:                 } else {
                   13003: # Original response item, part of the problem
                   13004:                     if ($importedresponses) {
                   13005:                         $metaentry{':responseorder'}.=','.$origid;
                   13006:                     }
                   13007:                 }
                   13008:             }
                   13009:             if ($importedparts) {
                   13010:                 $metaentry{':partorder'}=~s/^\,//;
                   13011:             }
                   13012:             if ($importedresponses) {
                   13013:                 $metaentry{':responseorder'}=~s/^\,//;
                   13014:             }
1.1070    www      13015:         }
                   13016: 
1.737     albertel 13017: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 13018: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  13019: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 13020: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      13021: # this is the end of "was not already recently cached
1.71      www      13022:     }
1.599     albertel 13023:     return $metaentry{':'.$what};
1.261     albertel 13024: }
                   13025: 
1.488     albertel 13026: sub metadata_create_package_def {
1.483     albertel 13027:     my ($uri,$key,$package,$metathesekeys)=@_;
                   13028:     my ($pack,$name,$subp)=split(/\&/,$key);
                   13029:     if ($subp eq 'default') { next; }
                   13030:     
1.599     albertel 13031:     if (defined($metaentry{':packages'})) {
                   13032: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 13033:     } else {
1.599     albertel 13034: 	$metaentry{':packages'}=$package;
1.483     albertel 13035:     }
                   13036:     my $value=$packagetab{$key};
                   13037:     my $unikey;
                   13038:     $unikey='parameter_0_'.$name;
1.599     albertel 13039:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 13040:     $$metathesekeys{$unikey}=1;
1.599     albertel 13041:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   13042: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 13043:     }
1.599     albertel 13044:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   13045: 	$metaentry{':'.$unikey}=
                   13046: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 13047:     }
                   13048: }
                   13049: 
1.261     albertel 13050: sub metadata_generate_part0 {
                   13051:     my ($metadata,$metacache,$uri) = @_;
                   13052:     my %allnames;
1.737     albertel 13053:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 13054: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 13055: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   13056: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 13057: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 13058: 	    $allnames{$name}=$part;
                   13059: 	  }
                   13060: 	}
                   13061:     }
                   13062:     foreach my $name (keys(%allnames)) {
                   13063:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 13064:       my $key=":parameter_0_$name";
1.261     albertel 13065:       $$metacache{"$key.part"}='0';
                   13066:       $$metacache{"$key.name"}=$name;
1.428     albertel 13067:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 13068: 					   $allnames{$name}.'_'.$name.
                   13069: 					   '.type'};
1.428     albertel 13070:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 13071: 			     '.display'};
1.644     www      13072:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 13073:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 13074:       $$metacache{"$key.display"}=$olddis;
                   13075:     }
1.71      www      13076: }
                   13077: 
1.764     albertel 13078: # ------------------------------------------------------ Devalidate title cache
                   13079: 
                   13080: sub devalidate_title_cache {
                   13081:     my ($url)=@_;
                   13082:     if (!$env{'request.course.id'}) { return; }
                   13083:     my $symb=&symbread($url);
                   13084:     if (!$symb) { return; }
                   13085:     my $key=$env{'request.course.id'}."\0".$symb;
                   13086:     &devalidate_cache_new('title',$key);
                   13087: }
                   13088: 
1.1014    droeschl 13089: # ------------------------------------------------- Get the title of a course
                   13090: 
                   13091: sub current_course_title {
                   13092:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   13093: }
1.301     www      13094: # ------------------------------------------------- Get the title of a resource
                   13095: 
                   13096: sub gettitle {
                   13097:     my $urlsymb=shift;
                   13098:     my $symb=&symbread($urlsymb);
1.534     albertel 13099:     if ($symb) {
1.620     albertel 13100: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 13101: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 13102: 	if (defined($cached)) { 
                   13103: 	    return $result;
                   13104: 	}
1.534     albertel 13105: 	my ($map,$resid,$url)=&decode_symb($symb);
                   13106: 	my $title='';
1.907     albertel 13107: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   13108: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   13109: 	} else {
                   13110: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   13111: 		    &GDBM_READER(),0640)) {
                   13112: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   13113: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   13114: 		untie(%bighash);
                   13115: 	    }
1.534     albertel 13116: 	}
                   13117: 	$title=~s/\&colon\;/\:/gs;
                   13118: 	if ($title) {
1.1159    www      13119: # Remember both $symb and $title for dynamic metadata
                   13120:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      13121:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      13122: # Cache this title and then return it
1.599     albertel 13123: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 13124: 	}
                   13125: 	$urlsymb=$url;
                   13126:     }
                   13127:     my $title=&metadata($urlsymb,'title');
                   13128:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   13129:     return $title;
1.301     www      13130: }
1.613     albertel 13131: 
1.614     albertel 13132: sub get_slot {
                   13133:     my ($which,$cnum,$cdom)=@_;
                   13134:     if (!$cnum || !$cdom) {
1.790     albertel 13135: 	(undef,my $courseid)=&whichuser();
1.620     albertel 13136: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   13137: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 13138:     }
1.703     albertel 13139:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   13140:     my %slotinfo;
                   13141:     if (exists($remembered{$key})) {
                   13142: 	$slotinfo{$which} = $remembered{$key};
                   13143:     } else {
                   13144: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   13145: 	&Apache::lonhomework::showhash(%slotinfo);
                   13146: 	my ($tmp)=keys(%slotinfo);
                   13147: 	if ($tmp=~/^error:/) { return (); }
                   13148: 	$remembered{$key} = $slotinfo{$which};
                   13149:     }
1.616     albertel 13150:     if (ref($slotinfo{$which}) eq 'HASH') {
                   13151: 	return %{$slotinfo{$which}};
                   13152:     }
                   13153:     return $slotinfo{$which};
1.614     albertel 13154: }
1.1150    raeburn  13155: 
                   13156: sub get_reservable_slots {
                   13157:     my ($cnum,$cdom,$uname,$udom) = @_;
                   13158:     my $now = time;
                   13159:     my $reservable_info;
                   13160:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   13161:     if (exists($remembered{$key})) {
                   13162:         $reservable_info = $remembered{$key};
                   13163:     } else {
                   13164:         my %resv;
                   13165:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   13166:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   13167:         $reservable_info = \%resv;
                   13168:         $remembered{$key} = $reservable_info;
                   13169:     }
                   13170:     return $reservable_info;
                   13171: }
                   13172: 
                   13173: sub get_course_slots {
                   13174:     my ($cnum,$cdom) = @_;
                   13175:     my $hashid=$cnum.':'.$cdom;
                   13176:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   13177:     if (defined($cached)) {
                   13178:         if (ref($result) eq 'HASH') {
                   13179:             return %{$result};
                   13180:         }
                   13181:     } else {
                   13182:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   13183:         my ($tmp) = keys(%slots);
                   13184:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  13185:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  13186:             return %slots;
                   13187:         }
                   13188:     }
                   13189:     return;
                   13190: }
                   13191: 
                   13192: sub devalidate_slots_cache {
                   13193:     my ($cnum,$cdom)=@_;
                   13194:     my $hashid=$cnum.':'.$cdom;
                   13195:     &devalidate_cache_new('allslots',$hashid);
                   13196: }
                   13197: 
1.1172.2.8  raeburn  13198: sub get_coursechange {
                   13199:     my ($cdom,$cnum) = @_;
                   13200:     if ($cdom eq '' || $cnum eq '') {
                   13201:         return unless ($env{'request.course.id'});
                   13202:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   13203:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   13204:     }
                   13205:     my $hashid=$cdom.'_'.$cnum;
                   13206:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   13207:     if ((defined($cached)) && ($change ne '')) {
                   13208:         return $change;
                   13209:     } else {
                   13210:         my %crshash;
                   13211:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   13212:         if ($crshash{'internal.contentchange'} eq '') {
                   13213:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13214:             if ($change eq '') {
                   13215:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13216:                 $change = $crshash{'internal.created'};
                   13217:             }
                   13218:         } else {
                   13219:             $change = $crshash{'internal.contentchange'};
                   13220:         }
                   13221:         my $cachetime = 600;
                   13222:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   13223:     }
                   13224:     return $change;
                   13225: }
                   13226: 
                   13227: sub devalidate_coursechange_cache {
1.1172.2.146.  .9(raebu 13228:23):     my ($cdom,$cnum)=@_;
                   13229:23):     my $hashid=$cdom.'_'.$cnum;
1.1172.2.8  raeburn  13230:     &devalidate_cache_new('crschange',$hashid);
                   13231: }
                   13232: 
1.1172.2.146.  .9(raebu 13233:23): sub get_suppchange {
                   13234:23):     my ($cdom,$cnum) = @_;
                   13235:23):     if ($cdom eq '' || $cnum eq '') {
                   13236:23):         return unless ($env{'request.course.id'});
                   13237:23):         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   13238:23):         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   13239:23):     }
                   13240:23):     my $hashid=$cdom.'_'.$cnum;
                   13241:23):     my ($change,$cached)=&is_cached_new('suppchange',$hashid);
                   13242:23):     if ((defined($cached)) && ($change ne '')) {
                   13243:23):         return $change;
                   13244:23):     } else {
                   13245:23):         my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
                   13246:23):         if ($crshash{'internal.supplementalchange'} eq '') {
                   13247:23):             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13248:23):             if ($change eq '') {
                   13249:23):                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13250:23):                 $change = $crshash{'internal.created'};
                   13251:23):             }
                   13252:23):         } else {
                   13253:23):             $change = $crshash{'internal.supplementalchange'};
                   13254:23):         }
                   13255:23):         my $cachetime = 600;
                   13256:23):         &do_cache_new('suppchange',$hashid,$change,$cachetime);
                   13257:23):     }
                   13258:23):     return $change;
                   13259:23): }
                   13260:23): 
                   13261:23): sub devalidate_suppchange_cache {
                   13262:23):     my ($cdom,$cnum)=@_;
                   13263:23):     my $hashid=$cdom.'_'.$cnum;
                   13264:23):     &devalidate_cache_new('suppchange',$hashid);
                   13265:23): }
                   13266:23): 
                   13267:23): sub update_supp_caches {
                   13268:23):     my ($cdom,$cnum) = @_;
                   13269:23):     my %servers = &internet_dom_servers($cdom);
                   13270:23):     my @ids=&current_machine_ids();
                   13271:23):     foreach my $server (keys(%servers)) {
                   13272:23):         next if (grep(/^\Q$server\E$/,@ids));
                   13273:23):         my $hashid=$cnum.':'.$cdom;
                   13274:23):         my $cachekey = &escape('showsupp').':'.&escape($hashid);
                   13275:23):         &remote_devalidate_cache($server,[$cachekey]);
                   13276:23):     }
                   13277:23):     &has_unhidden_suppfiles($cnum,$cdom,1,1);
                   13278:23):     &count_supptools($cnum,$cdom,1);
                   13279:23):     my $now = time;
                   13280:23):     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   13281:23):         &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
                   13282:23):     }
                   13283:23):     &put('environment',{'internal.supplementalchange' => $now},
                   13284:23):          $cdom,$cnum);
                   13285:23):     &Apache::lonnet::appenv(
                   13286:23):         {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
                   13287:23):     &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
                   13288:23): }
                   13289:23): 
1.31      www      13290: # ------------------------------------------------- Update symbolic store links
                   13291: 
                   13292: sub symblist {
                   13293:     my ($mapname,%newhash)=@_;
1.438     www      13294:     $mapname=&deversion(&declutter($mapname));
1.31      www      13295:     my %hash;
1.620     albertel 13296:     if (($env{'request.course.fn'}) && (%newhash)) {
                   13297:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 13298:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  13299: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 13300: 		next if ($url eq 'last_known'
                   13301: 			 && $env{'form.no_update_last_known'});
                   13302: 		$hash{declutter($url)}=&encode_symb($mapname,
                   13303: 						    $newhash{$url}->[1],
                   13304: 						    $newhash{$url}->[0]);
1.191     harris41 13305:             }
1.31      www      13306:             if (untie(%hash)) {
                   13307: 		return 'ok';
                   13308:             }
                   13309:         }
                   13310:     }
                   13311:     return 'error';
1.212     www      13312: }
                   13313: 
                   13314: # --------------------------------------------------------------- Verify a symb
                   13315: 
                   13316: sub symbverify {
1.1172.2.11  raeburn  13317:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      13318:     my $thisfn=$thisurl;
1.439     www      13319:     $thisfn=&declutter($thisfn);
1.215     www      13320: # direct jump to resource in page or to a sequence - will construct own symbs
                   13321:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   13322: # check URL part
1.409     www      13323:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      13324: 
1.431     www      13325:     unless ($url eq $thisfn) { return 0; }
1.213     www      13326: 
1.216     www      13327:     $symb=&symbclean($symb);
1.510     www      13328:     $thisurl=&deversion($thisurl);
1.439     www      13329:     $thisfn=&deversion($thisfn);
1.213     www      13330: 
                   13331:     my %bighash;
                   13332:     my $okay=0;
1.431     www      13333: 
1.620     albertel 13334:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13335:                             &GDBM_READER(),0640)) {
1.1032    raeburn  13336:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   13337:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  13338:             if ($map =~ m{^uploaded/.+\.page$}) {
                   13339:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   13340:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   13341:             }
                   13342:         }
                   13343:         my $ids;
1.1172.2.122  raeburn  13344:         if ($map =~ m{^uploaded/.+\.page$}) {
                   13345:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  13346:         } else {
                   13347:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  13348:         }
1.1102    raeburn  13349:         unless ($ids) {
1.1172.2.13  raeburn  13350:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  13351:             $ids=$bighash{$idkey};
1.216     www      13352:         }
                   13353:         if ($ids) {
                   13354: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  13355:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   13356:                 $symb =~ s/\?.+$//;
                   13357:             }
1.800     albertel 13358: 	    foreach my $id (split(/\,/,$ids)) {
                   13359: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      13360:                if (
                   13361:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  13362:    eq $symb) {
1.1172.2.11  raeburn  13363:                    if (ref($encstate)) {
                   13364:                        $$encstate = $bighash{'encrypted_'.$id};
                   13365:                    }
1.1172.2.13  raeburn  13366:                    if (($env{'request.role.adv'}) ||
                   13367:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  13368:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  13369:                        $okay=1;
                   13370:                        last;
                   13371:                    }
                   13372:                }
                   13373:            }
1.216     www      13374:         }
1.213     www      13375: 	untie(%bighash);
                   13376:     }
                   13377:     return $okay;
1.31      www      13378: }
                   13379: 
1.210     www      13380: # --------------------------------------------------------------- Clean-up symb
                   13381: 
                   13382: sub symbclean {
                   13383:     my $symb=shift;
1.568     albertel 13384:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      13385: # remove version from map
                   13386:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      13387: 
1.210     www      13388: # remove version from URL
                   13389:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      13390: 
1.507     www      13391: # remove wrapper
                   13392: 
1.510     www      13393:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 13394:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      13395:     return $symb;
1.409     www      13396: }
                   13397: 
                   13398: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 13399: 
                   13400: sub encode_symb {
                   13401:     my ($map,$resid,$url)=@_;
                   13402:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   13403: }
1.409     www      13404: 
                   13405: sub decode_symb {
1.568     albertel 13406:     my $symb=shift;
                   13407:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   13408:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      13409:     return (&fixversion($map),$resid,&fixversion($url));
                   13410: }
                   13411: 
                   13412: sub fixversion {
                   13413:     my $fn=shift;
1.609     banghart 13414:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      13415:     my %bighash;
                   13416:     my $uri=&clutter($fn);
1.620     albertel 13417:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      13418: # is this cached?
1.599     albertel 13419:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      13420:     if (defined($cached)) { return $result; }
                   13421: # unfortunately not cached, or expired
1.620     albertel 13422:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      13423: 	    &GDBM_READER(),0640)) {
                   13424:  	if ($bighash{'version_'.$uri}) {
                   13425:  	    my $version=$bighash{'version_'.$uri};
1.444     www      13426:  	    unless (($version eq 'mostrecent') || 
                   13427: 		    ($version==&getversion($uri))) {
1.440     www      13428:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   13429:  	    }
                   13430:  	}
                   13431:  	untie %bighash;
1.413     www      13432:     }
1.599     albertel 13433:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      13434: }
                   13435: 
                   13436: sub deversion {
                   13437:     my $url=shift;
                   13438:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   13439:     return $url;
1.210     www      13440: }
                   13441: 
1.31      www      13442: # ------------------------------------------------------ Return symb list entry
                   13443: 
                   13444: sub symbread {
1.1172.2.126  raeburn  13445:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128  raeburn  13446:         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  13447:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128  raeburn  13448:     if (defined($env{$cache_str})) {
1.1172.2.126  raeburn  13449:         unless (ref($possibles) eq 'HASH') {
                   13450:             if ($ignorecachednull) {
                   13451:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   13452:             } else {
                   13453:                 return $env{$cache_str};
                   13454:             }
1.1172.2.66  raeburn  13455:         }
                   13456:     }
1.242     www      13457: # no filename provided? try from environment
1.1172.2.54  raeburn  13458:     unless ($thisfn) {
1.620     albertel 13459:         if ($env{'request.symb'}) {
1.1172.2.128  raeburn  13460:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  13461:         }
                   13462:         $thisfn=$env{'request.filename'};
1.44      www      13463:     }
1.569     albertel 13464:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13465: # is that filename actually a symb? Verify, clean, and return
                   13466:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13467: 	if (&symbverify($thisfn,$1)) {
1.1172.2.128  raeburn  13468: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13469: 	}
1.242     www      13470:     }
1.44      www      13471:     $thisfn=declutter($thisfn);
1.31      www      13472:     my %hash;
1.37      www      13473:     my %bighash;
                   13474:     my $syval='';
1.620     albertel 13475:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.1172.2.128  raeburn  13476:         unless ($ignoresymbdb) {
1.1172.2.126  raeburn  13477:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   13478:                           &GDBM_READER(),0640)) {
1.1172.2.146.  .7(raebu 13479:22): 	        $syval=$hash{$thisfn};
1.1172.2.126  raeburn  13480:                 untie(%hash);
                   13481:             }
1.1172.2.128  raeburn  13482:             if ($syval && $checkforblock) {
                   13483:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126  raeburn  13484:                 if (@blockers) {
                   13485:                     $syval='';
                   13486:                 }
                   13487:             }
1.37      www      13488:         }
                   13489: # ---------------------------------------------------------- There was an entry
                   13490:         if ($syval) {
1.601     albertel 13491: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13492: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13493: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13494: 		    #return $env{$cache_str}='';
1.601     albertel 13495: 		#}    
                   13496: 		#$syval.=$1;
                   13497: 	    #}
1.37      www      13498:         } else {
                   13499: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13500:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13501:                             &GDBM_READER(),0640)) {
1.37      www      13502: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13503:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13504:               unless ($ids) { 
                   13505:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13506:               }
                   13507:               unless ($ids) {
                   13508: # alias?
                   13509: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13510:               }
1.37      www      13511:               if ($ids) {
                   13512: # ------------------------------------------------------------------- Has ID(s)
                   13513:                  my @possibilities=split(/\,/,$ids);
1.39      www      13514:                  if ($#possibilities==0) {
                   13515: # ----------------------------------------------- There is only one possibility
1.37      www      13516: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13517: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13518: 						    $resid,$thisfn);
1.1172.2.66  raeburn  13519:                      if (ref($possibles) eq 'HASH') {
1.1172.2.126  raeburn  13520:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   13521:                              $possibles->{$syval} = 1;
                   13522:                          }
1.1172.2.66  raeburn  13523:                      }
                   13524:                      if ($checkforblock) {
1.1172.2.126  raeburn  13525:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127  raeburn  13526:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126  raeburn  13527:                              if (@blockers) {
                   13528:                                  $syval = '';
                   13529:                                  untie(%bighash);
                   13530:                                  return $env{$cache_str}='';
                   13531:                              }
1.1172.2.66  raeburn  13532:                          }
                   13533:                      }
                   13534:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      13535: # ------------------------------------------ There is more than one possibility
                   13536:                      my $realpossible=0;
1.800     albertel 13537:                      foreach my $id (@possibilities) {
                   13538: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  13539:                          my $canaccess;
                   13540:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13541:                              $canaccess = 1;
                   13542:                          } else {
                   13543:                              $canaccess = &allowed('bre',$file);
                   13544:                          }
                   13545:                          if ($canaccess) {
                   13546:          		     my ($mapid,$resid)=split(/\./,$id);
                   13547:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13548:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13549:                                                              $resid,$thisfn);
1.1172.2.126  raeburn  13550:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127  raeburn  13551:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  13552:                                  if ($checkforblock) {
1.1172.2.127  raeburn  13553:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126  raeburn  13554:                                      if (@blockers > 0) {
                   13555:                                          $syval = '';
                   13556:                                      } else {
1.1172.2.66  raeburn  13557:                                          $syval = $poss_syval;
                   13558:                                          $realpossible++;
                   13559:                                      }
                   13560:                                  } else {
                   13561:                                      $syval = $poss_syval;
                   13562:                                      $realpossible++;
                   13563:                                  }
1.1172.2.126  raeburn  13564:                                  if ($syval) {
                   13565:                                      if (ref($possibles) eq 'HASH') {
                   13566:                                          $possibles->{$syval} = 1;
                   13567:                                      }
                   13568:                                  }
1.1172.2.66  raeburn  13569:                              }
1.39      www      13570: 			 }
1.191     harris41 13571:                      }
1.39      www      13572: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13573:                  } else {
                   13574:                      $syval='';
1.37      www      13575:                  }
                   13576: 	      }
1.1172.2.66  raeburn  13577:               untie(%bighash);
1.481     raeburn  13578:            }
1.31      www      13579:         }
1.62      www      13580:         if ($syval) {
1.1172.2.128  raeburn  13581: 	    return $env{$cache_str}=$syval;
1.62      www      13582:         }
1.31      www      13583:     }
1.949     raeburn  13584:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13585:     return $env{$cache_str}='';
1.31      www      13586: }
                   13587: 
                   13588: # ---------------------------------------------------------- Return random seed
                   13589: 
1.32      www      13590: sub numval {
                   13591:     my $txt=shift;
                   13592:     $txt=~tr/A-J/0-9/;
                   13593:     $txt=~tr/a-j/0-9/;
                   13594:     $txt=~tr/K-T/0-9/;
                   13595:     $txt=~tr/k-t/0-9/;
                   13596:     $txt=~tr/U-Z/0-5/;
                   13597:     $txt=~tr/u-z/0-5/;
                   13598:     $txt=~s/\D//g;
1.564     albertel 13599:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13600:     return int($txt);
1.368     albertel 13601: }
                   13602: 
1.484     albertel 13603: sub numval2 {
                   13604:     my $txt=shift;
                   13605:     $txt=~tr/A-J/0-9/;
                   13606:     $txt=~tr/a-j/0-9/;
                   13607:     $txt=~tr/K-T/0-9/;
                   13608:     $txt=~tr/k-t/0-9/;
                   13609:     $txt=~tr/U-Z/0-5/;
                   13610:     $txt=~tr/u-z/0-5/;
                   13611:     $txt=~s/\D//g;
                   13612:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13613:     my $total;
                   13614:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13615:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13616:     return int($total);
                   13617: }
                   13618: 
1.575     albertel 13619: sub numval3 {
                   13620:     use integer;
                   13621:     my $txt=shift;
                   13622:     $txt=~tr/A-J/0-9/;
                   13623:     $txt=~tr/a-j/0-9/;
                   13624:     $txt=~tr/K-T/0-9/;
                   13625:     $txt=~tr/k-t/0-9/;
                   13626:     $txt=~tr/U-Z/0-5/;
                   13627:     $txt=~tr/u-z/0-5/;
                   13628:     $txt=~s/\D//g;
                   13629:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13630:     my $total;
                   13631:     foreach my $val (@txts) { $total+=$val; }
                   13632:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13633:     return $total;
                   13634: }
                   13635: 
1.675     albertel 13636: sub digest {
                   13637:     my ($data)=@_;
                   13638:     my $digest=&Digest::MD5::md5($data);
                   13639:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13640:     my ($e,$f);
                   13641:     {
                   13642:         use integer;
                   13643:         $e=($a+$b);
                   13644:         $f=($c+$d);
                   13645:         if ($_64bit) {
                   13646:             $e=(($e<<32)>>32);
                   13647:             $f=(($f<<32)>>32);
                   13648:         }
                   13649:     }
                   13650:     if (wantarray) {
                   13651: 	return ($e,$f);
                   13652:     } else {
                   13653: 	my $g;
                   13654: 	{
                   13655: 	    use integer;
                   13656: 	    $g=($e+$f);
                   13657: 	    if ($_64bit) {
                   13658: 		$g=(($g<<32)>>32);
                   13659: 	    }
                   13660: 	}
                   13661: 	return $g;
                   13662:     }
                   13663: }
                   13664: 
1.368     albertel 13665: sub latest_rnd_algorithm_id {
1.675     albertel 13666:     return '64bit5';
1.366     albertel 13667: }
1.32      www      13668: 
1.503     albertel 13669: sub get_rand_alg {
                   13670:     my ($courseid)=@_;
1.790     albertel 13671:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13672:     if ($courseid) {
1.620     albertel 13673: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13674:     }
                   13675:     return &latest_rnd_algorithm_id();
                   13676: }
                   13677: 
1.562     albertel 13678: sub validCODE {
                   13679:     my ($CODE)=@_;
                   13680:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13681:     return 0;
                   13682: }
                   13683: 
1.491     albertel 13684: sub getCODE {
1.620     albertel 13685:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13686:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13687: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13688: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13689: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13690:     }
                   13691:     return undef;
                   13692: }
1.1133    foxr     13693: #
                   13694: #  Determines the random seed for a specific context:
                   13695: #
                   13696: # parameters:
                   13697: #   symb      - in course context the symb for the seed.
                   13698: #   course_id - The course id of the form domain_coursenum.
                   13699: #   domain    - Domain for the user.
                   13700: #   course    - Course for the user.
                   13701: #   cenv      - environment of the course.
                   13702: #
                   13703: # NOTE:
                   13704: #   All parameters are picked out of the environment if missing
                   13705: #   or not defined.
                   13706: #   If a symb cannot be determined the current time is used instead.
                   13707: #
                   13708: #  For a given well defined symb, courside, domain, username,
                   13709: #  and course environment, the seed is reproducible.
                   13710: #
1.31      www      13711: sub rndseed {
1.1133    foxr     13712:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13713:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13714:     if (!defined($symb)) {
1.366     albertel 13715: 	unless ($symb=$wsymb) { return time; }
                   13716:     }
1.1146    foxr     13717:     if (!defined $courseid) { 
                   13718: 	$courseid=$wcourseid; 
                   13719:     }
                   13720:     if (!defined $domain) { $domain=$wdomain; }
                   13721:     if (!defined $username) { $username=$wusername }
1.1133    foxr     13722: 
                   13723:     my $which;
                   13724:     if (defined($cenv->{'rndseed'})) {
                   13725: 	$which = $cenv->{'rndseed'};
                   13726:     } else {
                   13727: 	$which =&get_rand_alg($courseid);
                   13728:     }
1.491     albertel 13729:     if (defined(&getCODE())) {
1.675     albertel 13730: 	if ($which eq '64bit5') {
                   13731: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   13732: 	} elsif ($which eq '64bit4') {
1.575     albertel 13733: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   13734: 	} else {
                   13735: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   13736: 	}
1.675     albertel 13737:     } elsif ($which eq '64bit5') {
                   13738: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 13739:     } elsif ($which eq '64bit4') {
                   13740: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 13741:     } elsif ($which eq '64bit3') {
                   13742: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 13743:     } elsif ($which eq '64bit2') {
                   13744: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13745:     } elsif ($which eq '64bit') {
                   13746: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13747:     }
                   13748:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13749: }
                   13750: 
                   13751: sub rndseed_32bit {
                   13752:     my ($symb,$courseid,$domain,$username)=@_;
                   13753:     {
                   13754: 	use integer;
                   13755: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13756: 	my $symbseed=numval($symb) << 22;
                   13757: 	my $namechck=unpack("%32C*",$username) << 17;
                   13758: 	my $nameseed=numval($username) << 12;
                   13759: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13760: 	my $courseseed=unpack("%32C*",$courseid);
                   13761: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13762: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13763: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13764: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13765: 	return $num;
                   13766:     }
                   13767: }
                   13768: 
                   13769: sub rndseed_64bit {
                   13770:     my ($symb,$courseid,$domain,$username)=@_;
                   13771:     {
                   13772: 	use integer;
                   13773: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13774: 	my $symbseed=numval($symb) << 10;
                   13775: 	my $namechck=unpack("%32S*",$username);
                   13776: 	
                   13777: 	my $nameseed=numval($username) << 21;
                   13778: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13779: 	my $courseseed=unpack("%32S*",$courseid);
                   13780: 	
                   13781: 	my $num1=$symbchck+$symbseed+$namechck;
                   13782: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13783: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13784: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13785: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13786: 	return "$num1,$num2";
1.155     albertel 13787:     }
1.366     albertel 13788: }
                   13789: 
1.443     albertel 13790: sub rndseed_64bit2 {
                   13791:     my ($symb,$courseid,$domain,$username)=@_;
                   13792:     {
                   13793: 	use integer;
                   13794: 	# strings need to be an even # of cahracters long, it it is odd the
                   13795:         # last characters gets thrown away
                   13796: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13797: 	my $symbseed=numval($symb) << 10;
                   13798: 	my $namechck=unpack("%32S*",$username.' ');
                   13799: 	
                   13800: 	my $nameseed=numval($username) << 21;
1.501     albertel 13801: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13802: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13803: 	
                   13804: 	my $num1=$symbchck+$symbseed+$namechck;
                   13805: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13806: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13807: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13808: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13809: 	return "$num1,$num2";
                   13810:     }
                   13811: }
                   13812: 
                   13813: sub rndseed_64bit3 {
                   13814:     my ($symb,$courseid,$domain,$username)=@_;
                   13815:     {
                   13816: 	use integer;
                   13817: 	# strings need to be an even # of cahracters long, it it is odd the
                   13818:         # last characters gets thrown away
                   13819: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13820: 	my $symbseed=numval2($symb) << 10;
                   13821: 	my $namechck=unpack("%32S*",$username.' ');
                   13822: 	
                   13823: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13824: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13825: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13826: 	
                   13827: 	my $num1=$symbchck+$symbseed+$namechck;
                   13828: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13829: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13830: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13831: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13832: 	
1.503     albertel 13833: 	return "$num1:$num2";
1.443     albertel 13834:     }
                   13835: }
                   13836: 
1.575     albertel 13837: sub rndseed_64bit4 {
                   13838:     my ($symb,$courseid,$domain,$username)=@_;
                   13839:     {
                   13840: 	use integer;
                   13841: 	# strings need to be an even # of cahracters long, it it is odd the
                   13842:         # last characters gets thrown away
                   13843: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13844: 	my $symbseed=numval3($symb) << 10;
                   13845: 	my $namechck=unpack("%32S*",$username.' ');
                   13846: 	
                   13847: 	my $nameseed=numval3($username) << 21;
                   13848: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13849: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13850: 	
                   13851: 	my $num1=$symbchck+$symbseed+$namechck;
                   13852: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13853: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13854: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13855: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13856: 	
1.575     albertel 13857: 	return "$num1:$num2";
                   13858:     }
                   13859: }
                   13860: 
1.675     albertel 13861: sub rndseed_64bit5 {
                   13862:     my ($symb,$courseid,$domain,$username)=@_;
                   13863:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13864:     return "$num1:$num2";
                   13865: }
                   13866: 
1.366     albertel 13867: sub rndseed_CODE_64bit {
                   13868:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13869:     {
1.366     albertel 13870: 	use integer;
1.443     albertel 13871: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13872: 	my $symbseed=numval2($symb);
1.491     albertel 13873: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13874: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13875: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13876: 	my $num1=$symbseed+$CODEchck;
                   13877: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13878: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13879: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13880: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13881: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13882: 	return "$num1:$num2";
1.366     albertel 13883:     }
                   13884: }
                   13885: 
1.575     albertel 13886: sub rndseed_CODE_64bit4 {
                   13887:     my ($symb,$courseid,$domain,$username)=@_;
                   13888:     {
                   13889: 	use integer;
                   13890: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13891: 	my $symbseed=numval3($symb);
                   13892: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13893: 	my $CODEseed=numval3(&getCODE());
                   13894: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13895: 	my $num1=$symbseed+$CODEchck;
                   13896: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13897: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13898: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13899: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13900: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13901: 	return "$num1:$num2";
                   13902:     }
                   13903: }
                   13904: 
1.675     albertel 13905: sub rndseed_CODE_64bit5 {
                   13906:     my ($symb,$courseid,$domain,$username)=@_;
                   13907:     my $code = &getCODE();
                   13908:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13909:     return "$num1:$num2";
                   13910: }
                   13911: 
1.366     albertel 13912: sub setup_random_from_rndseed {
                   13913:     my ($rndseed)=@_;
1.503     albertel 13914:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  13915: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13916:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13917:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13918:         } else {
                   13919:             &Math::Random::random_set_seed($num1,$num2);
                   13920:         }
1.366     albertel 13921:     } else {
                   13922: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13923:     }
1.36      albertel 13924: }
                   13925: 
1.474     albertel 13926: sub latest_receipt_algorithm_id {
1.835     albertel 13927:     return 'receipt3';
1.474     albertel 13928: }
                   13929: 
1.480     www      13930: sub recunique {
                   13931:     my $fucourseid=shift;
                   13932:     my $unique;
1.835     albertel 13933:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13934: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13935: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13936:     } else {
                   13937: 	$unique=$perlvar{'lonReceipt'};
                   13938:     }
                   13939:     return unpack("%32C*",$unique);
                   13940: }
                   13941: 
                   13942: sub recprefix {
                   13943:     my $fucourseid=shift;
                   13944:     my $prefix;
1.835     albertel 13945:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13946: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13947: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13948:     } else {
                   13949: 	$prefix=$perlvar{'lonHostID'};
                   13950:     }
                   13951:     return unpack("%32C*",$prefix);
                   13952: }
                   13953: 
1.76      www      13954: sub ireceipt {
1.474     albertel 13955:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13956: 
                   13957:     my $return =&recprefix($fucourseid).'-';
                   13958: 
                   13959:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13960: 	$env{'request.state'} eq 'construct') {
                   13961: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13962: 	return $return;
                   13963:     }
                   13964: 
1.76      www      13965:     my $cuname=unpack("%32C*",$funame);
                   13966:     my $cudom=unpack("%32C*",$fudom);
                   13967:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13968:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13969:     my $cunique=&recunique($fucourseid);
1.474     albertel 13970:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13971:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13972: 
1.790     albertel 13973: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13974: 			       
                   13975: 	$return.= ($cunique%$cuname+
                   13976: 		   $cunique%$cudom+
                   13977: 		   $cusymb%$cuname+
                   13978: 		   $cusymb%$cudom+
                   13979: 		   $cucourseid%$cuname+
                   13980: 		   $cucourseid%$cudom+
                   13981: 		   $cpart%$cuname+
                   13982: 		   $cpart%$cudom);
                   13983:     } else {
                   13984: 	$return.= ($cunique%$cuname+
                   13985: 		   $cunique%$cudom+
                   13986: 		   $cusymb%$cuname+
                   13987: 		   $cusymb%$cudom+
                   13988: 		   $cucourseid%$cuname+
                   13989: 		   $cucourseid%$cudom);
                   13990:     }
                   13991:     return $return;
1.76      www      13992: }
                   13993: 
                   13994: sub receipt {
1.474     albertel 13995:     my ($part)=@_;
1.790     albertel 13996:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13997:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13998: }
1.260     ng       13999: 
1.790     albertel 14000: sub whichuser {
                   14001:     my ($passedsymb)=@_;
                   14002:     my ($symb,$courseid,$domain,$name,$publicuser);
                   14003:     if (defined($env{'form.grade_symb'})) {
                   14004: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   14005: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   14006: 	if (!$allowed &&
                   14007: 	    exists($env{'request.course.sec'}) &&
                   14008: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   14009: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   14010: 			      '/'.$env{'request.course.sec'});
                   14011: 	}
                   14012: 	if ($allowed) {
                   14013: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   14014: 	    $courseid=$tmp_courseid;
                   14015: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   14016: 	    ($name)=&get_env_multiple('form.grade_username');
                   14017: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   14018: 	}
                   14019:     }
                   14020:     if (!$passedsymb) {
                   14021: 	$symb=&symbread();
                   14022:     } else {
                   14023: 	$symb=$passedsymb;
                   14024:     }
                   14025:     $courseid=$env{'request.course.id'};
                   14026:     $domain=$env{'user.domain'};
                   14027:     $name=$env{'user.name'};
                   14028:     if ($name eq 'public' && $domain eq 'public') {
                   14029: 	if (!defined($env{'form.username'})) {
                   14030: 	    $env{'form.username'}.=time.rand(10000000);
                   14031: 	}
                   14032: 	$name.=$env{'form.username'};
                   14033:     }
                   14034:     return ($symb,$courseid,$domain,$name,$publicuser);
                   14035: 
                   14036: }
                   14037: 
1.36      albertel 14038: # ------------------------------------------------------------ Serves up a file
1.472     albertel 14039: # returns either the contents of the file or 
                   14040: # -1 if the file doesn't exist
1.481     raeburn  14041: #
                   14042: # if the target is a file that was uploaded via DOCS, 
                   14043: # a check will be made to see if a current copy exists on the local server,
                   14044: # if it does this will be served, otherwise a copy will be retrieved from
                   14045: # the home server for the course and stored in /home/httpd/html/userfiles on
                   14046: # the local server.   
1.472     albertel 14047: 
1.36      albertel 14048: sub getfile {
1.538     albertel 14049:     my ($file) = @_;
1.609     banghart 14050:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 14051:     &repcopy($file);
                   14052:     return &readfile($file);
                   14053: }
                   14054: 
                   14055: sub repcopy_userfile {
                   14056:     my ($file)=@_;
1.1142    raeburn  14057:     my $londocroot = $perlvar{'lonDocRoot'};
                   14058:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  14059:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 14060:     my ($cdom,$cnum,$filename) = 
1.811     albertel 14061: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 14062:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   14063:     if (-e "$file") {
1.828     www      14064: # we already have a local copy, check it out
1.538     albertel 14065: 	my @fileinfo = stat($file);
1.828     www      14066: 	my $rtncode;
                   14067: 	my $info;
1.538     albertel 14068: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 14069: 	if ($lwpresp ne 'ok') {
1.828     www      14070: # there is no such file anymore, even though we had a local copy
1.482     albertel 14071: 	    if ($rtncode eq '404') {
1.538     albertel 14072: 		unlink($file);
1.482     albertel 14073: 	    }
                   14074: 	    return -1;
                   14075: 	}
                   14076: 	if ($info < $fileinfo[9]) {
1.828     www      14077: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  14078: 	    return 'ok';
1.828     www      14079: 	} else {
                   14080: # the file is outdated, get rid of it
                   14081: 	    unlink($file);
1.482     albertel 14082: 	}
1.828     www      14083:     }
                   14084: # one way or the other, at this point, we don't have the file
                   14085: # construct the correct path for the file
                   14086:     my @parts = ($cdom,$cnum); 
                   14087:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   14088: 	push @parts, split(/\//,$1);
                   14089:     }
                   14090:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   14091:     foreach my $part (@parts) {
                   14092: 	$path .= '/'.$part;
                   14093: 	if (!-e $path) {
                   14094: 	    mkdir($path,0770);
1.482     albertel 14095: 	}
                   14096:     }
1.828     www      14097: # now the path exists for sure
                   14098: # get a user agent
                   14099:     my $ua=new LWP::UserAgent;
                   14100:     my $transferfile=$file.'.in.transfer';
                   14101: # FIXME: this should flock
                   14102:     if (-e $transferfile) { return 'ok'; }
                   14103:     my $request;
                   14104:     $uri=~s/^\///;
1.980     raeburn  14105:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  14106:     my $hostname = &hostname($homeserver);
1.980     raeburn  14107:     my $protocol = $protocol{$homeserver};
                   14108:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  14109:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      14110:     my $response=$ua->request($request,$transferfile);
                   14111: # did it work?
                   14112:     if ($response->is_error()) {
                   14113: 	unlink($transferfile);
                   14114: 	&logthis("Userfile repcopy failed for $uri");
                   14115: 	return -1;
                   14116:     }
                   14117: # worked, rename the transfer file
                   14118:     rename($transferfile,$file);
1.607     raeburn  14119:     return 'ok';
1.481     raeburn  14120: }
                   14121: 
1.517     albertel 14122: sub tokenwrapper {
                   14123:     my $uri=shift;
1.980     raeburn  14124:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 14125:     $uri=~s|^/||;
1.620     albertel 14126:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 14127:     my $token=$1;
1.552     albertel 14128:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   14129:     if ($udom && $uname && $file) {
                   14130: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  14131:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  14132:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.120  raeburn  14133:         my $hostname = &hostname($homeserver);
1.980     raeburn  14134:         my $protocol = $protocol{$homeserver};
                   14135:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  14136:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 14137:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   14138:                                '&tokenissued='.$perlvar{'lonHostID'};
                   14139:     } else {
                   14140:         return '/adm/notfound.html';
                   14141:     }
                   14142: }
                   14143: 
1.828     www      14144: # call with reqtype HEAD: get last modification time
                   14145: # call with reqtype GET: get the file contents
                   14146: # Do not call this with reqtype GET for large files! It loads everything into memory
                   14147: #
1.481     raeburn  14148: sub getuploaded {
                   14149:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   14150:     $uri=~s/^\///;
1.980     raeburn  14151:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  14152:     my $hostname = &hostname($homeserver);
1.980     raeburn  14153:     my $protocol = $protocol{$homeserver};
                   14154:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  14155:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  14156:     my $ua=new LWP::UserAgent;
                   14157:     my $request=new HTTP::Request($reqtype,$uri);
                   14158:     my $response=$ua->request($request);
                   14159:     $$rtncode = $response->code;
1.482     albertel 14160:     if (! $response->is_success()) {
                   14161: 	return 'failed';
                   14162:     }      
                   14163:     if ($reqtype eq 'HEAD') {
1.486     www      14164: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 14165:     } elsif ($reqtype eq 'GET') {
                   14166: 	$$info = $response->content;
1.472     albertel 14167:     }
1.482     albertel 14168:     return 'ok';
1.36      albertel 14169: }
                   14170: 
1.481     raeburn  14171: sub readfile {
                   14172:     my $file = shift;
                   14173:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   14174:     my $fh;
1.1172.2.96  raeburn  14175:     open($fh,"<",$file);
1.481     raeburn  14176:     my $a='';
1.800     albertel 14177:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  14178:     return $a;
                   14179: }
                   14180: 
1.36      albertel 14181: sub filelocation {
1.590     banghart 14182:     my ($dir,$file) = @_;
                   14183:     my $location;
                   14184:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 14185: 
                   14186:     if ($file =~ m-^/adm/-) {
                   14187: 	$file=~s-^/adm/wrapper/-/-;
                   14188: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   14189:     }
1.882     albertel 14190: 
1.1139    www      14191:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  14192:         $location = $file;
1.609     banghart 14193:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 14194:         my ($udom,$uname,$filename)=
1.811     albertel 14195:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 14196:         my $home=&homeserver($uname,$udom);
                   14197:         my $is_me=0;
                   14198:         my @ids=&current_machine_ids();
                   14199:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   14200:         if ($is_me) {
1.1117    foxr     14201:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 14202:         } else {
                   14203:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   14204:   	      $udom.'/'.$uname.'/'.$filename;
                   14205:         }
1.882     albertel 14206:     } elsif ($file =~ m-^/adm/-) {
                   14207: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 14208:     } else {
                   14209:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      14210:         $file=~s:^/(res|priv)/:/:;
                   14211:         my $space=$1;
1.590     banghart 14212:         if ( !( $file =~ m:^/:) ) {
                   14213:             $location = $dir. '/'.$file;
                   14214:         } else {
1.1142    raeburn  14215:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 14216:         }
1.59      albertel 14217:     }
1.590     banghart 14218:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 14219:     while ($location=~m{/\.\./}) {
                   14220: 	if ($location =~ m{/[^/]+/\.\./}) {
                   14221: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   14222: 	} else {
                   14223: 	    $location=~ s{/\.\./}{/}g;
                   14224: 	}
                   14225:     } #remove dir/..
1.590     banghart 14226:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   14227:     return $location;
1.46      www      14228: }
1.36      albertel 14229: 
1.46      www      14230: sub hreflocation {
                   14231:     my ($dir,$file)=@_;
1.980     raeburn  14232:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 14233: 	$file=filelocation($dir,$file);
1.700     albertel 14234:     } elsif ($file=~m-^/adm/-) {
                   14235: 	$file=~s-^/adm/wrapper/-/-;
                   14236: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 14237:     }
                   14238:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   14239: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   14240:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  14241: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   14242: 	        {/uploaded/$1/$2/}x;
1.46      www      14243:     }
1.913     albertel 14244:     if ($file=~ m{^/userfiles/}) {
                   14245: 	$file =~ s{^/userfiles/}{/uploaded/};
                   14246:     }
1.462     albertel 14247:     return $file;
1.465     albertel 14248: }
                   14249: 
1.1139    www      14250: 
                   14251: 
                   14252: 
                   14253: 
1.465     albertel 14254: sub current_machine_domains {
1.853     albertel 14255:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   14256: }
                   14257: 
                   14258: sub machine_domains {
                   14259:     my ($hostname) = @_;
1.465     albertel 14260:     my @domains;
1.838     albertel 14261:     my %hostname = &all_hostnames();
1.465     albertel 14262:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  14263: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 14264: 	if ($hostname eq $name) {
1.844     albertel 14265: 	    push(@domains,&host_domain($id));
1.465     albertel 14266: 	}
                   14267:     }
                   14268:     return @domains;
                   14269: }
                   14270: 
                   14271: sub current_machine_ids {
1.853     albertel 14272:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   14273: }
                   14274: 
                   14275: sub machine_ids {
                   14276:     my ($hostname) = @_;
                   14277:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 14278:     my @ids;
1.888     albertel 14279:     my %name_to_host = &all_names();
1.889     albertel 14280:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   14281: 	return @{ $name_to_host{$hostname} };
                   14282:     }
                   14283:     return;
1.31      www      14284: }
                   14285: 
1.824     raeburn  14286: sub additional_machine_domains {
                   14287:     my @domains;
1.1172.2.142  raeburn  14288:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
                   14289:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
                   14290:             while( my $line = <$fh>) {
                   14291:                 chomp($line);
                   14292:                 $line =~ s/\s//g;
                   14293:                 push(@domains,$line);
                   14294:             }
                   14295:             close($fh);
                   14296:         }
1.824     raeburn  14297:     }
                   14298:     return @domains;
                   14299: }
                   14300: 
                   14301: sub default_login_domain {
                   14302:     my $domain = $perlvar{'lonDefDomain'};
                   14303:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   14304:     foreach my $posdom (&current_machine_domains(),
                   14305:                         &additional_machine_domains()) {
                   14306:         if (lc($posdom) eq lc($testdomain)) {
                   14307:             $domain=$posdom;
                   14308:             last;
                   14309:         }
                   14310:     }
                   14311:     return $domain;
                   14312: }
                   14313: 
1.1172.2.106  raeburn  14314: sub shared_institution {
1.1172.2.136  raeburn  14315:     my ($dom,$lonhost) = @_;
                   14316:     if ($lonhost eq '') {
                   14317:         $lonhost = $perlvar{'lonHostID'};
                   14318:     }
1.1172.2.106  raeburn  14319:     my $same_intdom;
1.1172.2.136  raeburn  14320:     my $hostintdom = &internet_dom($lonhost);
1.1172.2.106  raeburn  14321:     if ($hostintdom ne '') {
                   14322:         my %iphost = &get_iphost();
                   14323:         my $primary_id = &domain($dom,'primary');
                   14324:         my $primary_ip = &get_host_ip($primary_id);
                   14325:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   14326:             foreach my $id (@{$iphost{$primary_ip}}) {
                   14327:                 my $intdom = &internet_dom($id);
                   14328:                 if ($intdom eq $hostintdom) {
                   14329:                     $same_intdom = 1;
                   14330:                     last;
                   14331:                 }
                   14332:             }
                   14333:         }
                   14334:     }
                   14335:     return $same_intdom;
                   14336: }
                   14337: 
1.1172.2.120  raeburn  14338: sub uses_sts {
                   14339:     my ($ignore_cache) = @_;
                   14340:     my $lonhost = $perlvar{'lonHostID'};
                   14341:     my $hostname = &hostname($lonhost);
                   14342:     my $sts_on;
                   14343:     if ($protocol{$lonhost} eq 'https') {
                   14344:         my $cachetime = 12*3600;
                   14345:         if (!$ignore_cache) {
                   14346:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   14347:             if (defined($cached)) {
                   14348:                 return $sts_on;
                   14349:             }
                   14350:         }
1.1172.2.121  raeburn  14351:         my $ua=new LWP::UserAgent;
1.1172.2.120  raeburn  14352:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   14353:         my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121  raeburn  14354:         my $response=$ua->request($request);
1.1172.2.120  raeburn  14355:         if ($response->is_success) {
                   14356:             my $has_sts = $response->header('Strict-Transport-Security');
                   14357:             if ($has_sts eq '') {
                   14358:                 $sts_on = 0;
                   14359:             } else {
                   14360:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   14361:                     my $maxage = $1;
                   14362:                     if ($maxage) {
                   14363:                         $sts_on = 1;
                   14364:                     } else {
                   14365:                         $sts_on = 0;
                   14366:                     }
                   14367:                 } else {
                   14368:                     $sts_on = 0;
                   14369:                 }
                   14370:             }
                   14371:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   14372:         }
                   14373:     }
                   14374:     return;
                   14375: }
                   14376: 
1.1172.2.142  raeburn  14377: sub waf_allssl {
                   14378:     my ($host_name) = @_;
                   14379:     my $alias = &get_proxy_alias();
                   14380:     if ($host_name eq '') {
                   14381:         $host_name = $ENV{'SERVER_NAME'};
                   14382:     }
                   14383:     if (($host_name ne '') && ($alias eq $host_name)) {
                   14384:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   14385:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   14386:         if ($defdomdefaults{'waf_sslopt'}) {
                   14387:             return $defdomdefaults{'waf_sslopt'};
                   14388:         }
                   14389:     }
                   14390:     return;
                   14391: }
                   14392: 
1.1172.2.134  raeburn  14393: sub get_requestor_ip {
                   14394:     my ($r,$nolookup,$noproxy) = @_;
                   14395:     my $from_ip;
                   14396:     if (ref($r)) {
1.1172.2.142  raeburn  14397:         if ($r->can('useragent_ip')) {
                   14398:             if ($noproxy && $r->can('client_ip')) {
                   14399:                 $from_ip = $r->client_ip();
                   14400:             } else {
                   14401:                 $from_ip = $r->useragent_ip();
                   14402:             }
                   14403:         } elsif ($r->connection->can('remote_ip')) {
                   14404:             $from_ip = $r->connection->remote_ip();
                   14405:         } else {
                   14406:             $from_ip = $r->get_remote_host($nolookup);
                   14407:         }
1.1172.2.134  raeburn  14408:     } else {
                   14409:         $from_ip = $ENV{'REMOTE_ADDR'};
                   14410:     }
1.1172.2.142  raeburn  14411:     return $from_ip if ($noproxy);
                   14412:    # Who controls proxy settings for server
                   14413:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14414:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   14415:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
                   14416:         if ($proxyinfo->{'vpnint'}) {
                   14417:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
                   14418:                 return $from_ip;
                   14419:             }
                   14420:         }
                   14421:         if ($proxyinfo->{'trusted'}) {
                   14422:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   14423:                 my $ipheader = $proxyinfo->{'ipheader'};
                   14424:                 my ($ip,$xfor);
                   14425:                 if (ref($r)) {
                   14426:                     if ($ipheader) {
                   14427:                         $ip = $r->headers_in->{$ipheader};
                   14428:                     }
                   14429:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   14430:                 } else {
                   14431:                     if ($ipheader) {
                   14432:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   14433:                     }
                   14434:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   14435:                 }
                   14436:                 if (($ip eq '') && ($xfor ne '')) {
                   14437:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   14438:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   14439:                             $ip = $poss_ip;
                   14440:                             last;
                   14441:                         }
                   14442:                     }
                   14443:                 }
                   14444:                 if ($ip ne '') {
                   14445:                     return $ip;
                   14446:                 }
                   14447:             }
                   14448:         }
                   14449:     }
1.1172.2.134  raeburn  14450:     return $from_ip;
                   14451: }
                   14452: 
1.1172.2.142  raeburn  14453: sub get_proxy_settings {
                   14454:     my ($dom_in_use) = @_;
                   14455:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   14456:     my $proxyinfo = {
                   14457:                        ipheader => $domdefaults{'waf_ipheader'},
                   14458:                        trusted  => $domdefaults{'waf_trusted'},
                   14459:                        vpnint   => $domdefaults{'waf_vpnint'},
                   14460:                        vpnext   => $domdefaults{'waf_vpnext'},
                   14461:                        sslopt   => $domdefaults{'waf_sslopt'},
                   14462:                     };
                   14463:     return $proxyinfo;
                   14464: }
                   14465: 
                   14466: sub ip_match {
                   14467:     my ($ip,$pattern_str) = @_;
                   14468:     $ip=Net::CIDR::cidrvalidate($ip);
                   14469:     if ($ip) {
                   14470:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   14471:     }
                   14472:     return;
                   14473: }
                   14474: 
                   14475: sub get_proxy_alias {
                   14476:     my ($lonid) = @_;
                   14477:     if ($lonid eq '') {
                   14478:         $lonid = $perlvar{'lonHostID'};
                   14479:     }
                   14480:     if (!defined(&hostname($lonid))) {
                   14481:         return;
                   14482:     }
                   14483:     if ($lonid ne '') {
                   14484:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
                   14485:         if ($cached) {
                   14486:             return $alias;
                   14487:         }
                   14488:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14489:         if ($dom ne '') {
                   14490:             my $cachetime = 60*60*24;
                   14491:             my %domconfig =
                   14492:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14493:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14494:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
                   14495:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   14496:                 }
                   14497:             }
                   14498:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   14499:         }
                   14500:     }
                   14501:     return;
                   14502: }
                   14503: 
                   14504: sub use_proxy_alias {
                   14505:     my ($r,$lonid) = @_;
                   14506:     my $alias = &get_proxy_alias($lonid);
                   14507:     if ($alias) {
                   14508:         my $dom = &host_domain($lonid);
                   14509:         if ($dom ne '') {
                   14510:             my $proxyinfo = &get_proxy_settings($dom);
                   14511:             my ($vpnint,$remote_ip);
                   14512:             if (ref($proxyinfo) eq 'HASH') {
                   14513:                 $vpnint = $proxyinfo->{'vpnint'};
                   14514:                 if ($vpnint) {
                   14515:                     $remote_ip = &get_requestor_ip($r,1,1);
                   14516:                 }
                   14517:             }
                   14518:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   14519:                 return $alias;
                   14520:             }
                   14521:         }
                   14522:     }
                   14523:     return;
                   14524: }
                   14525: 
                   14526: sub alias_sso {
                   14527:     my ($lonid) = @_;
                   14528:     if ($lonid eq '') {
                   14529:         $lonid = $perlvar{'lonHostID'};
                   14530:     }
                   14531:     if (!defined(&hostname($lonid))) {
                   14532:         return;
                   14533:     }
                   14534:     if ($lonid ne '') {
                   14535:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
                   14536:         if ($cached) {
                   14537:             return $use_alias;
                   14538:         }
                   14539:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14540:         if ($dom ne '') {
                   14541:             my $cachetime = 60*60*24;
                   14542:             my %domconfig =
                   14543:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14544:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14545:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
                   14546:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
                   14547:                 }
                   14548:             }
                   14549:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
                   14550:         }
                   14551:     }
                   14552:     return;
                   14553: }
                   14554: 
                   14555: sub get_saml_landing {
                   14556:     my ($lonid) = @_;
                   14557:     if ($lonid eq '') {
                   14558:         my $defdom = &default_login_domain();
                   14559:         my @hosts = &current_machine_ids();
                   14560:         if (@hosts > 1) {
                   14561:             foreach my $hostid (@hosts) {
                   14562:                 if (&host_domain($hostid) eq $defdom) {
                   14563:                     $lonid = $hostid;
                   14564:                     last;
                   14565:                 }
                   14566:             }
                   14567:         } else {
                   14568:             $lonid = $perlvar{'lonHostID'};
                   14569:         }
                   14570:         if ($lonid) {
                   14571:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
                   14572:                 return;
                   14573:             }
                   14574:         } else {
                   14575:             return;
                   14576:         }
                   14577:     } elsif (!defined(&hostname($lonid))) {
                   14578:         return;
                   14579:     }
                   14580:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   14581:     if ($cached) {
                   14582:         return $landing;
                   14583:     }
                   14584:     my $dom = &Apache::lonnet::host_domain($lonid);
                   14585:     if ($dom ne '') {
                   14586:         my $cachetime = 60*60*24;
                   14587:         my %domconfig =
                   14588:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
                   14589:         if (ref($domconfig{'login'}) eq 'HASH') {
                   14590:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   14591:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   14592:                     $landing = 1;
                   14593:                 }
                   14594:             }
                   14595:         }
                   14596:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   14597:     }
                   14598:     return;
                   14599: }
                   14600: 
1.31      www      14601: # ------------------------------------------------------------- Declutters URLs
                   14602: 
                   14603: sub declutter {
                   14604:     my $thisfn=shift;
1.569     albertel 14605:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  14606:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   14607:         $thisfn=~s{^/home/httpd/html}{};
                   14608:     }
1.31      www      14609:     $thisfn=~s/^\///;
1.697     albertel 14610:     $thisfn=~s|^adm/wrapper/||;
                   14611:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      14612:     $thisfn=~s/^res\///;
1.1172    bisitz   14613:     $thisfn=~s/^priv\///;
1.1032    raeburn  14614:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   14615:         $thisfn=~s/\?.+$//;
                   14616:     }
1.268     www      14617:     return $thisfn;
                   14618: }
                   14619: 
                   14620: # ------------------------------------------------------------- Clutter up URLs
                   14621: 
                   14622: sub clutter {
                   14623:     my $thisfn='/'.&declutter(shift);
1.887     albertel 14624:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 14625: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      14626:        $thisfn='/res'.$thisfn; 
                   14627:     }
1.1031    raeburn  14628:     if ($thisfn !~m|^/adm|) {
                   14629: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 14630: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 14631: 	} else {
                   14632: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   14633: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 14634: 	    if ($embstyle eq 'ssi'
                   14635: 		|| ($embstyle eq 'hdn')
                   14636: 		|| ($embstyle eq 'rat')
                   14637: 		|| ($embstyle eq 'prv')
                   14638: 		|| ($embstyle eq 'ign')) {
                   14639: 		#do nothing with these
                   14640: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 14641: 		|| ($embstyle eq 'emb')
                   14642: 		|| ($embstyle eq 'wrp')) {
                   14643: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 14644: 	    } elsif ($embstyle eq 'unk'
                   14645: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 14646: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 14647: 	    } else {
1.718     www      14648: #		&logthis("Got a blank emb style");
1.695     albertel 14649: 	    }
1.694     albertel 14650: 	}
1.1172.2.146.  .1(raebu 14651:22):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   14652:22):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 14653:     }
1.31      www      14654:     return $thisfn;
1.12      www      14655: }
                   14656: 
1.787     albertel 14657: sub clutter_with_no_wrapper {
                   14658:     my $uri = &clutter(shift);
                   14659:     if ($uri =~ m-^/adm/-) {
                   14660: 	$uri =~ s-^/adm/wrapper/-/-;
                   14661: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14662:     }
                   14663:     return $uri;
                   14664: }
                   14665: 
1.557     albertel 14666: sub freeze_escape {
                   14667:     my ($value)=@_;
                   14668:     if (ref($value)) {
                   14669: 	$value=&nfreeze($value);
                   14670: 	return '__FROZEN__'.&escape($value);
                   14671:     }
                   14672:     return &escape($value);
                   14673: }
                   14674: 
1.11      www      14675: 
1.557     albertel 14676: sub thaw_unescape {
                   14677:     my ($value)=@_;
                   14678:     if ($value =~ /^__FROZEN__/) {
                   14679: 	substr($value,0,10,undef);
                   14680: 	$value=&unescape($value);
                   14681: 	return &thaw($value);
                   14682:     }
                   14683:     return &unescape($value);
                   14684: }
                   14685: 
1.436     albertel 14686: sub correct_line_ends {
                   14687:     my ($result)=@_;
                   14688:     $$result =~s/\r\n/\n/mg;
                   14689:     $$result =~s/\r/\n/mg;
1.415     albertel 14690: }
1.1       albertel 14691: # ================================================================ Main Program
                   14692: 
1.184     www      14693: sub goodbye {
1.204     albertel 14694:    &logthis("Starting Shut down");
1.443     albertel 14695: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14696:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14697: #converted
1.599     albertel 14698: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14699:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14700: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   14701: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 14702: #1.1 only
1.870     albertel 14703: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   14704: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   14705: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   14706: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   14707:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 14708:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   14709:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      14710:    &flushcourselogs();
                   14711:    &logthis("Shutting down");
                   14712: }
                   14713: 
1.852     albertel 14714: sub get_dns {
1.1172.2.17  raeburn  14715:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 14716:     if (!$ignore_cache) {
                   14717: 	my ($content,$cached)=
                   14718: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   14719: 	if ($cached) {
1.1172.2.17  raeburn  14720: 	    &$func($content,$hashref);
1.869     albertel 14721: 	    return;
                   14722: 	}
                   14723:     }
                   14724: 
                   14725:     my %alldns;
1.1172.2.96  raeburn  14726:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   14727:         foreach my $dns (<$config>) {
                   14728: 	    next if ($dns !~ /^\^(\S*)/x);
                   14729:             my $line = $1;
                   14730:             my ($host,$protocol) = split(/:/,$line);
                   14731:             if ($protocol ne 'https') {
                   14732:                 $protocol = 'http';
                   14733:             }
                   14734: 	    $alldns{$host} = $protocol;
1.979     raeburn  14735:         }
1.1172.2.96  raeburn  14736:         close($config);
1.869     albertel 14737:     }
                   14738:     while (%alldns) {
1.1172.2.52  raeburn  14739: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142  raeburn  14740:         my @content;
                   14741:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   14742:             my $command = (split('/',$url))[3];
                   14743:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   14744:             delete($alldns{$dns});
                   14745:             next if (($dir eq '') || ($file eq ''));
                   14746:             if (open(my $config,'<',"$dir/$file")) {
                   14747:                 @content = <$config>;
                   14748:                 close($config);
                   14749:             }
                   14750:         } else {
                   14751: 	    my $ua=new LWP::UserAgent;
                   14752:             $ua->timeout(30);
                   14753: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   14754: 	    my $response=$ua->request($request);
                   14755:             delete($alldns{$dns});
                   14756: 	    next if ($response->is_error());
                   14757: 	    @content = split("\n",$response->content);
                   14758:         }
1.1172.2.17  raeburn  14759:         unless ($nocache) {
1.1172.2.23  raeburn  14760: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  14761:         }
                   14762: 	&$func(\@content,$hashref);
1.869     albertel 14763: 	return;
1.852     albertel 14764:     }
1.871     albertel 14765:     my $which = (split('/',$url))[3];
                   14766:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  14767:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   14768:         my @content = <$config>;
                   14769:         &$func(\@content,$hashref);
                   14770:     }
1.1172.2.17  raeburn  14771:     return;
                   14772: }
                   14773: 
                   14774: # ------------------------------------------------------Get DNS checksums file
                   14775: sub parse_dns_checksums_tab {
                   14776:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  14777:     my $lonhost = $perlvar{'lonHostID'};
                   14778:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  14779:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  14780:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14781:     my $webconfdir = '/etc/httpd/conf';
                   14782:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14783:         $webconfdir = '/etc/apache2';
                   14784:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14785:         if ($1 >= 10) {
                   14786:             $webconfdir = '/etc/apache2';
                   14787:         }
                   14788:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14789:         if ($1 >= 10.0) {
                   14790:             $webconfdir = '/etc/apache2';
                   14791:         }
                   14792:     }
1.1172.2.17  raeburn  14793:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14794:     my (%chksum,%revnum);
                   14795:     if (ref($lines) eq 'ARRAY') {
                   14796:         chomp(@{$lines});
1.1172.2.34  raeburn  14797:         my $version = shift(@{$lines});
                   14798:         if ($version eq $release) {
1.1172.2.17  raeburn  14799:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  14800:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  14801:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14802:                     if ($webconfdir eq '/etc/apache2') {
                   14803:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14804:                     }
                   14805:                 }
1.1172.2.34  raeburn  14806:                 $chksum{$file} = $shasum;
                   14807:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  14808:             }
                   14809:             if (ref($hashref) eq 'HASH') {
                   14810:                 %{$hashref} = (
                   14811:                                 sums     => \%chksum,
                   14812:                                 versions => \%revnum,
                   14813:                               );
                   14814:             }
                   14815:         }
                   14816:     }
1.869     albertel 14817:     return;
1.852     albertel 14818: }
1.1172.2.17  raeburn  14819: 
                   14820: sub fetch_dns_checksums {
                   14821:     my %checksums;
1.1172.2.34  raeburn  14822:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  14823:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  14824:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14825:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  14826:              \%checksums);
                   14827:     return \%checksums;
                   14828: }
                   14829: 
1.1172.2.142  raeburn  14830: sub parse_getdns_url {
                   14831:     my ($command,$url) = @_;
                   14832:     my $dir = $perlvar{'lonTabDir'};
                   14833:     my $file;
                   14834:     if ($command eq 'hosts') {
                   14835:         $file = 'dns_hosts.tab';
                   14836:     } elsif ($command eq 'domain') {
                   14837:         $file = 'dns_domain.tab';
                   14838:     } elsif ($command eq 'checksums') {
                   14839:         my $version = (split('/',$url))[4];
                   14840:         $file = "dns_checksums/$version.tab",
                   14841:     }
                   14842:     return ($dir,$file);
                   14843: }
                   14844: 
1.327     albertel 14845: # ------------------------------------------------------------ Read domain file
                   14846: {
1.852     albertel 14847:     my $loaded;
1.846     albertel 14848:     my %domain;
                   14849: 
1.852     albertel 14850:     sub parse_domain_tab {
                   14851: 	my ($lines) = @_;
                   14852: 	foreach my $line (@$lines) {
                   14853: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      14854: 
1.846     albertel 14855: 	    chomp($line);
1.852     albertel 14856: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 14857: 	    my %this_domain;
                   14858: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   14859: 			       'lang_def', 'city', 'longi', 'lati',
                   14860: 			       'primary') {
                   14861: 		$this_domain{$field} = shift(@elements);
                   14862: 	    }
                   14863: 	    $domain{$name} = \%this_domain;
1.852     albertel 14864: 	}
                   14865:     }
1.864     albertel 14866: 
                   14867:     sub reset_domain_info {
                   14868: 	undef($loaded);
                   14869: 	undef(%domain);
                   14870:     }
                   14871: 
1.852     albertel 14872:     sub load_domain_tab {
1.1172.2.70  raeburn  14873: 	my ($ignore_cache,$nocache) = @_;
                   14874: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 14875: 	my $fh;
1.1172.2.96  raeburn  14876: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 14877: 	    my @lines = <$fh>;
                   14878: 	    &parse_domain_tab(\@lines);
1.448     albertel 14879: 	}
1.852     albertel 14880: 	close($fh);
                   14881: 	$loaded = 1;
1.327     albertel 14882:     }
1.846     albertel 14883: 
                   14884:     sub domain {
1.852     albertel 14885: 	&load_domain_tab() if (!$loaded);
                   14886: 
1.846     albertel 14887: 	my ($name,$what) = @_;
                   14888: 	return if ( !exists($domain{$name}) );
                   14889: 
                   14890: 	if (!$what) {
                   14891: 	    return $domain{$name}{'description'};
                   14892: 	}
                   14893: 	return $domain{$name}{$what};
                   14894:     }
1.974     raeburn  14895: 
                   14896:     sub domain_info {
                   14897:         &load_domain_tab() if (!$loaded);
                   14898:         return %domain;
                   14899:     }
                   14900: 
1.327     albertel 14901: }
                   14902: 
                   14903: 
1.1       albertel 14904: # ------------------------------------------------------------- Read hosts file
                   14905: {
1.838     albertel 14906:     my %hostname;
1.844     albertel 14907:     my %hostdom;
1.845     albertel 14908:     my %libserv;
1.852     albertel 14909:     my $loaded;
1.888     albertel 14910:     my %name_to_host;
1.1074    raeburn  14911:     my %internetdom;
1.1107    raeburn  14912:     my %LC_dns_serv;
1.852     albertel 14913: 
                   14914:     sub parse_hosts_tab {
                   14915: 	my ($file) = @_;
                   14916: 	foreach my $configline (@$file) {
                   14917: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  14918:             chomp($configline);
                   14919: 	    if ($configline =~ /^\^/) {
                   14920:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   14921:                     $LC_dns_serv{$1} = 1;
                   14922:                 }
                   14923:                 next;
                   14924:             }
1.1074    raeburn  14925: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 14926: 	    $name=~s/\s//g;
                   14927: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  14928:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   14929:                     my $curr = $hostname{$id};
                   14930:                     my $skip;
                   14931:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   14932:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   14933:                             $skip = 1;
                   14934:                         } else {
                   14935:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   14936:                         }
                   14937:                     }
                   14938:                     unless ($skip) {
                   14939:                         push(@{$name_to_host{$name}},$id);
                   14940:                     }
                   14941:                 } else {
                   14942:                     push(@{$name_to_host{$name}},$id);
                   14943:                 }
1.852     albertel 14944: 		$hostname{$id}=$name;
                   14945: 		$hostdom{$id}=$domain;
                   14946: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  14947:                 if (defined($protocol)) {
                   14948:                     if ($protocol eq 'https') {
                   14949:                         $protocol{$id} = $protocol;
                   14950:                     } else {
                   14951:                         $protocol{$id} = 'http'; 
                   14952:                     }
1.968     raeburn  14953:                 } else {
1.969     raeburn  14954:                     $protocol{$id} = 'http';
1.968     raeburn  14955:                 }
1.1074    raeburn  14956:                 if (defined($intdom)) {
                   14957:                     $internetdom{$id} = $intdom;
                   14958:                 }
1.852     albertel 14959: 	    }
                   14960: 	}
                   14961:     }
1.864     albertel 14962:     
                   14963:     sub reset_hosts_info {
1.897     albertel 14964: 	&purge_remembered();
1.864     albertel 14965: 	&reset_domain_info();
                   14966: 	&reset_hosts_ip_info();
1.892     albertel 14967: 	undef(%name_to_host);
1.864     albertel 14968: 	undef(%hostname);
                   14969: 	undef(%hostdom);
                   14970: 	undef(%libserv);
                   14971: 	undef($loaded);
                   14972:     }
1.1       albertel 14973: 
1.852     albertel 14974:     sub load_hosts_tab {
1.1172.2.70  raeburn  14975: 	my ($ignore_cache,$nocache) = @_;
                   14976: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  14977: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 14978: 	my @config = <$config>;
                   14979: 	&parse_hosts_tab(\@config);
                   14980: 	close($config);
                   14981: 	$loaded=1;
1.1       albertel 14982:     }
1.852     albertel 14983: 
1.838     albertel 14984:     sub hostname {
1.852     albertel 14985: 	&load_hosts_tab() if (!$loaded);
                   14986: 
1.838     albertel 14987: 	my ($lonid) = @_;
                   14988: 	return $hostname{$lonid};
                   14989:     }
1.845     albertel 14990: 
1.838     albertel 14991:     sub all_hostnames {
1.852     albertel 14992: 	&load_hosts_tab() if (!$loaded);
                   14993: 
1.838     albertel 14994: 	return %hostname;
                   14995:     }
1.845     albertel 14996: 
1.888     albertel 14997:     sub all_names {
1.1172.2.70  raeburn  14998:         my ($ignore_cache,$nocache) = @_;
                   14999: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 15000: 
                   15001: 	return %name_to_host;
                   15002:     }
                   15003: 
1.974     raeburn  15004:     sub all_host_domain {
                   15005:         &load_hosts_tab() if (!$loaded);
                   15006:         return %hostdom;
                   15007:     }
                   15008: 
1.845     albertel 15009:     sub is_library {
1.852     albertel 15010: 	&load_hosts_tab() if (!$loaded);
                   15011: 
1.845     albertel 15012: 	return exists($libserv{$_[0]});
                   15013:     }
                   15014: 
                   15015:     sub all_library {
1.852     albertel 15016: 	&load_hosts_tab() if (!$loaded);
                   15017: 
1.845     albertel 15018: 	return %libserv;
                   15019:     }
                   15020: 
1.1062    droeschl 15021:     sub unique_library {
                   15022: 	#2x reverse removes all hostnames that appear more than once
                   15023:         my %unique = reverse &all_library();
                   15024:         return reverse %unique;
                   15025:     }
                   15026: 
1.841     albertel 15027:     sub get_servers {
1.852     albertel 15028: 	&load_hosts_tab() if (!$loaded);
                   15029: 
1.841     albertel 15030: 	my ($domain,$type) = @_;
                   15031: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   15032: 	                                          : %hostname;
                   15033: 	my %result;
1.842     albertel 15034: 	if (ref($domain) eq 'ARRAY') {
                   15035: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 15036: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 15037: 		    $result{$host} = $hostname;
                   15038: 		}
                   15039: 	    }
                   15040: 	} else {
                   15041: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   15042: 		if ($hostdom{$host} eq $domain) {
                   15043: 		    $result{$host} = $hostname;
                   15044: 		}
1.841     albertel 15045: 	    }
                   15046: 	}
                   15047: 	return %result;
                   15048:     }
1.845     albertel 15049: 
1.1062    droeschl 15050:     sub get_unique_servers {
                   15051:         my %unique = reverse &get_servers(@_);
                   15052: 	return reverse %unique;
                   15053:     }
                   15054: 
1.844     albertel 15055:     sub host_domain {
1.852     albertel 15056: 	&load_hosts_tab() if (!$loaded);
                   15057: 
1.844     albertel 15058: 	my ($lonid) = @_;
                   15059: 	return $hostdom{$lonid};
                   15060:     }
                   15061: 
1.841     albertel 15062:     sub all_domains {
1.852     albertel 15063: 	&load_hosts_tab() if (!$loaded);
                   15064: 
1.841     albertel 15065: 	my %seen;
                   15066: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   15067: 	return @uniq;
                   15068:     }
1.1074    raeburn  15069: 
                   15070:     sub internet_dom {
                   15071:         &load_hosts_tab() if (!$loaded);
                   15072: 
                   15073:         my ($lonid) = @_;
                   15074:         return $internetdom{$lonid};
                   15075:     }
1.1107    raeburn  15076: 
                   15077:     sub is_LC_dns {
                   15078:         &load_hosts_tab() if (!$loaded);
                   15079: 
                   15080:         my ($hostname) = @_;
                   15081:         return exists($LC_dns_serv{$hostname});
                   15082:     }
                   15083: 
1.1       albertel 15084: }
                   15085: 
1.847     albertel 15086: { 
                   15087:     my %iphost;
1.856     albertel 15088:     my %name_to_ip;
                   15089:     my %lonid_to_ip;
1.869     albertel 15090: 
1.847     albertel 15091:     sub get_hosts_from_ip {
                   15092: 	my ($ip) = @_;
                   15093: 	my %iphosts = &get_iphost();
                   15094: 	if (ref($iphosts{$ip})) {
                   15095: 	    return @{$iphosts{$ip}};
                   15096: 	}
                   15097: 	return;
1.839     albertel 15098:     }
1.864     albertel 15099:     
                   15100:     sub reset_hosts_ip_info {
                   15101: 	undef(%iphost);
                   15102: 	undef(%name_to_ip);
                   15103: 	undef(%lonid_to_ip);
                   15104:     }
1.856     albertel 15105: 
                   15106:     sub get_host_ip {
                   15107: 	my ($lonid) = @_;
                   15108: 	if (exists($lonid_to_ip{$lonid})) {
                   15109: 	    return $lonid_to_ip{$lonid};
                   15110: 	}
                   15111: 	my $name=&hostname($lonid);
                   15112:    	my $ip = gethostbyname($name);
                   15113: 	return if (!$ip || length($ip) ne 4);
                   15114: 	$ip=inet_ntoa($ip);
                   15115: 	$name_to_ip{$name}   = $ip;
                   15116: 	$lonid_to_ip{$lonid} = $ip;
                   15117: 	return $ip;
                   15118:     }
1.847     albertel 15119:     
                   15120:     sub get_iphost {
1.1172.2.70  raeburn  15121: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 15122: 
1.869     albertel 15123: 	if (!$ignore_cache) {
                   15124: 	    if (%iphost) {
                   15125: 		return %iphost;
                   15126: 	    }
                   15127: 	    my ($ip_info,$cached)=
                   15128: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   15129: 	    if ($cached) {
                   15130: 		%iphost      = %{$ip_info->[0]};
                   15131: 		%name_to_ip  = %{$ip_info->[1]};
                   15132: 		%lonid_to_ip = %{$ip_info->[2]};
                   15133: 		return %iphost;
                   15134: 	    }
                   15135: 	}
1.894     albertel 15136: 
                   15137: 	# get yesterday's info for fallback
                   15138: 	my %old_name_to_ip;
                   15139: 	my ($ip_info,$cached)=
                   15140: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   15141: 	if ($cached) {
                   15142: 	    %old_name_to_ip = %{$ip_info->[1]};
                   15143: 	}
                   15144: 
1.1172.2.70  raeburn  15145: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 15146: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 15147: 	    my $ip;
                   15148: 	    if (!exists($name_to_ip{$name})) {
                   15149: 		$ip = gethostbyname($name);
                   15150: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 15151: 		    if (defined($old_name_to_ip{$name})) {
                   15152: 			$ip = $old_name_to_ip{$name};
                   15153: 			&logthis("Can't find $name defaulting to old $ip");
                   15154: 		    } else {
                   15155: 			&logthis("Name $name no IP found");
                   15156: 			next;
                   15157: 		    }
                   15158: 		} else {
                   15159: 		    $ip=inet_ntoa($ip);
1.847     albertel 15160: 		}
                   15161: 		$name_to_ip{$name} = $ip;
                   15162: 	    } else {
                   15163: 		$ip = $name_to_ip{$name};
1.653     albertel 15164: 	    }
1.888     albertel 15165: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   15166: 		$lonid_to_ip{$id} = $ip;
                   15167: 	    }
                   15168: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 15169: 	}
1.1172.2.70  raeburn  15170:         unless ($nocache) {
                   15171: 	    &do_cache_new('iphost','iphost',
                   15172: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   15173: 		          48*60*60);
                   15174:         }
1.869     albertel 15175: 
1.847     albertel 15176: 	return %iphost;
1.598     albertel 15177:     }
                   15178: 
1.992     raeburn  15179:     #
                   15180:     #  Given a DNS returns the loncapa host name for that DNS 
                   15181:     # 
                   15182:     sub host_from_dns {
                   15183:         my ($dns) = @_;
                   15184:         my @hosts;
                   15185:         my $ip;
                   15186: 
1.993     raeburn  15187:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  15188:             $ip = $name_to_ip{$dns};
                   15189:         }
                   15190:         if (!$ip) {
                   15191:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   15192:             if (length($ip) == 4) { 
                   15193: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   15194:             }
                   15195:         }
                   15196:         if ($ip) {
                   15197: 	    @hosts = get_hosts_from_ip($ip);
                   15198: 	    return $hosts[0];
                   15199:         }
                   15200:         return undef;
1.986     foxr     15201:     }
1.992     raeburn  15202: 
1.1074    raeburn  15203:     sub get_internet_names {
                   15204:         my ($lonid) = @_;
                   15205:         return if ($lonid eq '');
                   15206:         my ($idnref,$cached)=
                   15207:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   15208:         if ($cached) {
                   15209:             return $idnref;
                   15210:         }
                   15211:         my $ip = &get_host_ip($lonid);
                   15212:         my @hosts = &get_hosts_from_ip($ip);
                   15213:         my %iphost = &get_iphost();
                   15214:         my (@idns,%seen);
                   15215:         foreach my $id (@hosts) {
                   15216:             my $dom = &host_domain($id);
                   15217:             my $prim_id = &domain($dom,'primary');
                   15218:             my $prim_ip = &get_host_ip($prim_id);
                   15219:             next if ($seen{$prim_ip});
                   15220:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   15221:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   15222:                     my $intdom = &internet_dom($id);
                   15223:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   15224:                         push(@idns,$intdom);
                   15225:                     }
                   15226:                 }
                   15227:             }
                   15228:             $seen{$prim_ip} = 1;
                   15229:         }
1.1172.2.23  raeburn  15230:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  15231:     }
                   15232: 
1.986     foxr     15233: }
                   15234: 
1.1079    raeburn  15235: sub all_loncaparevs {
1.1172.2.39  raeburn  15236:     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  15237: }
                   15238: 
1.1172.2.27  raeburn  15239: # ------------------------------------------------------- Read loncaparev table
                   15240: {
                   15241:     sub load_loncaparevs {
                   15242:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  15243:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  15244:                 while (my $configline=<$config>) {
                   15245:                     chomp($configline);
                   15246:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   15247:                     $loncaparevs{$hostid}=$loncaparev;
                   15248:                 }
                   15249:                 close($config);
                   15250:             }
                   15251:         }
                   15252:     }
                   15253: }
                   15254: 
                   15255: # ----------------------------------------------------- Read serverhostID table
                   15256: {
                   15257:     sub load_serverhomeIDs {
                   15258:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  15259:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  15260:                 while (my $configline=<$config>) {
                   15261:                     chomp($configline);
                   15262:                     my ($name,$id)=split(/:/,$configline);
                   15263:                     $serverhomeIDs{$name}=$id;
                   15264:                 }
                   15265:                 close($config);
                   15266:             }
                   15267:         }
                   15268:     }
                   15269: }
                   15270: 
                   15271: 
1.862     albertel 15272: BEGIN {
                   15273: 
                   15274: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   15275:     unless ($readit) {
                   15276: {
                   15277:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   15278:     %perlvar = (%perlvar,%{$configvars});
                   15279: }
                   15280: 
                   15281: 
1.1       albertel 15282: # ------------------------------------------------------ Read spare server file
                   15283: {
1.1172.2.96  raeburn  15284:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 15285: 
                   15286:     while (my $configline=<$config>) {
                   15287:        chomp($configline);
1.284     matthew  15288:        if ($configline) {
1.784     albertel 15289: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 15290: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 15291: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 15292:        }
                   15293:     }
1.448     albertel 15294:     close($config);
1.1       albertel 15295: }
1.11      www      15296: # ------------------------------------------------------------ Read permissions
                   15297: {
1.1172.2.96  raeburn  15298:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      15299: 
                   15300:     while (my $configline=<$config>) {
1.448     albertel 15301: 	chomp($configline);
                   15302: 	if ($configline) {
                   15303: 	    my ($role,$perm)=split(/ /,$configline);
                   15304: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   15305: 	}
1.11      www      15306:     }
1.448     albertel 15307:     close($config);
1.11      www      15308: }
                   15309: 
                   15310: # -------------------------------------------- Read plain texts for permissions
                   15311: {
1.1172.2.96  raeburn  15312:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      15313: 
                   15314:     while (my $configline=<$config>) {
1.448     albertel 15315: 	chomp($configline);
                   15316: 	if ($configline) {
1.742     raeburn  15317: 	    my ($short,@plain)=split(/:/,$configline);
                   15318:             %{$prp{$short}} = ();
                   15319: 	    if (@plain > 0) {
                   15320:                 $prp{$short}{'std'} = $plain[0];
                   15321:                 for (my $i=1; $i<@plain; $i++) {
                   15322:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   15323:                 }
                   15324:             }
1.448     albertel 15325: 	}
1.135     www      15326:     }
1.448     albertel 15327:     close($config);
1.135     www      15328: }
                   15329: 
                   15330: # ---------------------------------------------------------- Read package table
                   15331: {
1.1172.2.96  raeburn  15332:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      15333: 
                   15334:     while (my $configline=<$config>) {
1.483     albertel 15335: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 15336: 	chomp($configline);
                   15337: 	my ($short,$plain)=split(/:/,$configline);
                   15338: 	my ($pack,$name)=split(/\&/,$short);
                   15339: 	if ($plain ne '') {
                   15340: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   15341: 	    $packagetab{$short}=$plain; 
                   15342: 	}
1.11      www      15343:     }
1.448     albertel 15344:     close($config);
1.329     matthew  15345: }
                   15346: 
1.1172.2.27  raeburn  15347: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  15348: 
1.1172.2.27  raeburn  15349: &load_loncaparevs();
                   15350: 
                   15351: # ------------------------------------------------------- Read serverhostID table
                   15352: 
                   15353: &load_serverhomeIDs();
1.1074    raeburn  15354: 
1.1172.2.27  raeburn  15355: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  15356: {
                   15357:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   15358:     if (-e $file) {
                   15359:         my $parser = HTML::LCParser->new($file);
                   15360:         while (my $token = $parser->get_token()) {
                   15361:             if ($token->[0] eq 'S') {
                   15362:                 my $item = $token->[1];
                   15363:                 my $name = $token->[2]{'name'};
                   15364:                 my $value = $token->[2]{'value'};
                   15365:                 if ($item ne '' && $name ne '' && $value ne '') {
                   15366:                     my $release = $parser->get_text();
                   15367:                     $release =~ s/(^\s*|\s*$ )//gx;
                   15368:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   15369:                 }
                   15370:             }
                   15371:         }
                   15372:     }
1.1073    raeburn  15373: }
                   15374: 
1.1138    raeburn  15375: # ---------------------------------------------------------- Read managers table
                   15376: {
                   15377:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  15378:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  15379:             while (my $configline=<$config>) {
                   15380:                 chomp($configline);
                   15381:                 next if ($configline =~ /^\#/);
                   15382:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   15383:                     $managerstab{$configline} = 1;
                   15384:                 }
                   15385:             }
                   15386:             close($config);
                   15387:         }
                   15388:     }
                   15389: }
                   15390: 
1.329     matthew  15391: # ------------- set up temporary directory
                   15392: {
1.1117    foxr     15393:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  15394: 
1.11      www      15395: }
                   15396: 
1.1172.2.104  raeburn  15397: # ------------- set default texengine (domain default overrides this)
                   15398: {
                   15399:     $deftex = LONCAPA::texengine();
                   15400: }
                   15401: 
1.1172.2.114  raeburn  15402: # ------------- set default minimum length for passwords for internal auth users
                   15403: {
                   15404:     $passwdmin = LONCAPA::passwd_min();
                   15405: }
                   15406: 
1.794     albertel 15407: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   15408: 				'compress_threshold'=> 20_000,
                   15409:  			        });
1.185     www      15410: 
1.281     www      15411: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      15412: $dumpcount=0;
1.958     www      15413: $locknum=0;
1.22      www      15414: 
1.163     harris41 15415: &logtouch();
1.672     albertel 15416: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      15417: $readit=1;
1.564     albertel 15418:     {
                   15419: 	use integer;
                   15420: 	my $test=(2**32)+1;
1.568     albertel 15421: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 15422: 	&logthis(" Detected 64bit platform ($_64bit)");
                   15423:     }
1.195     www      15424: }
1.1       albertel 15425: }
1.179     www      15426: 
1.1       albertel 15427: 1;
1.191     harris41 15428: __END__
                   15429: 
1.243     albertel 15430: =pod
                   15431: 
1.191     harris41 15432: =head1 NAME
                   15433: 
1.243     albertel 15434: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 15435: 
                   15436: =head1 SYNOPSIS
                   15437: 
1.243     albertel 15438: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 15439: 
                   15440:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   15441: 
1.243     albertel 15442: Common parameters:
                   15443: 
                   15444: =over 4
                   15445: 
                   15446: =item *
                   15447: 
                   15448: $uname : an internal username (if $cname expecting a course Id specifically)
                   15449: 
                   15450: =item *
                   15451: 
                   15452: $udom : a domain (if $cdom expecting a course's domain specifically)
                   15453: 
                   15454: =item *
                   15455: 
                   15456: $symb : a resource instance identifier
                   15457: 
                   15458: =item *
                   15459: 
                   15460: $namespace : the name of a .db file that contains the data needed or
                   15461: being set.
                   15462: 
                   15463: =back
                   15464: 
1.394     bowersj2 15465: =head1 OVERVIEW
1.191     harris41 15466: 
1.394     bowersj2 15467: lonnet provides subroutines which interact with the
                   15468: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   15469: about classes, users, and resources.
1.243     albertel 15470: 
                   15471: For many of these objects you can also use this to store data about
                   15472: them or modify them in various ways.
1.191     harris41 15473: 
1.394     bowersj2 15474: =head2 Symbs
1.191     harris41 15475: 
1.394     bowersj2 15476: To identify a specific instance of a resource, LON-CAPA uses symbols
                   15477: or "symbs"X<symb>. These identifiers are built from the URL of the
                   15478: map, the resource number of the resource in the map, and the URL of
                   15479: the resource itself. The latter is somewhat redundant, but might help
                   15480: if maps change.
                   15481: 
                   15482: An example is
                   15483: 
                   15484:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   15485: 
                   15486: The respective map entry is
                   15487: 
                   15488:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   15489:   title="Problem 2">
                   15490:  </resource>
                   15491: 
                   15492: Symbs are used by the random number generator, as well as to store and
                   15493: restore data specific to a certain instance of for example a problem.
                   15494: 
                   15495: =head2 Storing And Retrieving Data
                   15496: 
                   15497: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   15498: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   15499: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   15500: is is the non-critical message twin of cstore. These functions are for
                   15501: handlers to store a perl hash to a user's permanent data space in an
                   15502: easy manner, and to retrieve it again on another call. It is expected
                   15503: that a handler would use this once at the beginning to retrieve data,
                   15504: and then again once at the end to send only the new data back.
                   15505: 
                   15506: The data is stored in the user's data directory on the user's
                   15507: homeserver under the ID of the course.
                   15508: 
                   15509: The hash that is returned by restore will have all of the previous
                   15510: value for all of the elements of the hash.
                   15511: 
                   15512: Example:
                   15513: 
                   15514:  #creating a hash
                   15515:  my %hash;
                   15516:  $hash{'foo'}='bar';
                   15517: 
                   15518:  #storing it
                   15519:  &Apache::lonnet::cstore(\%hash);
                   15520: 
                   15521:  #changing a value
                   15522:  $hash{'foo'}='notbar';
                   15523: 
                   15524:  #adding a new value
                   15525:  $hash{'bar'}='foo';
                   15526:  &Apache::lonnet::cstore(\%hash);
                   15527: 
                   15528:  #retrieving the hash
                   15529:  my %history=&Apache::lonnet::restore();
                   15530: 
                   15531:  #print the hash
                   15532:  foreach my $key (sort(keys(%history))) {
                   15533:    print("\%history{$key} = $history{$key}");
                   15534:  }
                   15535: 
                   15536: Will print out:
1.191     harris41 15537: 
1.394     bowersj2 15538:  %history{1:foo} = bar
                   15539:  %history{1:keys} = foo:timestamp
                   15540:  %history{1:timestamp} = 990455579
                   15541:  %history{2:bar} = foo
                   15542:  %history{2:foo} = notbar
                   15543:  %history{2:keys} = foo:bar:timestamp
                   15544:  %history{2:timestamp} = 990455580
                   15545:  %history{bar} = foo
                   15546:  %history{foo} = notbar
                   15547:  %history{timestamp} = 990455580
                   15548:  %history{version} = 2
                   15549: 
                   15550: Note that the special hash entries C<keys>, C<version> and
                   15551: C<timestamp> were added to the hash. C<version> will be equal to the
                   15552: total number of versions of the data that have been stored. The
                   15553: C<timestamp> attribute will be the UNIX time the hash was
                   15554: stored. C<keys> is available in every historical section to list which
                   15555: keys were added or changed at a specific historical revision of a
                   15556: hash.
                   15557: 
                   15558: B<Warning>: do not store the hash that restore returns directly. This
                   15559: will cause a mess since it will restore the historical keys as if the
                   15560: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 15561: 
1.394     bowersj2 15562: Calling convention:
1.191     harris41 15563: 
1.1172.2.27  raeburn  15564:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  15565:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 15566: 
1.394     bowersj2 15567: For more detailed information, see lonnet specific documentation.
1.191     harris41 15568: 
1.394     bowersj2 15569: =head1 RETURN MESSAGES
1.191     harris41 15570: 
1.394     bowersj2 15571: =over 4
1.191     harris41 15572: 
1.394     bowersj2 15573: =item * B<con_lost>: unable to contact remote host
1.191     harris41 15574: 
1.394     bowersj2 15575: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   15576: when the connection is brought back up
1.191     harris41 15577: 
1.394     bowersj2 15578: =item * B<con_failed>: unable to contact remote host and unable to save message
                   15579: for later delivery
1.191     harris41 15580: 
1.967     bisitz   15581: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 15582: 
1.394     bowersj2 15583: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 15584: that was requested
1.191     harris41 15585: 
1.243     albertel 15586: =back
1.191     harris41 15587: 
1.243     albertel 15588: =head1 PUBLIC SUBROUTINES
1.191     harris41 15589: 
1.243     albertel 15590: =head2 Session Environment Functions
1.191     harris41 15591: 
1.243     albertel 15592: =over 4
1.191     harris41 15593: 
1.394     bowersj2 15594: =item * 
                   15595: X<appenv()>
1.949     raeburn  15596: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 15597: the user envirnoment file, and will be restored for each access this
1.620     albertel 15598: user makes during this session, also modifies the %env for the current
1.949     raeburn  15599: process. Optional rolesarrayref - if defined contains a reference to an array
                   15600: of roles which are exempt from the restriction on modifying user.role entries 
                   15601: in the user's environment.db and in %env.    
1.191     harris41 15602: 
                   15603: =item *
1.394     bowersj2 15604: X<delenv()>
1.987     raeburn  15605: B<delenv($delthis,$regexp)>: removes all items from the session
                   15606: environment file that begin with $delthis. If the 
                   15607: optional second arg - $regexp - is true, $delthis is treated as a 
                   15608: regular expression, otherwise \Q$delthis\E is used. 
                   15609: The values are also deleted from the current processes %env.
1.191     harris41 15610: 
1.795     albertel 15611: =item * get_env_multiple($name) 
                   15612: 
                   15613: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   15614: values may be defined and end up as an array ref.
                   15615: 
                   15616: returns an array of values
                   15617: 
1.243     albertel 15618: =back
                   15619: 
                   15620: =head2 User Information
1.191     harris41 15621: 
1.243     albertel 15622: =over 4
1.191     harris41 15623: 
                   15624: =item *
1.394     bowersj2 15625: X<queryauthenticate()>
                   15626: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 15627: authentication scheme
                   15628: 
                   15629: =item *
1.394     bowersj2 15630: X<authenticate()>
1.1073    raeburn  15631: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 15632: authenticate user from domain's lib servers (first use the current
                   15633: one). C<$upass> should be the users password.
1.1073    raeburn  15634: $checkdefauth is optional (value is 1 if a check should be made to
                   15635:    authenticate user using default authentication method, and allow
                   15636:    account creation if username does not have account in the domain).
                   15637: $clientcancheckhost is optional (value is 1 if checking whether the
                   15638:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 15639: 
                   15640: =item *
1.394     bowersj2 15641: X<homeserver()>
                   15642: B<homeserver($uname,$udom)>: find the server which has
                   15643: the user's directory and files (there must be only one), this caches
                   15644: the answer, and also caches if there is a borken connection.
1.191     harris41 15645: 
                   15646: =item *
1.394     bowersj2 15647: X<idget()>
                   15648: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   15649: (IDs are a unique resource in a domain, there must be only 1 ID per
                   15650: username, and only 1 username per ID in a specific domain) (returns
                   15651: hash: id=>name,id=>name)
1.191     harris41 15652: 
                   15653: =item *
1.394     bowersj2 15654: X<idrget()>
                   15655: B<idrget($udom,@unames)>: find the IDs behind a list of
                   15656: usernames (returns hash: name=>id,name=>id)
1.191     harris41 15657: 
                   15658: =item *
1.394     bowersj2 15659: X<idput()>
                   15660: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 15661: 
                   15662: =item *
1.394     bowersj2 15663: X<rolesinit()>
1.1169    droeschl 15664: B<rolesinit($udom,$username)>: get user privileges.
                   15665: returns user role, first access and timer interval hashes
1.243     albertel 15666: 
                   15667: =item *
1.1171    droeschl 15668: X<privileged()>
                   15669: B<privileged($username,$domain)>: returns a true if user has a
                   15670: privileged and active role (i.e. su or dc), false otherwise.
                   15671: 
                   15672: =item *
1.551     albertel 15673: X<getsection()>
                   15674: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 15675: course $cname, return section name/number or '' for "not in course"
                   15676: and '-1' for "no section"
                   15677: 
                   15678: =item *
1.394     bowersj2 15679: X<userenvironment()>
                   15680: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 15681: passed in @what from the requested user's environment, returns a hash
                   15682: 
1.858     raeburn  15683: =item * 
                   15684: X<userlog_query()>
1.859     albertel 15685: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   15686: activity.log file. %filters defines filters applied when parsing the
                   15687: log file. These can be start or end timestamps, or the type of action
                   15688: - log to look for Login or Logout events, check for Checkin or
                   15689: Checkout, role for role selection. The response is in the form
                   15690: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   15691: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  15692: 
1.243     albertel 15693: =back
                   15694: 
                   15695: =head2 User Roles
                   15696: 
                   15697: =over 4
                   15698: 
                   15699: =item *
                   15700: 
1.1172.2.65  raeburn  15701: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   15702: returns codes for allowed actions.
                   15703: 
                   15704: The first argument is required, all others are optional.
                   15705: 
                   15706: $priv is the privilege being checked.
                   15707: $uri contains additional information about what is being checked for access (e.g.,
                   15708: URL, course ID etc.).
                   15709: $symb is the unique resource instance identifier in a course; if needed,
                   15710: but not provided, it will be retrieved via a call to &symbread().
                   15711: $role is the role for which a priv is being checked (only used if priv is evb).
                   15712: $clientip is the user's IP address (only used when checking for access to portfolio
                   15713: files).
                   15714: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   15715: prevents recursive calls to &allowed.
                   15716: 
1.243     albertel 15717:  F: full access
                   15718:  U,I,K: authentication modes (cxx only)
                   15719:  '': forbidden
                   15720:  1: user needs to choose course
                   15721:  2: browse allowed
1.766     albertel 15722:  A: passphrase authentication needed
1.1172.2.65  raeburn  15723:  B: access temporarily blocked because of a blocking event in a course.
1.1172.2.146.  .1(raebu 15724:22):  D: access blocked because access is required via session initiated via deep-link
1.243     albertel 15725: 
                   15726: =item *
                   15727: 
1.1172.2.13  raeburn  15728: constructaccess($url,$setpriv) : check for access to construction space URL
                   15729: 
                   15730: See if the owner domain and name in the URL match those in the
                   15731: expected environment.  If so, return three element list
                   15732: ($ownername,$ownerdomain,$ownerhome).
                   15733: 
                   15734: Otherwise return the null string.
                   15735: 
                   15736: If second argument 'setpriv' is true, it assigns the privileges,
                   15737: and returns the same three element list, unless the owner has
                   15738: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   15739: in which case the null string is returned.
                   15740: 
                   15741: =item *
                   15742: 
1.1172.2.84  raeburn  15743: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   15744: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   15745: for system, domain, and course level. $uname and $udom are optional (current
                   15746: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 15747: 
                   15748: =item *
                   15749: 
1.988     raeburn  15750: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   15751: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  15752: $type is Course (default) or Community.
1.988     raeburn  15753: If $forcedefault evaluates to true, text returned will be default 
                   15754: text for $type. Otherwise, if this is a course, the text returned 
                   15755: will be a custom name for the role (if defined in the course's 
                   15756: environment).  If no custom name is defined the default is returned.
                   15757:    
1.832     raeburn  15758: =item *
                   15759: 
1.1172.2.23  raeburn  15760: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  15761: All arguments are optional. Returns a hash of a roles, either for
                   15762: co-author/assistant author roles for a user's Construction Space
1.906     albertel 15763: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  15764: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   15765: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   15766: For each key, value is set to colon-separated start and end times for
                   15767: the role.  If no username and domain are specified, will default to
1.934     raeburn  15768: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  15769: of role statuses (active, future or previous), roles 
                   15770: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   15771: to restrict the list of roles reported. If no array ref is 
                   15772: provided for types, will default to return only active roles.
1.834     albertel 15773: 
1.1172.2.13  raeburn  15774: =item *
                   15775: 
                   15776: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   15777: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   15778: 
                   15779: Additional optional arguments are: $type (if role checking is to be restricted
                   15780: to certain user status types -- previous (expired roles), active (currently
                   15781: available roles) or future (roles available in the future), and
                   15782: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  15783: have active Domain Coordinator role in course's domain or in additional
                   15784: domains (specified in 'Domains to check for privileged users' in course
                   15785: environment -- set via:  Course Settings -> Classlists and staff listing).
                   15786: 
                   15787: =item *
                   15788: 
                   15789: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   15790: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   15791: $possdomains and $possroles are optional array refs -- to domains to check and
                   15792: roles to check.  If $possdomains is not specified, a dump will be done of the
                   15793: users' roles.db to check for a dc or su role in any domain. This can be
                   15794: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   15795: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   15796: this then allows &privileged_by_domain() to be used, which caches the identity
                   15797: of privileged users, eliminating the need for repeated calls to &dump().
                   15798: 
                   15799: =item *
                   15800: 
                   15801: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15802: where the outer hash keys are domains specified in the $possdomains array ref,
                   15803: next inner hash keys are privileged roles specified in the $roles array ref,
                   15804: and the innermost hash contains key = value pairs for username:domain = end:start
                   15805: for active or future "privileged" users with that role in that domain. To avoid
                   15806: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15807: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  15808: 
1.243     albertel 15809: =back
                   15810: 
                   15811: =head2 User Modification
                   15812: 
                   15813: =over 4
                   15814: 
                   15815: =item *
                   15816: 
1.957     raeburn  15817: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15818: user for the level given by URL.  Optional start and end dates (leave empty
                   15819: string or zero for "no date")
1.191     harris41 15820: 
                   15821: =item *
                   15822: 
1.243     albertel 15823: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15824: change a users, password, possible return values are: ok,
                   15825: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15826: refused
1.191     harris41 15827: 
                   15828: =item *
                   15829: 
1.243     albertel 15830: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15831: 
                   15832: =item *
                   15833: 
1.1058    raeburn  15834: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   15835:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   15836: 
                   15837: will update user information (firstname,middlename,lastname,generation,
                   15838: permanentemail), and if forceid is true, student/employee ID also.
                   15839: A user's institutional affiliation(s) can also be updated.
                   15840: User information fields will not be overwritten with empty entries 
                   15841: unless the field is included in the $candelete array reference.
                   15842: This array is included when a single user is modified via "Manage Users",
                   15843: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 15844: 
                   15845: =item *
                   15846: 
1.286     matthew  15847: modifystudent
                   15848: 
1.957     raeburn  15849: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  15850: The course id is resolved based on the current user's environment.  
                   15851: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  15852: associated with a course.
                   15853: 
1.297     matthew  15854: This call is essentially a wrapper for lonnet::modifyuser and
                   15855: lonnet::modify_student_enrollment
1.286     matthew  15856: 
                   15857: Inputs: 
                   15858: 
                   15859: =over 4
                   15860: 
1.957     raeburn  15861: =item B<$udom> Student's loncapa domain
1.286     matthew  15862: 
1.957     raeburn  15863: =item B<$uname> Student's loncapa login name
1.286     matthew  15864: 
1.964     bisitz   15865: =item B<$uid> Student/Employee ID
1.286     matthew  15866: 
1.957     raeburn  15867: =item B<$umode> Student's authentication mode
1.286     matthew  15868: 
1.957     raeburn  15869: =item B<$upass> Student's password
1.286     matthew  15870: 
1.957     raeburn  15871: =item B<$first> Student's first name
1.286     matthew  15872: 
1.957     raeburn  15873: =item B<$middle> Student's middle name
1.286     matthew  15874: 
1.957     raeburn  15875: =item B<$last> Student's last name
1.286     matthew  15876: 
1.957     raeburn  15877: =item B<$gene> Student's generation
1.286     matthew  15878: 
1.957     raeburn  15879: =item B<$usec> Student's section in course
1.286     matthew  15880: 
                   15881: =item B<$end> Unix time of the roles expiration
                   15882: 
                   15883: =item B<$start> Unix time of the roles start date
                   15884: 
                   15885: =item B<$forceid> If defined, allow $uid to be changed
                   15886: 
                   15887: =item B<$desiredhome> server to use as home server for student
                   15888: 
1.957     raeburn  15889: =item B<$email> Student's permanent e-mail address
                   15890: 
                   15891: =item B<$type> Type of enrollment (auto or manual)
                   15892: 
1.963     raeburn  15893: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   15894: 
                   15895: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  15896: 
1.963     raeburn  15897: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  15898: 
1.963     raeburn  15899: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  15900: 
1.1172.2.19  raeburn  15901: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   15902: 
                   15903: =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  15904: 
1.286     matthew  15905: =back
1.297     matthew  15906: 
                   15907: =item *
                   15908: 
                   15909: modify_student_enrollment
                   15910: 
1.1172.2.31  raeburn  15911: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  15912: 'role.request.course' must be defined for this function to proceed.
                   15913: 
                   15914: Inputs:
                   15915: 
                   15916: =over 4
                   15917: 
1.1172.2.31  raeburn  15918: =item $udom, student's domain
1.297     matthew  15919: 
1.1172.2.31  raeburn  15920: =item $uname, student's name
1.297     matthew  15921: 
1.1172.2.31  raeburn  15922: =item $uid, student's user id
1.297     matthew  15923: 
1.1172.2.31  raeburn  15924: =item $first, student's first name
1.297     matthew  15925: 
                   15926: =item $middle
                   15927: 
                   15928: =item $last
                   15929: 
                   15930: =item $gene
                   15931: 
                   15932: =item $usec
                   15933: 
                   15934: =item $end
                   15935: 
                   15936: =item $start
                   15937: 
1.957     raeburn  15938: =item $type
                   15939: 
                   15940: =item $locktype
                   15941: 
                   15942: =item $cid
                   15943: 
                   15944: =item $selfenroll
                   15945: 
                   15946: =item $context
                   15947: 
1.1172.2.19  raeburn  15948: =item $credits, number of credits student will earn from this class
                   15949: 
1.1172.2.76  raeburn  15950: =item $instsec, institutional course section code for student
                   15951: 
1.297     matthew  15952: =back
                   15953: 
1.191     harris41 15954: 
                   15955: =item *
                   15956: 
1.243     albertel 15957: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   15958: custom role; give a custom role to a user for the level given by URL.  Specify
                   15959: name and domain of role author, and role name
1.191     harris41 15960: 
                   15961: =item *
                   15962: 
1.243     albertel 15963: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 15964: 
                   15965: =item *
                   15966: 
1.243     albertel 15967: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   15968: 
                   15969: =back
                   15970: 
                   15971: =head2 Course Infomation
                   15972: 
                   15973: =over 4
1.191     harris41 15974: 
                   15975: =item *
                   15976: 
1.1118    foxr     15977: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 15978: specified course id, including all environment settings for the
                   15979: course, the description of the course will be in the hash under the
                   15980: key 'description'
1.191     harris41 15981: 
1.1118    foxr     15982: $options is an optional parameter that if supplied is a hash reference that controls
                   15983: what how this function works.  It has the following key/values:
                   15984: 
                   15985: =over 4
                   15986: 
                   15987: =item freshen_cache
                   15988: 
                   15989: If defined, and the environment cache for the course is valid, it is 
                   15990: returned in the returned hash.
                   15991: 
                   15992: =item one_time
                   15993: 
                   15994: If defined, the last cache time is set to _now_
                   15995: 
                   15996: =item user
                   15997: 
                   15998: If defined, the supplied username is used instead of the current user.
                   15999: 
                   16000: 
                   16001: =back
                   16002: 
1.191     harris41 16003: =item *
                   16004: 
1.624     albertel 16005: resdata($name,$domain,$type,@which) : request for current parameter
                   16006: setting for a specific $type, where $type is either 'course' or 'user',
                   16007: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  16008: answers for 10 minutes.
1.243     albertel 16009: 
1.877     foxr     16010: =item *
                   16011: 
                   16012: get_courseresdata($courseid, $domain) : dump the entire course resource
                   16013: data base, returning a hash that is keyed by the resource name and has
                   16014: values that are the resource value.  I believe that the timestamps and
                   16015: versions are also returned.
                   16016: 
1.243     albertel 16017: =back
                   16018: 
                   16019: =head2 Course Modification
                   16020: 
                   16021: =over 4
1.191     harris41 16022: 
                   16023: =item *
                   16024: 
1.243     albertel 16025: writecoursepref($courseid,%prefs) : write preferences (environment
                   16026: database) for a course
1.191     harris41 16027: 
                   16028: =item *
                   16029: 
1.1011    raeburn  16030: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   16031: 
                   16032: =item *
                   16033: 
1.1038    raeburn  16034: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 16035: 
1.1167    droeschl 16036: =item *
                   16037: 
                   16038: is_course($courseid), is_course($cdom, $cnum)
                   16039: 
                   16040: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   16041: two component version $cdom, $cnum. It checks if the specified course exists.
                   16042: 
                   16043: Returns:
                   16044:     undef if the course doesn't exist, otherwise
                   16045:     in scalar context the combined courseid.
                   16046:     in list context the two components of the course identifier, domain and 
                   16047:     courseid.    
                   16048: 
1.243     albertel 16049: =back
                   16050: 
1.1172.2.109  raeburn  16051: =head2 Bubblesheet Configuration
                   16052: 
                   16053: =over 4
                   16054: 
                   16055: =item *
                   16056: 
                   16057: get_scantron_config($which)
                   16058: 
                   16059: $which - the name of the configuration to parse from the file.
                   16060: 
                   16061: Parses and returns the bubblesheet configuration line selected as a
                   16062: hash of configuration file fields.
                   16063: 
                   16064: 
                   16065: Returns:
                   16066:     If the named configuration is not in the file, an empty
                   16067:     hash is returned.
                   16068: 
                   16069:     a hash with the fields
                   16070:       name         - internal name for the this configuration setup
                   16071:       description  - text to display to operator that describes this config
                   16072:       CODElocation - if 0 or the string 'none'
                   16073:                           - no CODE exists for this config
                   16074:                      if -1 || the string 'letter'
                   16075:                           - a CODE exists for this config and is
                   16076:                             a string of letters
                   16077:                      Unsupported value (but planned for future support)
                   16078:                           if a positive integer
                   16079:                                - The CODE exists as the first n items from
                   16080:                                  the question section of the form
                   16081:                           if the string 'number'
                   16082:                                - The CODE exists for this config and is
                   16083:                                  a string of numbers
                   16084:       CODEstart   - (only matter if a CODE exists) column in the line where
                   16085:                      the CODE starts
                   16086:       CODElength  - length of the CODE
                   16087:       IDstart     - column where the student/employee ID starts
                   16088:       IDlength    - length of the student/employee ID info
                   16089:       Qstart      - column where the information from the bubbled
                   16090:                     'questions' start
                   16091:       Qlength     - number of columns comprising a single bubble line from
                   16092:                     the sheet. (usually either 1 or 10)
                   16093:       Qon         - either a single character representing the character used
                   16094:                     to signal a bubble was chosen in the positional setup, or
                   16095:                     the string 'letter' if the letter of the chosen bubble is
                   16096:                     in the final, or 'number' if a number representing the
                   16097:                     chosen bubble is in the file (1->A 0->J)
                   16098:       Qoff        - the character used to represent that a bubble was
                   16099:                     left blank
                   16100:       PaperID     - if the scanning process generates a unique number for each
                   16101:                     sheet scanned the column that this ID number starts in
                   16102:       PaperIDlength - number of columns that comprise the unique ID number
                   16103:                       for the sheet of paper
                   16104:       FirstName   - column that the first name starts in
                   16105:       FirstNameLength - number of columns that the first name spans
                   16106:       LastName    - column that the last name starts in
                   16107:       LastNameLength - number of columns that the last name spans
                   16108:       BubblesPerRow - number of bubbles available in each row used to
                   16109:                       bubble an answer. (If not specified, 10 assumed).
                   16110: 
                   16111: 
                   16112: =item *
                   16113: 
                   16114: get_scantronformat_file($cdom)
                   16115: 
                   16116: $cdom - the course's domain (optional); if not supplied, uses
                   16117: domain for current $env{'request.course.id'}.
                   16118: 
                   16119: Returns an array containing lines from the scantron format file for
                   16120: the domain of the course.
                   16121: 
                   16122: If a url for a custom.tab file is listed in domain's configuration.db,
                   16123: lines are from this file.
                   16124: 
                   16125: Otherwise, if a default.tab has been published in RES space by the
                   16126: domainconfig user, lines are from this file.
                   16127: 
                   16128: Otherwise, fall back to getting lines from the legacy file on the
                   16129: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   16130: 
                   16131: =back
                   16132: 
1.243     albertel 16133: =head2 Resource Subroutines
                   16134: 
                   16135: =over 4
1.191     harris41 16136: 
                   16137: =item *
                   16138: 
1.243     albertel 16139: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 16140: 
                   16141: =item *
                   16142: 
1.243     albertel 16143: repcopy($filename) : subscribes to the requested file, and attempts to
                   16144: replicate from the owning library server, Might return
1.607     raeburn  16145: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   16146: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 16147: resource. Expects the local filesystem pathname
                   16148: (/home/httpd/html/res/....)
                   16149: 
                   16150: =back
                   16151: 
                   16152: =head2 Resource Information
                   16153: 
                   16154: =over 4
1.191     harris41 16155: 
                   16156: =item *
                   16157: 
1.1172.2.28  raeburn  16158: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   16159: and returns the value of a variety of different possible values,
                   16160: $varname should be a request string, and the other parameters can be
                   16161: used to specify who and what one is asking about. Ordinarily, $cid 
                   16162: does not need to be specified, as it is retrived from 
                   16163: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   16164: within lonuserstate::loadmap() when initializing a course, before
                   16165: $env{'request.course.id'} has been set, so it needs to be provided
                   16166: in that one case.
1.243     albertel 16167: 
                   16168: Possible values for $varname are environment.lastname (or other item
                   16169: from the envirnment hash), user.name (or someother aspect about the
                   16170: user), resource.0.maxtries (or some other part and parameter of a
                   16171: resource)
1.204     albertel 16172: 
                   16173: =item *
                   16174: 
1.243     albertel 16175: directcondval($number) : get current value of a condition; reads from a state
                   16176: string
1.204     albertel 16177: 
                   16178: =item *
                   16179: 
1.243     albertel 16180: condval($condidx) : value of condition index based on state
1.204     albertel 16181: 
                   16182: =item *
                   16183: 
1.1172.2.146.  .13(raeb 16184:-23): metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 16185: resource's metadata, $what should be either a specific key, or either
                   16186: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1172.2.146.  .13(raeb 16187:-23): packages that this resource currently uses, the last 3 arguments are
                   16188:-23): only used internally for recursive metadata.
                   16189:-23): 
                   16190:-23): the toolsymb is only used where the uri is for an external tool (for which
                   16191:-23): the uri as well as the symb are guaranteed to be unique).
1.243     albertel 16192: 
                   16193: this function automatically caches all requests
1.191     harris41 16194: 
                   16195: =item *
                   16196: 
1.243     albertel 16197: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   16198: network of library servers; returns file handle of where SQL and regex results
                   16199: will be stored for query
1.191     harris41 16200: 
                   16201: =item *
                   16202: 
1.1172.2.66  raeburn  16203: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   16204: return symbolic list entry (all arguments optional).
                   16205: 
                   16206: Args: filename is the filename (including path) for the file for which a symb
                   16207: is required; donotrecurse, if true will prevent calls to allowed() being made
                   16208: to check access status if more than one resource was found in the bighash
                   16209: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   16210: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   16211: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   16212: cause possible symbs to be checked to determine if they are subject to content
                   16213: blocking, if so they will not be included as possible symbs; possibles is a
                   16214: ref to a hash, which, as a side effect, will be populated with all possible
                   16215: symbs (content blocking not tested).
                   16216: 
1.243     albertel 16217: returns the data handle
1.191     harris41 16218: 
                   16219: =item *
                   16220: 
1.1172.2.17  raeburn  16221: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  16222: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 16223: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  16224: on failure, user must be in a course, as it assumes the existence of
                   16225: the course initial hash, and uses $env('request.course.id'}.  The third
                   16226: arg is an optional reference to a scalar.  If this arg is passed in the
                   16227: call to symbverify, it will be set to 1 if the symb has been set to be 
                   16228: encrypted; otherwise it will be null.
1.243     albertel 16229: 
1.191     harris41 16230: =item *
                   16231: 
1.243     albertel 16232: symbclean($symb) : removes versions numbers from a symb, returns the
                   16233: cleaned symb
1.191     harris41 16234: 
                   16235: =item *
                   16236: 
1.243     albertel 16237: is_on_map($uri) : checks if the $uri is somewhere on the current
                   16238: course map, user must be in a course for it to work.
1.191     harris41 16239: 
                   16240: =item *
                   16241: 
1.243     albertel 16242: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 16243: 
                   16244: =item *
                   16245: 
1.243     albertel 16246: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   16247: a random seed, all arguments are optional, if they aren't sent it uses the
                   16248: environment to derive them. Note: if symb isn't sent and it can't get one
                   16249: from &symbread it will use the current time as its return value
1.191     harris41 16250: 
                   16251: =item *
                   16252: 
1.243     albertel 16253: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   16254: unfakeable, receipt
1.191     harris41 16255: 
                   16256: =item *
                   16257: 
1.620     albertel 16258: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 16259: 
                   16260: =item *
                   16261: 
1.243     albertel 16262: countacc($url) : count the number of accesses to a given URL
1.191     harris41 16263: 
                   16264: =item *
                   16265: 
1.243     albertel 16266: 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 16267: 
                   16268: =item *
                   16269: 
1.243     albertel 16270: 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 16271: 
                   16272: =item *
                   16273: 
1.243     albertel 16274: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 16275: 
                   16276: =item *
                   16277: 
1.243     albertel 16278: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   16279: forcing spreadsheet to reevaluate the resource scores next time.
                   16280: 
1.1172.2.13  raeburn  16281: =item *
                   16282: 
                   16283: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   16284: when viewing in course context.
                   16285: 
                   16286:  input: six args -- filename (decluttered), course number, course domain,
                   16287:                     url, symb (if registered) and group (if this is a
                   16288:                     group item -- e.g., bulletin board, group page etc.).
                   16289: 
                   16290:  output: array of five scalars --
                   16291:          $cfile -- url for file editing if editable on current server
                   16292:          $home -- homeserver of resource (i.e., for author if published,
                   16293:                                           or course if uploaded.).
                   16294:          $switchserver --  1 if server switch will be needed.
                   16295:          $forceedit -- 1 if icon/link should be to go to edit mode
                   16296:          $forceview -- 1 if icon/link should be to go to view mode
                   16297: 
                   16298: =item *
                   16299: 
                   16300: is_course_upload($file,$cnum,$cdom)
                   16301: 
                   16302: Used in course context to determine if current file was uploaded to
                   16303: the course (i.e., would be found in /userfiles/docs on the course's
                   16304: homeserver.
                   16305: 
                   16306:   input: 3 args -- filename (decluttered), course number and course domain.
                   16307:   output: boolean -- 1 if file was uploaded.
                   16308: 
1.243     albertel 16309: =back
                   16310: 
                   16311: =head2 Storing/Retreiving Data
                   16312: 
                   16313: =over 4
1.191     harris41 16314: 
                   16315: =item *
                   16316: 
1.1172.2.64  raeburn  16317: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   16318: permanently for this url; hashref needs to be given and should be a \%hashname;
                   16319: the remaining args aren't required and if they aren't passed or are '' they will
                   16320: be derived from the env (with the exception of $laststore, which is an
                   16321: optional arg used when a user's submission is stored in grading).
                   16322: $laststore is $version=$timestamp, where $version is the most recent version
                   16323: number retrieved for the corresponding $symb in the $namespace db file, and
                   16324: $timestamp is the timestamp for that transaction (UNIX time).
                   16325: $laststore is currently only passed when cstore() is called by
                   16326: structuretags::finalize_storage().
1.191     harris41 16327: 
                   16328: =item *
                   16329: 
1.1172.2.64  raeburn  16330: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   16331: but uses critical subroutine
1.191     harris41 16332: 
                   16333: =item *
                   16334: 
1.243     albertel 16335: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   16336: all args are optional
1.191     harris41 16337: 
                   16338: =item *
                   16339: 
1.717     albertel 16340: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   16341: dumps the complete (or key matching regexp) namespace into a hash
                   16342: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   16343: normally &store()ed into
                   16344: 
                   16345: $range should be either an integer '100' (give me the first 100
                   16346:                                            matching records)
                   16347:               or be  two integers sperated by a - with no spaces
                   16348:                  '30-50' (give me the 30th through the 50th matching
                   16349:                           records)
                   16350: 
                   16351: 
                   16352: =item *
                   16353: 
1.1172.2.59  raeburn  16354: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 16355: replaces a &store() version of data with a replacement set of data
                   16356: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  16357: reference. If $tolog is true, the transaction is logged in the courselog
                   16358: with an action=PUTSTORE.
1.717     albertel 16359: 
                   16360: =item *
                   16361: 
1.243     albertel 16362: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   16363: works very similar to store/cstore, but all data is stored in a
                   16364: temporary location and can be reset using tmpreset, $storehash should
                   16365: be a hash reference, returns nothing on success
1.191     harris41 16366: 
                   16367: =item *
                   16368: 
1.243     albertel 16369: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   16370: similar to restore, but all data is stored in a temporary location and
                   16371: can be reset using tmpreset. Returns a hash of values on success,
                   16372: error string otherwise.
1.191     harris41 16373: 
                   16374: =item *
                   16375: 
1.243     albertel 16376: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   16377: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 16378: 
                   16379: =item *
                   16380: 
1.243     albertel 16381: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16382: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 16383: 
                   16384: =item *
                   16385: 
1.243     albertel 16386: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   16387: namesp ($udom and $uname are optional)
1.191     harris41 16388: 
                   16389: =item *
                   16390: 
1.702     albertel 16391: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 16392: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 16393: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  16394: 
1.702     albertel 16395: $range should be either an integer '100' (give me the first 100
                   16396:                                            matching records)
                   16397:               or be  two integers sperated by a - with no spaces
                   16398:                  '30-50' (give me the 30th through the 50th matching
                   16399:                           records)
1.449     matthew  16400: =item *
                   16401: 
                   16402: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   16403: $store can be a scalar, an array reference, or if the amount to be 
                   16404: incremented is > 1, a hash reference.
                   16405: 
                   16406: ($udom and $uname are optional)
1.191     harris41 16407: 
                   16408: =item *
                   16409: 
1.243     albertel 16410: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   16411: ($udom and $uname are optional)
1.191     harris41 16412: 
                   16413: =item *
                   16414: 
1.243     albertel 16415: cput($namespace,$storehash,$udom,$uname) : critical put
                   16416: ($udom and $uname are optional)
1.191     harris41 16417: 
                   16418: =item *
                   16419: 
1.748     albertel 16420: newput($namespace,$storehash,$udom,$uname) :
                   16421: 
                   16422: Attempts to store the items in the $storehash, but only if they don't
                   16423: currently exist, if this succeeds you can be certain that you have 
                   16424: successfully created a new key value pair in the $namespace db.
                   16425: 
                   16426: 
                   16427: Args:
                   16428:  $namespace: name of database to store values to
                   16429:  $storehash: hashref to store to the db
                   16430:  $udom: (optional) domain of user containing the db
                   16431:  $uname: (optional) name of user caontaining the db
                   16432: 
                   16433: Returns:
                   16434:  'ok' -> succeeded in storing all keys of $storehash
                   16435:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   16436:                         least <key> already existed in the db (other
                   16437:                         requested keys may also already exist)
1.967     bisitz   16438:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 16439:  'con_lost' -> unable to contact request server
                   16440:  'refused' -> action was not allowed by remote machine
                   16441: 
                   16442: 
                   16443: =item *
                   16444: 
1.243     albertel 16445: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16446: reference filled in from namesp (encrypts the return communication)
                   16447: ($udom and $uname are optional)
1.191     harris41 16448: 
                   16449: =item *
                   16450: 
1.243     albertel 16451: log($udom,$name,$home,$message) : write to permanent log for user; use
                   16452: critical subroutine
                   16453: 
1.806     raeburn  16454: =item *
                   16455: 
1.860     raeburn  16456: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   16457: array reference filled in from namespace found in domain level on either
                   16458: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  16459: 
                   16460: =item *
                   16461: 
1.860     raeburn  16462: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   16463: domain level either on specified domain server ($uhome) or primary domain 
                   16464: server ($udom and $uhome are optional)
1.806     raeburn  16465: 
1.943     raeburn  16466: =item * 
                   16467: 
1.1172.2.35  raeburn  16468: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   16469: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   16470: the target domain.
                   16471: 
                   16472: May also include additional key => value pairs for the following groups:
                   16473: 
                   16474: =over
                   16475: 
                   16476: =item
                   16477: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   16478: 
                   16479: =over
                   16480: 
                   16481: =item defaultquota, authorquota
                   16482: 
                   16483: =back
                   16484: 
                   16485: =item
                   16486: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   16487: portfolio for users).
                   16488: 
                   16489: =over
                   16490: 
                   16491: =item
                   16492: aboutme, blog, webdav, portfolio
                   16493: 
                   16494: =back
                   16495: 
                   16496: =item
                   16497: requestcourses: ability to request courses, and how requests are processed.
                   16498: 
                   16499: =over
                   16500: 
                   16501: =item
1.1172.2.37  raeburn  16502: official, unofficial, community, textbook
1.1172.2.35  raeburn  16503: 
                   16504: =back
                   16505: 
                   16506: =item
                   16507: inststatus: types of institutional affiliation, and order in which they are displayed.
                   16508: 
                   16509: =over
                   16510: 
                   16511: =item
1.1172.2.44  raeburn  16512: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  16513: 
                   16514: =back
                   16515: 
                   16516: =item
                   16517: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   16518: for course's uploaded content.
                   16519: 
                   16520: =over
                   16521: 
                   16522: =item
1.1172.2.68  raeburn  16523: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   16524: communityquota, textbookquota
1.1172.2.35  raeburn  16525: 
                   16526: =back
                   16527: 
                   16528: =item
                   16529: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   16530: on your servers.
                   16531: 
                   16532: =over
                   16533: 
                   16534: =item
                   16535: remotesessions, hostedsessions
                   16536: 
                   16537: =back
                   16538: 
                   16539: =back
                   16540: 
                   16541: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   16542: utility to create a configuration.db file on a domain's primary library server
                   16543: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   16544: -- corresponding values are authentication type (internal, krb4, krb5,
                   16545: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   16546: will be available. Values are retrieved from cache (if current), unless the
                   16547: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   16548: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   16549: 
                   16550: Typical usage:
1.943     raeburn  16551: 
1.1172.2.35  raeburn  16552: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  16553: 
1.243     albertel 16554: =back
                   16555: 
                   16556: =head2 Network Status Functions
                   16557: 
                   16558: =over 4
1.191     harris41 16559: 
                   16560: =item *
                   16561: 
1.1137    raeburn  16562: dirlist() : return directory list based on URI (first arg).
                   16563: 
                   16564: Inputs: 1 required, 5 optional.
                   16565: 
                   16566: =over
                   16567: 
                   16568: =item 
                   16569: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   16570: 
                   16571: =item
                   16572: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   16573: 
                   16574: =item
                   16575: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   16576: 
                   16577: =item
                   16578: $getpropath - boolean: 1 if prepend path using &propath(). 
                   16579: 
                   16580: =item
                   16581: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   16582: 
                   16583: =item 
                   16584: $alternateRoot - path to prepend in place of path from $uri.
                   16585: 
                   16586: =back
                   16587: 
                   16588: Returns: Array of up to two items.
                   16589: 
                   16590: =over
                   16591: 
                   16592: a reference to an array of files/subdirectories
                   16593: 
                   16594: =over
                   16595: 
                   16596: Each element in the array of files/subdirectories is a & separated list of
                   16597: item name and the result of running stat on the item.  If dirlist was requested
                   16598: for a file instead of a directory, the item name will be ''. For a directory 
                   16599: listing, if the item is a metadata file, the element will end &N&M 
                   16600: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   16601: default copyright set (1).  
                   16602: 
                   16603: =back
                   16604: 
                   16605: a scalar containing error condition (if encountered).
                   16606: 
                   16607: =over
                   16608: 
                   16609: =item 
                   16610: no_host (no homeserver identified for $username:$domain).
                   16611: 
                   16612: =item 
                   16613: no_such_host (server contacted for listing not identified as valid host).
                   16614: 
                   16615: =item 
                   16616: con_lost (connection to remote server failed).
                   16617: 
                   16618: =item 
                   16619: refused (invalid $username:$domain received on lond side).
                   16620: 
                   16621: =item 
                   16622: no_such_dir (directory at specified path on lond side does not exist). 
                   16623: 
                   16624: =item 
                   16625: empty (directory at specified path on lond side is empty).
                   16626: 
                   16627: =over
                   16628: 
                   16629: This is currently not encountered because the &ls3, &ls2, 
                   16630: &ls (_handler) routines on the lond side do not filter out
                   16631: . and .. from a directory listing. 
                   16632: 
                   16633: =back
                   16634: 
                   16635: =back
                   16636: 
                   16637: =back
1.191     harris41 16638: 
                   16639: =item *
                   16640: 
1.243     albertel 16641: spareserver() : find server with least workload from spare.tab
                   16642: 
1.986     foxr     16643: 
                   16644: =item *
                   16645: 
                   16646: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   16647: if there is no corresponding loncapa host.
                   16648: 
1.243     albertel 16649: =back
                   16650: 
1.986     foxr     16651: 
1.243     albertel 16652: =head2 Apache Request
                   16653: 
                   16654: =over 4
1.191     harris41 16655: 
                   16656: =item *
                   16657: 
1.243     albertel 16658: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   16659: localhost, posts hash
                   16660: 
                   16661: =back
                   16662: 
                   16663: =head2 Data to String to Data
                   16664: 
                   16665: =over 4
1.191     harris41 16666: 
                   16667: =item *
                   16668: 
1.243     albertel 16669: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   16670: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 16671: 
                   16672: =item *
                   16673: 
1.243     albertel 16674: hashref2str($hashref) : convert a hashref into a string complete with
                   16675: escaping and '=' and '&' separators, supports elements that are
                   16676: arrayrefs and hashrefs
1.191     harris41 16677: 
                   16678: =item *
                   16679: 
1.243     albertel 16680: arrayref2str($arrayref) : convert an arrayref into a string complete
                   16681: with escaping and '&' separators, supports elements that are arrayrefs
                   16682: and hashrefs
1.191     harris41 16683: 
                   16684: =item *
                   16685: 
1.243     albertel 16686: str2hash($string) : convert string to hash using unescaping and
                   16687: splitting on '=' and '&', supports elements that are arrayrefs and
                   16688: hashrefs
1.191     harris41 16689: 
                   16690: =item *
                   16691: 
1.243     albertel 16692: str2array($string) : convert string to hash using unescaping and
                   16693: splitting on '&', supports elements that are arrayrefs and hashrefs
                   16694: 
                   16695: =back
                   16696: 
                   16697: =head2 Logging Routines
                   16698: 
                   16699: 
                   16700: These routines allow one to make log messages in the lonnet.log and
                   16701: lonnet.perm logfiles.
1.191     harris41 16702: 
1.1119    foxr     16703: =over 4
                   16704: 
1.191     harris41 16705: =item *
                   16706: 
1.243     albertel 16707: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 16708: 
                   16709: =item *
                   16710: 
1.243     albertel 16711: logthis() : append message to the normal lonnet.log file, it gets
                   16712: preiodically rolled over and deleted.
1.191     harris41 16713: 
                   16714: =item *
                   16715: 
1.243     albertel 16716: logperm() : append a permanent message to lonnet.perm.log, this log
                   16717: file never gets deleted by any automated portion of the system, only
                   16718: messages of critical importance should go in here.
                   16719: 
1.1119    foxr     16720: 
1.243     albertel 16721: =back
                   16722: 
                   16723: =head2 General File Helper Routines
                   16724: 
                   16725: =over 4
1.191     harris41 16726: 
                   16727: =item *
                   16728: 
1.481     raeburn  16729: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   16730: (a) files in /uploaded
                   16731:   (i) If a local copy of the file exists - 
                   16732:       compares modification date of local copy with last-modified date for 
                   16733:       definitive version stored on home server for course. If local copy is 
                   16734:       stale, requests a new version from the home server and stores it. 
                   16735:       If the original has been removed from the home server, then local copy 
                   16736:       is unlinked.
                   16737:   (ii) If local copy does not exist -
                   16738:       requests the file from the home server and stores it. 
                   16739:   
                   16740:   If $caller is 'uploadrep':  
                   16741:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   16742:     for request for files originally uploaded via DOCS. 
                   16743:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   16744:   
                   16745:   Otherwise:
                   16746:      This indicates a call from the content generation phase of the request.
                   16747:      -  returns the entire contents of the file or -1.
                   16748:      
                   16749: (b) files in /res
                   16750:    - returns the entire contents of a file or -1; 
                   16751:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 16752: 
1.712     albertel 16753: 
                   16754: =item *
                   16755: 
                   16756: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   16757:                   reference
                   16758: 
                   16759: returns either a stat() list of data about the file or an empty list
                   16760: if the file doesn't exist or couldn't find out about it (connection
                   16761: problems or user unknown)
                   16762: 
1.191     harris41 16763: =item *
                   16764: 
1.243     albertel 16765: filelocation($dir,$file) : returns file system location of a file
                   16766: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   16767: directory that relative $file lookups are to looked in ($dir of /a/dir
                   16768: and a file of ../bob will become /a/bob)
1.191     harris41 16769: 
                   16770: =item *
                   16771: 
                   16772: hreflocation($dir,$file) : returns file system location or a URL; same as
                   16773: filelocation except for hrefs
                   16774: 
                   16775: =item *
                   16776: 
1.1172.2.49  raeburn  16777: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   16778: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 16779: 
1.243     albertel 16780: =back
                   16781: 
1.608     albertel 16782: =head2 Usererfile file routines (/uploaded*)
                   16783: 
                   16784: =over 4
                   16785: 
                   16786: =item *
                   16787: 
                   16788: userfileupload(): main rotine for putting a file in a user or course's
                   16789:                   filespace, arguments are,
                   16790: 
1.620     albertel 16791:  formname - required - this is the name of the element in $env where the
1.608     albertel 16792:            filename, and the contents of the file to create/modifed exist
1.620     albertel 16793:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   16794:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  16795:  context - if coursedoc, store the file in the course of the active role
                   16796:              of the current user; 
                   16797:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   16798:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 16799:  subdir - required - subdirectory to put the file in under ../userfiles/
                   16800:          if undefined, it will be placed in "unknown"
                   16801: 
                   16802:  (This routine calls clean_filename() to remove any dangerous
                   16803:  characters from the filename, and then calls finuserfileupload() to
                   16804:  complete the transaction)
                   16805: 
                   16806:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16807:  and /adm/notfound.html if unsuccessful
                   16808: 
                   16809: =item *
                   16810: 
                   16811: clean_filename(): routine for cleaing a filename up for storage in
                   16812:                  userfile space, argument is:
                   16813: 
                   16814:  filename - proposed filename
                   16815: 
                   16816: returns: the new clean filename
                   16817: 
                   16818: =item *
                   16819: 
1.1090    raeburn  16820: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16821: userspace, probably shouldn't be called directly
                   16822: 
                   16823:   docuname: username or courseid of destination for the file
                   16824:   docudom: domain of user/course of destination for the file
                   16825:   formname: same as for userfileupload()
1.1090    raeburn  16826:   fname: filename (including subdirectories) for the file
                   16827:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  16828:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16829:   allfiles: reference to hash used to store objects found by parser
                   16830:   codebase: reference to hash used for codebases of java objects found by parser
                   16831:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16832:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16833:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   16834:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   16835:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   16836:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  16837:   mimetype: reference to scalar to accommodate mime type determined
                   16838:             from File::MMagic if $parser = parse.
1.608     albertel 16839: 
                   16840:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  16841:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   16842:  was 'overwrite').
                   16843:  
1.608     albertel 16844: 
                   16845: =item *
                   16846: 
                   16847: renameuserfile(): renames an existing userfile to a new name
                   16848: 
                   16849:   Args:
                   16850:    docuname: username or courseid of destination for the file
                   16851:    docudom: domain of user/course of destination for the file
                   16852:    old: current file name (including any subdirs under userfiles)
                   16853:    new: desired file name (including any subdirs under userfiles)
                   16854: 
                   16855: =item *
                   16856: 
                   16857: mkdiruserfile(): creates a directory is a userfiles dir
                   16858: 
                   16859:   Args:
                   16860:    docuname: username or courseid of destination for the file
                   16861:    docudom: domain of user/course of destination for the file
                   16862:    dir: dir to create (including any subdirs under userfiles)
                   16863: 
                   16864: =item *
                   16865: 
                   16866: removeuserfile(): removes a file that exists in userfiles
                   16867: 
                   16868:   Args:
                   16869:    docuname: username or courseid of destination for the file
                   16870:    docudom: domain of user/course of destination for the file
                   16871:    fname: filname to delete (including any subdirs under userfiles)
                   16872: 
                   16873: =item *
                   16874: 
                   16875: removeuploadedurl(): convience function for removeuserfile()
                   16876: 
                   16877:   Args:
                   16878:    url:  a full /uploaded/... url to delete
                   16879: 
1.747     albertel 16880: =item * 
                   16881: 
                   16882: get_portfile_permissions():
                   16883:   Args:
                   16884:     domain: domain of user or course contain the portfolio files
                   16885:     user: name of user or num of course contain the portfolio files
                   16886:   Returns:
                   16887:     hashref of a dump of the proper file_permissions.db
                   16888:    
                   16889: 
                   16890: =item * 
                   16891: 
                   16892: get_access_controls():
                   16893: 
                   16894: Args:
                   16895:   current_permissions: the hash ref returned from get_portfile_permissions()
                   16896:   group: (optional) the group you want the files associated with
                   16897:   file: (optional) the file you want access info on
                   16898: 
                   16899: Returns:
1.749     raeburn  16900:     a hash (keys are file names) of hashes containing
                   16901:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   16902:         values are XML containing access control settings (see below) 
1.747     albertel 16903: 
                   16904: Internal notes:
                   16905: 
1.749     raeburn  16906:  access controls are stored in file_permissions.db as key=value pairs.
                   16907:     key -> path to file/file_name\0uniqueID:scope_end_start
                   16908:         where scope -> public,guest,course,group,domains or users.
                   16909:               end -> UNIX time for end of access (0 -> no end date)
                   16910:               start -> UNIX time for start of access
                   16911: 
                   16912:     value -> XML description of access control
                   16913:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   16914:             <start></start>
                   16915:             <end></end>
                   16916: 
                   16917:             <password></password>  for scope type = guest
                   16918: 
                   16919:             <domain></domain>     for scope type = course or group
                   16920:             <number></number>
                   16921:             <roles id="">
                   16922:              <role></role>
                   16923:              <access></access>
                   16924:              <section></section>
                   16925:              <group></group>
                   16926:             </roles>
                   16927: 
                   16928:             <dom></dom>         for scope type = domains
                   16929: 
                   16930:             <users>             for scope type = users
                   16931:              <user>
                   16932:               <uname></uname>
                   16933:               <udom></udom>
                   16934:              </user>
                   16935:             </users>
                   16936:            </scope> 
                   16937:               
                   16938:  Access data is also aggregated for each file in an additional key=value pair:
                   16939:  key -> path to file/file_name\0accesscontrol 
                   16940:  value -> reference to hash
                   16941:           hash contains key = value pairs
                   16942:           where key = uniqueID:scope_end_start
                   16943:                 value = UNIX time record was last updated
                   16944: 
                   16945:           Used to improve speed of look-ups of access controls for each file.  
                   16946:  
                   16947:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   16948: 
1.1172.2.13  raeburn  16949: =item *
                   16950: 
1.749     raeburn  16951: modify_access_controls():
                   16952: 
                   16953: Modifies access controls for a portfolio file
                   16954: Args
                   16955: 1. file name
                   16956: 2. reference to hash of required changes,
                   16957: 3. domain
                   16958: 4. username
                   16959:   where domain,username are the domain of the portfolio owner 
                   16960:   (either a user or a course) 
                   16961: 
                   16962: Returns:
                   16963: 1. result of additions or updates ('ok' or 'error', with error message). 
                   16964: 2. result of deletions ('ok' or 'error', with error message).
                   16965: 3. reference to hash of any new or updated access controls.
                   16966: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   16967:    key = integer (inbound ID)
1.1172.2.13  raeburn  16968:    value = uniqueID
                   16969: 
                   16970: =item *
                   16971: 
                   16972: get_timebased_id():
                   16973: 
                   16974: Attempts to get a unique timestamp-based suffix for use with items added to a
                   16975: course via the Course Editor (e.g., folders, composite pages,
                   16976: group bulletin boards).
                   16977: 
                   16978: Args: (first three required; six others optional)
                   16979: 
                   16980: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   16981:    docssequence, or name of group
                   16982: 
                   16983: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   16984:    e.g., num, boardids
                   16985: 
                   16986: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   16987:    file will be named nohist_namespace.db
                   16988: 
                   16989: 4. cdom: domain of course; default is current course domain from %env
                   16990: 
                   16991: 5. cnum: course number; default is current course number from %env
                   16992: 
                   16993: 6. idtype: set to concat if an additional digit is to be appended to the
                   16994:    unix timestamp to form the suffix, if the plain timestamp is already
                   16995:    in use.  Default is to not do this, but simply increment the unix
                   16996:    timestamp by 1 until a unique key is obtained.
                   16997: 
                   16998: 7. who: holder of locking key; defaults to user:domain for user.
                   16999: 
                   17000: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   17001:    retrying); default is 3.
                   17002: 
                   17003: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   17004: 
                   17005: Returns:
                   17006: 
                   17007: 1. suffix obtained (numeric)
                   17008: 
                   17009: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   17010: 
                   17011: 3. error: contains (localized) error message if an error occurred.
                   17012: 
1.747     albertel 17013: 
1.608     albertel 17014: =back
                   17015: 
1.243     albertel 17016: =head2 HTTP Helper Routines
                   17017: 
                   17018: =over 4
                   17019: 
1.191     harris41 17020: =item *
                   17021: 
                   17022: escape() : unpack non-word characters into CGI-compatible hex codes
                   17023: 
                   17024: =item *
                   17025: 
                   17026: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   17027: 
1.243     albertel 17028: =back
                   17029: 
                   17030: =head1 PRIVATE SUBROUTINES
                   17031: 
                   17032: =head2 Underlying communication routines (Shouldn't call)
                   17033: 
                   17034: =over 4
                   17035: 
                   17036: =item *
                   17037: 
                   17038: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   17039: 
                   17040: =item *
                   17041: 
                   17042: reply() : uses subreply to send a message to remote machine, logs all failures
                   17043: 
                   17044: =item *
                   17045: 
                   17046: critical() : passes a critical message to another server; if cannot
                   17047: get through then place message in connection buffer directory and
                   17048: returns con_delayed, if incapable of saving message, returns
                   17049: con_failed
                   17050: 
                   17051: =item *
                   17052: 
                   17053: reconlonc() : tries to reconnect lonc client processes.
                   17054: 
                   17055: =back
                   17056: 
                   17057: =head2 Resource Access Logging
                   17058: 
                   17059: =over 4
                   17060: 
                   17061: =item *
                   17062: 
                   17063: flushcourselogs() : flush (save) buffer logs and access logs
                   17064: 
                   17065: =item *
                   17066: 
                   17067: courselog($what) : save message for course in hash
                   17068: 
                   17069: =item *
                   17070: 
                   17071: courseacclog($what) : save message for course using &courselog().  Perform
                   17072: special processing for specific resource types (problems, exams, quizzes, etc).
                   17073: 
1.191     harris41 17074: =item *
                   17075: 
                   17076: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   17077: as a PerlChildExitHandler
1.243     albertel 17078: 
                   17079: =back
                   17080: 
                   17081: =head2 Other
                   17082: 
                   17083: =over 4
                   17084: 
                   17085: =item *
                   17086: 
                   17087: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 17088: 
                   17089: =back
                   17090: 
                   17091: =cut
1.877     foxr     17092: 

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