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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.146.  .20(raeb    4:-24): # $Id: lonnet.pm,v 1.1172.2.146.2.19 2024/02/28 05:40:11 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.146.  .18(raeb 2513:-24):                                   'requestauthor','authordefaults',
                   2514:-24):                                   'selfenrollment','coursecategories',
                   2515:-24):                                   'autoenroll','helpsettings',
                   2516:-24):                                   'wafproxy','ltisec','toolsec',
                   2517:-24):                                   'domexttool','exttool'],$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.146.  .18(raeb 2558:-24):     if (ref($domconfig{'authordefaults'}) eq 'HASH') {
                   2559:-24):         foreach my $item ('nocodemirror','copyright','sourceavail','domcoordacc','editors') {
                   2560:-24):             if ($item eq 'editors') {
                   2561:-24):                 if (ref($domconfig{'authordefaults'}{'editors'}) eq 'ARRAY') {
                   2562:-24):                     $domdefaults{$item} = join(',',@{$domconfig{'authordefaults'}{'editors'}});
                   2563:-24):                 }
                   2564:-24):             } else {
                   2565:-24):                 $domdefaults{$item} = $domconfig{'authordefaults'}{$item};
                   2566:-24):             }
                   2567:-24):         }
                   2568:-24):     }
1.1172.2.9  raeburn  2569:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2570:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2571:     }
1.989     raeburn  2572:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2573:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2574:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2575:         }
                   2576:     }
1.1047    raeburn  2577:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2578:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1172.2.144  raeburn  2579:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1172.2.60  raeburn  2580:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2581:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2582:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2583:         }
1.1172.2.41  raeburn  2584:         foreach my $type (@coursetypes) {
                   2585:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2586:                 unless ($type eq 'community') {
                   2587:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2588:                 }
                   2589:             }
                   2590:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2591:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2592:             }
1.1172.2.146.  .14(raeb 2593:-23):             if (ref($domconfig{'coursedefaults'}{'coursequota'}) eq 'HASH') {
                   2594:-23):                 $domdefaults{$type.'coursequota'} = $domconfig{'coursedefaults'}{'coursequota'}{$type};
                   2595:-23):             }
1.1172.2.60  raeburn  2596:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2597:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2598:                     $domdefaults{$type.'postsubtimeout'} =
                   2599:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2600:                 }
                   2601:             }
1.1172.2.146.  .13(raeb 2602:-23):             if (ref($domconfig{'coursedefaults'}{'domexttool'}) eq 'HASH') {
                   2603:-23):                 $domdefaults{$type.'domexttool'} = $domconfig{'coursedefaults'}{'domexttool'}{$type};
                   2604:-23):             } else {
                   2605:-23):                 $domdefaults{$type.'domexttool'} = 1;
                   2606:-23):             }
                   2607:-23):             if (ref($domconfig{'coursedefaults'}{'exttool'}) eq 'HASH') {
                   2608:-23):                 $domdefaults{$type.'exttool'} = $domconfig{'coursedefaults'}{'exttool'}{$type};
                   2609:-23):             } else {
                   2610:-23):                 $domdefaults{$type.'exttool'} = 0;
                   2611:-23):             }
1.1172.2.30  raeburn  2612:         }
1.1172.2.67  raeburn  2613:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2614:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2615:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2616:                 if (@clonecodes) {
                   2617:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2618:                 }
                   2619:             }
                   2620:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2621:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2622:         }
1.1172.2.103  raeburn  2623:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2624:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2625:         }
1.1172.2.146.  .3(raebu 2626:22):         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
                   2627:22):             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
                   2628:22):         }
1.1047    raeburn  2629:     }
1.1073    raeburn  2630:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2631:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2632:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2633:         }
                   2634:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2635:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2636:         }
1.1172.2.62  raeburn  2637:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2638:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2639:         }
1.1172.2.137  raeburn  2640:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1172.2.136  raeburn  2641:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2642:         }
1.1073    raeburn  2643:     }
1.1172.2.41  raeburn  2644:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2645:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2646:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2647:                             'approval','limit');
                   2648:             foreach my $type (@coursetypes) {
                   2649:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2650:                     my @mgrdc = ();
                   2651:                     foreach my $item (@settings) {
                   2652:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2653:                             push(@mgrdc,$item);
                   2654:                         }
                   2655:                     }
                   2656:                     if (@mgrdc) {
                   2657:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2658:                     }
                   2659:                 }
                   2660:             }
                   2661:         }
                   2662:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2663:             foreach my $type (@coursetypes) {
                   2664:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2665:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2666:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2667:                     }
                   2668:                 }
                   2669:             }
                   2670:         }
                   2671:     }
1.1172.2.46  raeburn  2672:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2673:         $domdefaults{'catauth'} = 'std';
                   2674:         $domdefaults{'catunauth'} = 'std';
                   2675:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2676:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2677:         }
                   2678:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2679:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2680:         }
                   2681:     }
1.1172.2.76  raeburn  2682:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2683:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1172.2.146  raeburn  2684:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1172.2.76  raeburn  2685:     }
1.1172.2.89  raeburn  2686:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2687:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2688:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2689:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2690:         }
                   2691:     }
1.1172.2.142  raeburn  2692:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   2693:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
                   2694:             if ($domconfig{'wafproxy'}{$item}) {
                   2695:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
                   2696:             }
                   2697:         }
                   2698:     }
1.1172.2.146.  .4(raebu 2699:22):     if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   2700:22):         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
                   2701:22):             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
                   2702:22):             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
                   2703:22):             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
                   2704:22):         }
                   2705:22):         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
                   2706:22):             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
          .13(raeb 2707:-23):                 $domdefaults{'ltiprivhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
                   2708:-23):             }
                   2709:-23):         }
          .17(raeb 2710:-24):         if (ref($domconfig{'ltisec'}{'suggested'}) eq 'HASH') {
                   2711:-24):             my %suggestions = %{$domconfig{'ltisec'}{'suggested'}};
                   2712:-24):             foreach my $item (keys(%{$domconfig{'ltisec'}{'suggested'}})) {
                   2713:-24):                 unless (ref($domconfig{'ltisec'}{'suggested'}{$item}) eq 'HASH') {
                   2714:-24):                     delete($suggestions{$item});
                   2715:-24):                 }
                   2716:-24):             }
                   2717:-24):             if (keys(%suggestions)) {
                   2718:-24):                 $domdefaults{'linkprotsuggested'} = \%suggestions;
                   2719:-24):             }
                   2720:-24):         }
          .13(raeb 2721:-23):     }
                   2722:-23):     if (ref($domconfig{'toolsec'}) eq 'HASH') {
                   2723:-23):         if (ref($domconfig{'toolsec'}{'encrypt'}) eq 'HASH') {
                   2724:-23):             $domdefaults{'toolenc_crs'} = $domconfig{'toolsec'}{'encrypt'}{'crs'};
                   2725:-23):             $domdefaults{'toolenc_dom'} = $domconfig{'toolsec'}{'encrypt'}{'dom'};
                   2726:-23):         }
                   2727:-23):         if (ref($domconfig{'toolsec'}{'private'}) eq 'HASH') {
                   2728:-23):             if (ref($domconfig{'toolsec'}{'private'}{'keys'}) eq 'ARRAY') {
                   2729:-23):                 $domdefaults{'toolprivhosts'} = $domconfig{'toolsec'}{'private'}{'keys'};
          .4(raebu 2730:22):             }
                   2731:22):         }
                   2732:22):     }
1.1172.2.23  raeburn  2733:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2734:     return %domdefaults;
                   2735: }
                   2736: 
1.1172.2.106  raeburn  2737: sub get_dom_cats {
                   2738:     my ($dom) = @_;
                   2739:     return unless (&domain($dom));
                   2740:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2741:     unless (defined($cached)) {
                   2742:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2743:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2744:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2745:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2746:             } else {
                   2747:                 $cats = {};
                   2748:             }
                   2749:         } else {
                   2750:             $cats = {};
                   2751:         }
                   2752:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2753:     }
                   2754:     return $cats;
                   2755: }
                   2756: 
                   2757: sub get_dom_instcats {
                   2758:     my ($dom) = @_;
                   2759:     return unless (&domain($dom));
                   2760:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2761:     unless (defined($cached)) {
                   2762:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2763:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2764:         if ($totcodes > 0) {
                   2765:             my $caller = 'global';
                   2766:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2767:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2768:                 $instcats = {
1.1172.2.146.  .10(raeb 2769:-23):                                 totcodes => $totcodes,
1.1172.2.106  raeburn  2770:                                 codes => \%codes,
                   2771:                                 codetitles => \@codetitles,
                   2772:                                 cat_titles => \%cat_titles,
                   2773:                                 cat_order => \%cat_order,
                   2774:                             };
                   2775:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2776:             }
                   2777:         }
                   2778:     }
                   2779:     return $instcats;
                   2780: }
                   2781: 
                   2782: sub retrieve_instcodes {
                   2783:     my ($coursecodes,$dom) = @_;
                   2784:     my $totcodes;
                   2785:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2786:     foreach my $course (keys(%courses)) {
                   2787:         if (ref($courses{$course}) eq 'HASH') {
                   2788:             if ($courses{$course}{'inst_code'} ne '') {
                   2789:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2790:                 $totcodes ++;
                   2791:             }
                   2792:         }
                   2793:     }
                   2794:     return $totcodes;
                   2795: }
                   2796: 
1.1172.2.113  raeburn  2797: # --------------------------------------------- Get domain config for passwords
                   2798: 
                   2799: sub get_passwdconf {
                   2800:     my ($dom) = @_;
                   2801:     my (%passwdconf,$gotconf,$lookup);
                   2802:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2803:     if (defined($cached)) {
                   2804:         if (ref($result) eq 'HASH') {
                   2805:             %passwdconf = %{$result};
                   2806:             $gotconf = 1;
                   2807:         }
                   2808:     }
                   2809:     unless ($gotconf) {
                   2810:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2811:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2812:             %passwdconf = %{$domconfig{'passwords'}};
                   2813:         }
                   2814:         my $cachetime = 24*60*60;
                   2815:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2816:     }
                   2817:     return %passwdconf;
                   2818: }
                   2819: 
1.1172.2.146.  .1(raebu 2820:22): sub course_portal_url {
                   2821:22):     my ($cnum,$cdom,$r) = @_;
                   2822:22):     my $chome = &homeserver($cnum,$cdom);
                   2823:22):     my $hostname = &hostname($chome);
                   2824:22):     my $protocol = $protocol{$chome};
                   2825:22):     $protocol = 'http' if ($protocol ne 'https');
                   2826:22):     my %domdefaults = &get_domain_defaults($cdom);
                   2827:22):     my $firsturl;
                   2828:22):     if ($domdefaults{'portal_def'}) {
                   2829:22):         $firsturl = $domdefaults{'portal_def'};
                   2830:22):     } else {
                   2831:22):         my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
                   2832:22):         $hostname = $alias if ($alias ne '');
                   2833:22):         $firsturl = $protocol.'://'.$hostname;
                   2834:22):     }
                   2835:22):     return $firsturl;
                   2836:22): }
                   2837:22): 
          .12(raeb 2838:-23): sub url_prefix {
                   2839:-23):     my ($r,$dom,$home,$context) = @_;
                   2840:-23):     my $prefix;
                   2841:-23):     my %domdefs = &get_domain_defaults($dom);
                   2842:-23):     if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
                   2843:-23):         if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
                   2844:-23):             $prefix = $1;
                   2845:-23):         }
                   2846:-23):     }
                   2847:-23):     if ($prefix eq '') {
                   2848:-23):         my $hostname = &hostname($home);
                   2849:-23):         my $protocol = $protocol{$home};
                   2850:-23):         $protocol = 'http' if ($protocol{$home} ne 'https');
                   2851:-23):         my $alias = &use_proxy_alias($r,$home);
                   2852:-23):         $hostname = $alias if ($alias ne '');
                   2853:-23):         $prefix = $protocol.'://'.$hostname;
                   2854:-23):     }
                   2855:-23):     return $prefix;
                   2856:-23): }
                   2857:-23): 
1.344     www      2858: # --------------------------------------------------- Assign a key to a student
                   2859: 
                   2860: sub assign_access_key {
1.364     www      2861: #
                   2862: # a valid key looks like uname:udom#comments
                   2863: # comments are being appended
                   2864: #
1.498     www      2865:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2866:     $kdom=
1.620     albertel 2867:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2868:     $knum=
1.620     albertel 2869:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2870:     $cdom=
1.620     albertel 2871:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2872:     $cnum=
1.620     albertel 2873:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2874:     $udom=$env{'user.name'} unless (defined($udom));
                   2875:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2876:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2877:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2878:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2879:                                                   # assigned to this person
                   2880:                                                   # - this should not happen,
1.345     www      2881:                                                   # unless something went wrong
                   2882:                                                   # the first time around
                   2883: # ready to assign
1.364     www      2884:         $logentry=$1.'; '.$logentry;
1.496     www      2885:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2886:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2887: # key now belongs to user
1.346     www      2888: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2889:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2890:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2891:                 return 'ok';
                   2892:             } else {
                   2893:                 return 
                   2894:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2895: 	    }
                   2896:         } else {
                   2897:             return 'error: Could not assign key, try again later.';
                   2898:         }
1.364     www      2899:     } elsif (!$existing{$ckey}) {
1.345     www      2900: # the key does not exist
                   2901: 	return 'error: The key does not exist';
                   2902:     } else {
                   2903: # the key is somebody else's
                   2904: 	return 'error: The key is already in use';
                   2905:     }
1.344     www      2906: }
                   2907: 
1.364     www      2908: # ------------------------------------------ put an additional comment on a key
                   2909: 
                   2910: sub comment_access_key {
                   2911: #
                   2912: # a valid key looks like uname:udom#comments
                   2913: # comments are being appended
                   2914: #
                   2915:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2916:     $cdom=
1.620     albertel 2917:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2918:     $cnum=
1.620     albertel 2919:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2920:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2921:     if ($existing{$ckey}) {
                   2922:         $existing{$ckey}.='; '.$logentry;
                   2923: # ready to assign
1.367     www      2924:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2925:                                                  $cdom,$cnum) eq 'ok') {
                   2926: 	    return 'ok';
                   2927:         } else {
                   2928: 	    return 'error: Count not store comment.';
                   2929:         }
                   2930:     } else {
                   2931: # the key does not exist
                   2932: 	return 'error: The key does not exist';
                   2933:     }
                   2934: }
                   2935: 
1.344     www      2936: # ------------------------------------------------------ Generate a set of keys
                   2937: 
                   2938: sub generate_access_keys {
1.364     www      2939:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2940:     $cdom=
1.620     albertel 2941:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2942:     $cnum=
1.620     albertel 2943:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2944:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2945:     unless (($cdom) && ($cnum)) { return 0; }
                   2946:     if ($number>10000) { return 0; }
                   2947:     sleep(2); # make sure don't get same seed twice
                   2948:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2949:     my $total=0;
                   2950:     for (my $i=1;$i<=$number;$i++) {
                   2951:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2952:                   sprintf("%lx",int(100000*rand)).'-'.
                   2953:                   sprintf("%lx",int(100000*rand));
                   2954:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2955:        $newkey=~s/0/h/g; # and also 0 and O
                   2956:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2957:        if ($existing{$newkey}) {
                   2958:            $i--;
                   2959:        } else {
1.364     www      2960: 	  if (&put('accesskeys',
                   2961:               { $newkey => '# generated '.localtime().
1.620     albertel 2962:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2963:                            '; '.$logentry },
                   2964: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2965:               $total++;
                   2966: 	  }
                   2967:        }
                   2968:     }
1.620     albertel 2969:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2970:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2971:     return $total;
                   2972: }
                   2973: 
                   2974: # ------------------------------------------------------- Validate an accesskey
                   2975: 
                   2976: sub validate_access_key {
                   2977:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2978:     $cdom=
1.620     albertel 2979:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2980:     $cnum=
1.620     albertel 2981:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2982:     $udom=$env{'user.domain'} unless (defined($udom));
                   2983:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2984:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2985:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2986: }
                   2987: 
                   2988: # ------------------------------------- Find the section of student in a course
1.652     albertel 2989: sub devalidate_getsection_cache {
                   2990:     my ($udom,$unam,$courseid)=@_;
                   2991:     my $hashid="$udom:$unam:$courseid";
                   2992:     &devalidate_cache_new('getsection',$hashid);
                   2993: }
1.298     matthew  2994: 
1.815     albertel 2995: sub courseid_to_courseurl {
                   2996:     my ($courseid) = @_;
                   2997:     #already url style courseid
                   2998:     return $courseid if ($courseid =~ m{^/});
                   2999: 
                   3000:     if (exists($env{'course.'.$courseid.'.num'})) {
                   3001: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   3002: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   3003: 	return "/$cdom/$cnum";
                   3004:     }
                   3005: 
                   3006:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   3007:     if (exists($courseinfo{'num'})) {
                   3008: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   3009:     }
                   3010: 
                   3011:     return undef;
                   3012: }
                   3013: 
1.298     matthew  3014: sub getsection {
                   3015:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 3016:     my $cachetime=1800;
1.551     albertel 3017: 
                   3018:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 3019:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 3020:     if (defined($cached)) { return $result; }
                   3021: 
1.298     matthew  3022:     my %Pending; 
                   3023:     my %Expired;
                   3024:     #
                   3025:     # Each role can either have not started yet (pending), be active, 
                   3026:     #    or have expired.
                   3027:     #
                   3028:     # If there is an active role, we are done.
                   3029:     #
                   3030:     # If there is more than one role which has not started yet, 
                   3031:     #     choose the one which will start sooner
                   3032:     # If there is one role which has not started yet, return it.
                   3033:     #
                   3034:     # If there is more than one expired role, choose the one which ended last.
                   3035:     # If there is a role which has expired, return it.
                   3036:     #
1.815     albertel 3037:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  3038:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  3039:     foreach my $key (keys(%roleshash)) {
1.479     albertel 3040:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  3041:         my $section=$1;
                   3042:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  3043:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  3044:         my $now=time;
1.548     albertel 3045:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  3046:             $Expired{$end}=$section;
                   3047:             next;
                   3048:         }
1.548     albertel 3049:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  3050:             $Pending{$start}=$section;
                   3051:             next;
                   3052:         }
1.599     albertel 3053:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  3054:     }
                   3055:     #
                   3056:     # Presumedly there will be few matching roles from the above
                   3057:     # loop and the sorting time will be negligible.
                   3058:     if (scalar(keys(%Pending))) {
                   3059:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 3060:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  3061:     } 
                   3062:     if (scalar(keys(%Expired))) {
                   3063:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   3064:         my $time = pop(@sorted);
1.599     albertel 3065:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  3066:     }
1.599     albertel 3067:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  3068: }
1.70      www      3069: 
1.599     albertel 3070: sub save_cache {
                   3071:     &purge_remembered();
1.722     albertel 3072:     #&Apache::loncommon::validate_page();
1.620     albertel 3073:     undef(%env);
1.780     albertel 3074:     undef($env_loaded);
1.599     albertel 3075: }
1.452     albertel 3076: 
1.599     albertel 3077: my $to_remember=-1;
                   3078: my %remembered;
                   3079: my %accessed;
                   3080: my $kicks=0;
                   3081: my $hits=0;
1.849     albertel 3082: sub make_key {
                   3083:     my ($name,$id) = @_;
1.872     albertel 3084:     if (length($id) > 65 
                   3085: 	&& length(&escape($id)) > 200) {
                   3086: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   3087:     }
1.849     albertel 3088:     return &escape($name.':'.$id);
                   3089: }
                   3090: 
1.599     albertel 3091: sub devalidate_cache_new {
                   3092:     my ($name,$id,$debug) = @_;
                   3093:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  3094:     my $remembered_id=$name.':'.$id;
1.849     albertel 3095:     $id=&make_key($name,$id);
1.599     albertel 3096:     $memcache->delete($id);
1.1172.2.81  raeburn  3097:     delete($remembered{$remembered_id});
                   3098:     delete($accessed{$remembered_id});
1.599     albertel 3099: }
                   3100: 
                   3101: sub is_cached_new {
                   3102:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  3103:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   3104:                                      # keys in %remembered hash, which persists for
                   3105:                                      # duration of request (no restriction on key length).
                   3106:     if (exists($remembered{$remembered_id})) {
                   3107: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   3108: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3109: 	$hits++;
1.1172.2.81  raeburn  3110: 	return ($remembered{$remembered_id},1);
1.599     albertel 3111:     }
1.1172.2.81  raeburn  3112:     $id=&make_key($name,$id);
1.599     albertel 3113:     my $value = $memcache->get($id);
                   3114:     if (!(defined($value))) {
                   3115: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 3116: 	return (undef,undef);
1.416     albertel 3117:     }
1.599     albertel 3118:     if ($value eq '__undef__') {
                   3119: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   3120: 	$value=undef;
                   3121:     }
1.1172.2.81  raeburn  3122:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3123:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   3124:     return ($value,1);
                   3125: }
                   3126: 
                   3127: sub do_cache_new {
                   3128:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  3129:     my $remembered_id=$name.':'.$id;
1.849     albertel 3130:     $id=&make_key($name,$id);
1.599     albertel 3131:     my $setvalue=$value;
                   3132:     if (!defined($setvalue)) {
                   3133: 	$setvalue='__undef__';
                   3134:     }
1.623     albertel 3135:     if (!defined($time) ) {
                   3136: 	$time=600;
                   3137:     }
1.599     albertel 3138:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 3139:     my $result = $memcache->set($id,$setvalue,$time);
                   3140:     if (! $result) {
1.872     albertel 3141: 	&logthis("caching of id -> $id  failed");
1.910     albertel 3142: 	$memcache->disconnect_all();
1.872     albertel 3143:     }
1.600     albertel 3144:     # need to make a copy of $value
1.1172.2.81  raeburn  3145:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3146:     return $value;
                   3147: }
                   3148: 
                   3149: sub make_room {
1.1172.2.81  raeburn  3150:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3151: 
1.1172.2.81  raeburn  3152:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3153:                                     : $value;
1.599     albertel 3154:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  3155:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3156:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3157:     my $to_kick;
                   3158:     my $max_time=0;
                   3159:     foreach my $other (keys(%accessed)) {
                   3160: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3161: 	    $to_kick=$other;
                   3162: 	    $max_time=&tv_interval($accessed{$other});
                   3163: 	}
                   3164:     }
                   3165:     delete($remembered{$to_kick});
                   3166:     delete($accessed{$to_kick});
                   3167:     $kicks++;
                   3168:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3169:     return;
                   3170: }
                   3171: 
1.599     albertel 3172: sub purge_remembered {
1.604     albertel 3173:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3174:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3175:     undef(%remembered);
                   3176:     undef(%accessed);
1.428     albertel 3177: }
1.70      www      3178: # ------------------------------------- Read an entry from a user's environment
                   3179: 
                   3180: sub userenvironment {
                   3181:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3182:     my $items;
                   3183:     foreach my $item (@what) {
                   3184:         $items.=&escape($item).'&';
                   3185:     }
                   3186:     $items=~s/\&$//;
1.70      www      3187:     my %returnhash=();
1.1009    raeburn  3188:     my $uhome = &homeserver($unam,$udom);
                   3189:     unless ($uhome eq 'no_host') {
                   3190:         my @answer=split(/\&/, 
                   3191:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3192:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3193:             return %returnhash;
                   3194:         }
1.1009    raeburn  3195:         my $i;
                   3196:         for ($i=0;$i<=$#what;$i++) {
                   3197: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3198:         }
1.70      www      3199:     }
                   3200:     return %returnhash;
1.1       albertel 3201: }
                   3202: 
1.617     albertel 3203: # ---------------------------------------------------------- Get a studentphoto
                   3204: sub studentphoto {
                   3205:     my ($udom,$unam,$ext) = @_;
                   3206:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3207:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3208:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3209:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3210:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3211:             } else {
                   3212:                 my ($result,$perm_reqd)=
1.707     albertel 3213: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3214:                 if ($result eq 'ok') {
                   3215:                     if (!($perm_reqd eq 'yes')) {
                   3216:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3217:                     }
                   3218:                 }
                   3219:             }
                   3220:         }
                   3221:     } else {
                   3222:         my ($result,$perm_reqd) = 
1.707     albertel 3223: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3224:         if ($result eq 'ok') {
                   3225:             if (!($perm_reqd eq 'yes')) {
                   3226:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3227:             }
                   3228:         }
                   3229:     }
                   3230:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3231: }
                   3232: 
                   3233: sub retrievestudentphoto {
                   3234:     my ($udom,$unam,$ext,$type) = @_;
                   3235:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3236:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3237:     if ($ret eq 'ok') {
                   3238:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3239:         if ($type eq 'thumbnail') {
                   3240:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3241:         }
                   3242:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3243:         return $tokenurl;
                   3244:     } else {
                   3245:         if ($type eq 'thumbnail') {
                   3246:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3247:         } else { 
                   3248:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3249:         }
1.617     albertel 3250:     }
                   3251: }
                   3252: 
1.263     www      3253: # -------------------------------------------------------------------- New chat
                   3254: 
                   3255: sub chatsend {
1.724     raeburn  3256:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3257:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3258:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3259:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3260:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3261: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3262: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3263: }
                   3264: 
                   3265: # ------------------------------------------ Find current version of a resource
                   3266: 
                   3267: sub getversion {
                   3268:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  3269:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3270:     return &currentversion(&filelocation('',$fname));
                   3271: }
                   3272: 
                   3273: sub currentversion {
                   3274:     my $fname=shift;
                   3275:     my $author=$fname;
                   3276:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3277:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3278:     my $home=&homeserver($uname,$udom);
1.292     www      3279:     if ($home eq 'no_host') { 
                   3280:         return -1; 
                   3281:     }
1.1112    www      3282:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3283:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3284: 	return -1;
                   3285:     }
1.1112    www      3286:     return $answer;
1.263     www      3287: }
                   3288: 
1.1111    www      3289: #
                   3290: # Return special version number of resource if set by override, empty otherwise
                   3291: #
                   3292: sub usedversion {
                   3293:     my $fname=shift;
                   3294:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3295:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3296:     if ($urlversion) { return $urlversion; }
                   3297:     return '';
                   3298: }
                   3299: 
1.1       albertel 3300: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3301: 
1.1       albertel 3302: sub subscribe {
                   3303:     my $fname=shift;
1.761     raeburn  3304:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3305:     $fname=~s/[\n\r]//g;
1.1       albertel 3306:     my $author=$fname;
                   3307:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3308:     my ($udom,$uname)=split(/\//,$author);
                   3309:     my $home=homeserver($uname,$udom);
1.335     albertel 3310:     if ($home eq 'no_host') {
                   3311:         return 'not_found';
1.1       albertel 3312:     }
                   3313:     my $answer=reply("sub:$fname",$home);
1.64      www      3314:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3315: 	$answer.=' by '.$home;
                   3316:     }
1.1       albertel 3317:     return $answer;
                   3318: }
                   3319:     
1.8       www      3320: # -------------------------------------------------------------- Replicate file
                   3321: 
                   3322: sub repcopy {
                   3323:     my $filename=shift;
1.23      www      3324:     $filename=~s/\/+/\//g;
1.1142    raeburn  3325:     my $londocroot = $perlvar{'lonDocRoot'};
                   3326:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3327:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3328:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3329: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3330: 	return &repcopy_userfile($filename);
                   3331:     }
1.532     albertel 3332:     $filename=~s/[\n\r]//g;
1.8       www      3333:     my $transname="$filename.in.transfer";
1.828     www      3334: # FIXME: this should flock
1.607     raeburn  3335:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3336:     my $remoteurl=subscribe($filename);
1.64      www      3337:     if ($remoteurl =~ /^con_lost by/) {
                   3338: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3339:            return 'unavailable';
1.8       www      3340:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3341: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3342: 	   return 'not_found';
1.64      www      3343:     } elsif ($remoteurl =~ /^rejected by/) {
                   3344: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3345:            return 'forbidden';
1.20      www      3346:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3347:            return 'ok';
1.8       www      3348:     } else {
1.290     www      3349:         my $author=$filename;
                   3350:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3351:         my ($udom,$uname)=split(/\//,$author);
                   3352:         my $home=homeserver($uname,$udom);
                   3353:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3354:            my @parts=split(/\//,$filename);
                   3355:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3356:            if ($path ne "$londocroot/res") {
1.8       www      3357:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3358: 	       return 'bad_request';
1.8       www      3359:            }
                   3360:            my $count;
                   3361:            for ($count=5;$count<$#parts;$count++) {
                   3362:                $path.="/$parts[$count]";
                   3363:                if ((-e $path)!=1) {
                   3364: 		   mkdir($path,0777);
                   3365:                }
                   3366:            }
                   3367:            my $ua=new LWP::UserAgent;
                   3368:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3369:            my $response=$ua->request($request,$transname);
                   3370:            if ($response->is_error()) {
                   3371: 	       unlink($transname);
                   3372:                my $message=$response->status_line;
1.672     albertel 3373:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3374:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3375:                return 'unavailable';
1.8       www      3376:            } else {
1.16      www      3377: 	       if ($remoteurl!~/\.meta$/) {
                   3378:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3379:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3380:                   if ($mresponse->is_error()) {
                   3381: 		      unlink($filename.'.meta');
                   3382:                       &logthis(
1.672     albertel 3383:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3384:                   }
                   3385: 	       }
1.8       www      3386:                rename($transname,$filename);
1.607     raeburn  3387:                return 'ok';
1.8       www      3388:            }
1.290     www      3389:        }
1.8       www      3390:     }
1.330     www      3391: }
                   3392: 
1.1172.2.124  raeburn  3393: # ------------------------------------------------- Unsubscribe from a resource
                   3394: 
                   3395: sub unsubscribe {
                   3396:     my ($fname) = @_;
                   3397:     my $answer;
                   3398:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3399:     $fname=~s/[\n\r]//g;
                   3400:     my $author=$fname;
                   3401:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3402:     my ($udom,$uname)=split(/\//,$author);
                   3403:     my $home=homeserver($uname,$udom);
                   3404:     if ($home eq 'no_host') {
                   3405:         $answer = 'no_host';
                   3406:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3407:         $answer = 'home';
                   3408:     } else {
1.1172.2.125  raeburn  3409:         $answer = reply("unsub:$fname",$home);
1.1172.2.124  raeburn  3410:     }
                   3411:     return $answer;
                   3412: }
                   3413: 
1.330     www      3414: # ------------------------------------------------ Get server side include body
                   3415: sub ssi_body {
1.381     albertel 3416:     my ($filelink,%form)=@_;
1.606     matthew  3417:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3418:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3419:     }
1.953     www      3420:     my $output='';
                   3421:     my $response;
1.980     raeburn  3422:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3423:        ($output,$response)=&externalssi($filelink);
1.953     www      3424:     } else {
1.1004    droeschl 3425:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3426:        $filelink .= 'inhibitmenu=yes';
1.953     www      3427:        ($output,$response)=&ssi($filelink,%form);
                   3428:     }
1.778     albertel 3429:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3430:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3431:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3432:     if (wantarray) {
                   3433:         return ($output, $response);
                   3434:     } else {
                   3435:         return $output;
                   3436:     }
1.8       www      3437: }
                   3438: 
1.15      www      3439: # --------------------------------------------------------- Server Side Include
                   3440: 
1.782     albertel 3441: sub absolute_url {
1.1172.2.145  raeburn  3442:     my ($host_name,$unalias,$keep_proto) = @_;
1.782     albertel 3443:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3444:     if ($host_name eq '') {
                   3445: 	$host_name = $ENV{'SERVER_NAME'};
                   3446:     }
1.1172.2.145  raeburn  3447:     if ($unalias) {
                   3448:         my $alias = &get_proxy_alias();
                   3449:         if ($alias eq $host_name) {
                   3450:             my $lonhost = $perlvar{'lonHostID'};
                   3451:             my $hostname = &hostname($lonhost);
                   3452:             my $lcproto;
                   3453:             if (($keep_proto) || ($hostname eq '')) {
                   3454:                 $lcproto = $protocol;
                   3455:             } else {
                   3456:                 $lcproto = $protocol{$lonhost};
                   3457:                 $lcproto = 'http' if ($lcproto ne 'https');
                   3458:                 $lcproto .= '://';
                   3459:             }
                   3460:             unless ($hostname eq '') {
                   3461:                 return $lcproto.$hostname;
                   3462:             }
                   3463:         }
                   3464:     } 
1.782     albertel 3465:     return $protocol.$host_name;
                   3466: }
                   3467: 
1.942     foxr     3468: #
                   3469: #   Server side include.
                   3470: # Parameters:
                   3471: #  fn     Possibly encrypted resource name/id.
                   3472: #  form   Hash that describes how the rendering should be done
                   3473: #         and other things.
1.944     foxr     3474: # Returns:
1.950     raeburn  3475: #   Scalar context: The content of the response.
                   3476: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3477: #     
1.15      www      3478: sub ssi {
                   3479: 
1.944     foxr     3480:     my ($fn,%form)=@_;
1.1172.2.145  raeburn  3481:     my ($host,$request,$response);
                   3482:     $host = &absolute_url('',1);
1.711     albertel 3483: 
                   3484:     $form{'no_update_last_known'}=1;
1.895     albertel 3485:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3486:     if (%form) {
1.1172.2.145  raeburn  3487:       $request=new HTTP::Request('POST',$host.$fn);
1.1172.2.58  raeburn  3488:       $request->content(join('&',map {
                   3489:             my $name = escape($_);
                   3490:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3491:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3492:             : &escape($form{$_}) );
                   3493:         } keys(%form)));
1.23      www      3494:     } else {
1.1172.2.145  raeburn  3495:       $request=new HTTP::Request('GET',$host.$fn);
1.23      www      3496:     }
                   3497: 
1.15      www      3498:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3499: 
1.1172.2.101  raeburn  3500:     if (($env{'request.course.id'}) &&
                   3501:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3502:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3503:         ($form{'grade_symb'} ne '') &&
                   3504:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3505:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3506:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3507:             my $ua=new LWP::UserAgent;
                   3508:             $ua->local_address('127.0.0.1');
                   3509:             $response = $ua->request($request);
                   3510:         } else {
                   3511:             {
                   3512:                 require LWP::Protocol::http;
                   3513:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3514:                 my $ua=new LWP::UserAgent;
                   3515:                 $response = $ua->request($request);
                   3516:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3517:             }
                   3518:         }
                   3519:     } else {
                   3520:         my $ua=new LWP::UserAgent;
                   3521:         $response = $ua->request($request);
                   3522:     }
1.944     foxr     3523:     if (wantarray) {
1.1172.2.3  raeburn  3524: 	return ($response->content, $response);
1.944     foxr     3525:     } else {
1.1172.2.3  raeburn  3526: 	return $response->content;
1.942     foxr     3527:     }
1.324     www      3528: }
                   3529: 
                   3530: sub externalssi {
                   3531:     my ($url)=@_;
                   3532:     my $ua=new LWP::UserAgent;
                   3533:     my $request=new HTTP::Request('GET',$url);
                   3534:     my $response=$ua->request($request);
1.954     raeburn  3535:     if (wantarray) {
                   3536:         return ($response->content, $response);
                   3537:     } else {
                   3538:         return $response->content;
                   3539:     }
1.15      www      3540: }
1.254     www      3541: 
1.1172.2.98  raeburn  3542: # If the local copy of a replicated resource is outdated, trigger a
                   3543: # connection from the homeserver to flush the delayed queue. If no update
                   3544: # happens, remove local copies of outdated resource (and corresponding
                   3545: # metadata file).
                   3546: 
                   3547: sub remove_stale_resfile {
                   3548:     my ($url) = @_;
                   3549:     my $removed;
                   3550:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3551:         my $audom = $1;
                   3552:         my $auname = $2;
                   3553:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3554:             my $homeserver = &homeserver($auname,$audom);
                   3555:             unless (($homeserver eq 'no_host') ||
                   3556:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3557:                 my $fname = &filelocation('',$url);
                   3558:                 if (-e $fname) {
                   3559:                     my $hostname = &hostname($homeserver);
                   3560:                     if ($hostname) {
1.1172.2.120  raeburn  3561:                         my $protocol = $protocol{$homeserver};
                   3562:                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3563:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120  raeburn  3564:                         my $ua=new LWP::UserAgent;
                   3565:                         $ua->timeout(5);
1.1172.2.98  raeburn  3566:                         my $request=new HTTP::Request('HEAD',$uri);
                   3567:                         my $response=$ua->request($request);
                   3568:                         if ($response->is_success()) {
                   3569:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3570:                             my $locmodtime = (stat($fname))[9];
                   3571:                             if ($locmodtime < $remmodtime) {
                   3572:                                 my $stale;
                   3573:                                 my $answer = &reply('pong',$homeserver);
                   3574:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3575:                                     sleep(0.2);
                   3576:                                     $locmodtime = (stat($fname))[9];
                   3577:                                     if ($locmodtime < $remmodtime) {
                   3578:                                         my $posstransfer = $fname.'.in.transfer';
                   3579:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3580:                                             $removed = 1;
                   3581:                                         } else {
                   3582:                                             $stale = 1;
                   3583:                                         }
                   3584:                                     } else {
                   3585:                                         $removed = 1;
                   3586:                                     }
                   3587:                                 } else {
                   3588:                                     $stale = 1;
                   3589:                                 }
                   3590:                                 if ($stale) {
1.1172.2.124  raeburn  3591:                                     if (unlink($fname)) {
                   3592:                                         if ($uri!~/\.meta$/) {
                   3593:                                             if (-e $fname.'.meta') {
                   3594:                                                 unlink($fname.'.meta');
                   3595:                                             }
                   3596:                                         }
                   3597:                                         my $unsubresult = &unsubscribe($fname);
                   3598:                                         unless ($unsubresult eq 'ok') {
                   3599:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3600:                                         }
                   3601:                                         $removed = 1;
1.1172.2.98  raeburn  3602:                                     }
                   3603:                                 }
                   3604:                             }
                   3605:                         }
                   3606:                     }
                   3607:                 }
                   3608:             }
                   3609:         }
                   3610:     }
                   3611:     return $removed;
                   3612: }
                   3613: 
1.492     albertel 3614: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3615: 
                   3616: sub allowuploaded {
                   3617:     my ($srcurl,$url)=@_;
                   3618:     $url=&clutter(&declutter($url));
                   3619:     my $dir=$url;
                   3620:     $dir=~s/\/[^\/]+$//;
                   3621:     my %httpref=();
                   3622:     my $httpurl=&hreflocation('',$url);
                   3623:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3624:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3625: }
1.477     raeburn  3626: 
1.1172.2.13  raeburn  3627: #
                   3628: # Determine if the current user should be able to edit a particular resource,
                   3629: # when viewing in course context.
                   3630: # (a) When viewing resource used to determine if "Edit" item is included in
                   3631: #     Functions.
                   3632: # (b) When displaying folder contents in course editor, used to determine if
                   3633: #     "Edit" link will be displayed alongside resource.
                   3634: #
                   3635: #  input: six args -- filename (decluttered), course number, course domain,
                   3636: #                   url, symb (if registered) and group (if this is a group
                   3637: #                   item -- e.g., bulletin board, group page etc.).
                   3638: #  output: array of five scalars --
                   3639: #          $cfile -- url for file editing if editable on current server
                   3640: #          $home -- homeserver of resource (i.e., for author if published,
                   3641: #                                           or course if uploaded.).
                   3642: #          $switchserver --  1 if server switch will be needed.
                   3643: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3644: #          $forceview -- 1 if icon/link should be to go to view mode
                   3645: #
                   3646: 
                   3647: sub can_edit_resource {
                   3648:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3649:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3650: #
                   3651: # For aboutme pages user can only edit his/her own.
                   3652: #
                   3653:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3654:         my ($sdom,$sname) = ($1,$2);
                   3655:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3656:             $home = $env{'user.home'};
                   3657:             $cfile = $resurl;
                   3658:             if ($env{'form.forceedit'}) {
                   3659:                 $forceview = 1;
                   3660:             } else {
                   3661:                 $forceedit = 1;
                   3662:             }
                   3663:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3664:         } else {
                   3665:             return;
                   3666:         }
                   3667:     }
                   3668: 
                   3669:     if ($env{'request.course.id'}) {
                   3670:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3671:         if ($group ne '') {
                   3672: # if this is a group homepage or group bulletin board, check group privs
                   3673:             my $allowed = 0;
                   3674:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3675:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3676:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3677:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3678:                     $allowed = 1;
                   3679:                 }
                   3680:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3681:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3682:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3683:                     $allowed = 1;
                   3684:                 }
                   3685:             }
                   3686:             if ($allowed) {
                   3687:                 $home=&homeserver($cnum,$cdom);
                   3688:                 if ($env{'form.forceedit'}) {
                   3689:                     $forceview = 1;
                   3690:                 } else {
                   3691:                     $forceedit = 1;
                   3692:                 }
                   3693:                 $cfile = $resurl;
                   3694:             } else {
                   3695:                 return;
                   3696:             }
                   3697:         } else {
1.1172.2.15  raeburn  3698:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3699:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3700:                     return;
                   3701:                 }
                   3702:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3703: #
                   3704: # No edit allowed where CC has switched to student role.
                   3705: #
                   3706:                 return;
                   3707:             }
                   3708:         }
                   3709:     }
                   3710: 
                   3711:     if ($file ne '') {
                   3712:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3713:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3714:                 $uploaded = 1;
                   3715:                 $incourse = 1;
                   3716:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3717:                     $cfile = &hreflocation('',$file);
                   3718:                     if ($env{'form.forceedit'}) {
                   3719:                         $forceview = 1;
                   3720:                     } else {
                   3721:                         $forceedit = 1;
                   3722:                     }
                   3723:                 }
                   3724:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3725:                 $incourse = 1;
                   3726:                 if ($env{'form.forceedit'}) {
                   3727:                     $forceview = 1;
                   3728:                 } else {
                   3729:                     $forceedit = 1;
                   3730:                 }
                   3731:                 $cfile = $resurl;
                   3732:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3733:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3734:                     $incourse = 1;
                   3735:                     if ($env{'form.forceedit'}) {
                   3736:                         $forceview = 1;
                   3737:                     } else {
                   3738:                         $forceedit = 1;
                   3739:                     }
                   3740:                     $cfile = $resurl;
                   3741:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3742:                     $incourse = 1;
                   3743:                     $cfile = $resurl.'/smpedit';
                   3744:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3745:                     $incourse = 1;
                   3746:                     if ($env{'form.forceedit'}) {
                   3747:                         $forceview = 1;
                   3748:                     } else {
                   3749:                         $forceedit = 1;
                   3750:                     }
                   3751:                     $cfile = $resurl;
1.1172.2.122  raeburn  3752:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3753:                     my ($map,$id,$res) = &decode_symb($symb);
                   3754:                     if ($map =~ /\.page$/) {
                   3755:                         $incourse = 1;
                   3756:                         if ($env{'form.forceedit'}) {
                   3757:                             $forceview = 1;
                   3758:                             $cfile = $map;
                   3759:                         } else {
                   3760:                             $forceedit = 1;
                   3761:                             $cfile =  '/adm/wrapper'.$resurl;
                   3762:                         }
                   3763:                     }
1.1172.2.146.  .1(raebu 3764:22):                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3765:22):                     $incourse = 1;
                   3766:22):                     if ($env{'form.forceedit'}) {
                   3767:22):                         $forceview = 1;
                   3768:22):                     } else {
                   3769:22):                         $forceedit = 1;
                   3770:22):                     }
                   3771:22):                     $cfile = $resurl;
1.1172.2.15  raeburn  3772:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3773:                     $incourse = 1;
                   3774:                     if ($env{'form.forceedit'}) {
                   3775:                         $forceview = 1;
                   3776:                     } else {
                   3777:                         $forceedit = 1;
                   3778:                     }
                   3779:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3780:                 }
                   3781:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3782:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3783:                 if (&is_on_map($template)) {
                   3784:                     $incourse = 1;
                   3785:                     $forceview = 1;
                   3786:                     $cfile = $template;
                   3787:                 }
                   3788:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3789:                 $incourse = 1;
                   3790:                 if ($env{'form.forceedit'}) {
                   3791:                     $forceview = 1;
                   3792:                 } else {
                   3793:                     $forceedit = 1;
                   3794:                 }
                   3795:                 $cfile = $resurl;
1.1172.2.146.  .1(raebu 3796:22):             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3797:22):                 $incourse = 1;
                   3798:22):                 if ($env{'form.forceedit'}) {
                   3799:22):                     $forceview = 1;
                   3800:22):                 } else {
                   3801:22):                     $forceedit = 1;
                   3802:22):                 }
                   3803:22):                 $cfile = $resurl;
1.1172.2.13  raeburn  3804:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3805:                 $incourse = 1;
                   3806:                 $forceview = 1;
                   3807:                 if ($symb) {
                   3808:                     my ($map,$id,$res)=&decode_symb($symb);
                   3809:                     $env{'request.symb'} = $symb;
                   3810:                     $cfile = &clutter($res);
                   3811:                 } else {
                   3812:                     $cfile = $env{'form.suppurl'};
1.1172.2.146.  .1(raebu 3813:22):                     my $escfile = &unescape($cfile);
                   3814:22):                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3815:22):                         $cfile = '/adm/wrapper'.$escfile;
                   3816:22):                     } else {
                   3817:22):                         $escfile =~ s{^http://}{};
                   3818:22):                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3819:22):                     }
1.1172.2.13  raeburn  3820:                 }
1.1172.2.31  raeburn  3821:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3822:                 if ($env{'form.forceedit'}) {
                   3823:                     $forceview = 1;
                   3824:                 } else {
                   3825:                     $forceedit = 1;
                   3826:                 }
                   3827:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3828:             }
                   3829:         }
                   3830:         if ($uploaded || $incourse) {
                   3831:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3832:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3833:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3834:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3835:             # Check that the user has permission to edit this resource
                   3836:             my $setpriv = 1;
                   3837:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3838:             if (defined($cfudom)) {
                   3839:                 $home=&homeserver($cfuname,$cfudom);
                   3840:                 $cfile=$file;
                   3841:             }
                   3842:         }
                   3843:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3844:             (($home ne '') && ($home ne 'no_host'))) {
                   3845:             my @ids=&current_machine_ids();
                   3846:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3847:                 $switchserver=1;
                   3848:             }
                   3849:         }
                   3850:     }
                   3851:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3852: }
                   3853: 
                   3854: sub is_course_upload {
                   3855:     my ($file,$cnum,$cdom) = @_;
                   3856:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3857:     $uploadpath =~ s{^\/}{};
                   3858:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3859:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3860:         return 1;
                   3861:     }
                   3862:     return;
                   3863: }
                   3864: 
                   3865: sub in_course {
                   3866:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3867:     if ($hideprivileged) {
                   3868:         my $skipuser;
1.1172.2.23  raeburn  3869:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3870:         my @possdoms = ($cdom);
                   3871:         if ($coursehash{'checkforpriv'}) {
                   3872:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3873:         }
                   3874:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3875:             $skipuser = 1;
                   3876:             if ($coursehash{'nothideprivileged'}) {
                   3877:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3878:                     my $user;
                   3879:                     if ($item =~ /:/) {
                   3880:                         $user = $item;
                   3881:                     } else {
                   3882:                         $user = join(':',split(/[\@]/,$item));
                   3883:                     }
                   3884:                     if ($user eq $uname.':'.$udom) {
                   3885:                         undef($skipuser);
                   3886:                         last;
                   3887:                     }
                   3888:                 }
                   3889:             }
                   3890:             if ($skipuser) {
                   3891:                 return 0;
                   3892:             }
                   3893:         }
                   3894:     }
                   3895:     $type ||= 'any';
                   3896:     if (!defined($cdom) || !defined($cnum)) {
                   3897:         my $cid  = $env{'request.course.id'};
                   3898:         $cdom = $env{'course.'.$cid.'.domain'};
                   3899:         $cnum = $env{'course.'.$cid.'.num'};
                   3900:     }
                   3901:     my $typesref;
                   3902:     if (($type eq 'any') || ($type eq 'all')) {
                   3903:         $typesref = ['active','previous','future'];
                   3904:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3905:         $typesref = [$type];
                   3906:     }
                   3907:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3908:                               $typesref,undef,[$cdom]);
                   3909:     my ($tmp) = keys(%roles);
                   3910:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3911:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3912:     if (@course_roles > 0) {
                   3913:         return 1;
                   3914:     }
                   3915:     return 0;
                   3916: }
                   3917: 
1.478     albertel 3918: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3919: # input: action, courseID, current domain, intended
1.637     raeburn  3920: #        path to file, source of file, instruction to parse file for objects,
                   3921: #        ref to hash for embedded objects,
                   3922: #        ref to hash for codebase of java objects.
1.1095    raeburn  3923: #        reference to scalar to accommodate mime type determined
                   3924: #          from File::MMagic if $parser = parse.
1.637     raeburn  3925: #
1.485     raeburn  3926: # output: url to file (if action was uploaddoc), 
                   3927: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3928: #
1.478     albertel 3929: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3930: # course.
1.477     raeburn  3931: #
1.478     albertel 3932: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3933: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3934: #          course's home server.
1.477     raeburn  3935: #
1.478     albertel 3936: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3937: #          be copied from $source (current location) to 
                   3938: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3939: #         and will then be copied to
                   3940: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3941: #         course's home server.
1.485     raeburn  3942: #
1.481     raeburn  3943: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3944: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3945: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3946: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3947: #         in course's home server.
1.637     raeburn  3948: #
1.477     raeburn  3949: 
                   3950: sub process_coursefile {
1.1095    raeburn  3951:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3952:         $mimetype)=@_;
1.477     raeburn  3953:     my $fetchresult;
1.638     albertel 3954:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3955:     if ($action eq 'propagate') {
1.638     albertel 3956:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3957: 			     $home);
1.481     raeburn  3958:     } else {
1.477     raeburn  3959:         my $fpath = '';
                   3960:         my $fname = $file;
1.478     albertel 3961:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3962:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3963:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3964:         if ($action eq 'copy') {
                   3965:             if ($source eq '') {
                   3966:                 $fetchresult = 'no source file';
                   3967:                 return $fetchresult;
                   3968:             } else {
                   3969:                 my $destination = $filepath.'/'.$fname;
                   3970:                 rename($source,$destination);
                   3971:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3972:                                  $home);
1.481     raeburn  3973:             }
                   3974:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3975:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3976:             print $fh $env{'form.'.$source};
1.481     raeburn  3977:             close($fh);
1.637     raeburn  3978:             if ($parser eq 'parse') {
1.1024    raeburn  3979:                 my $mm = new File::MMagic;
1.1095    raeburn  3980:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3981:                 if ($type eq 'text/html') {
1.1024    raeburn  3982:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3983:                     unless ($parse_result eq 'ok') {
                   3984:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3985:                     }
1.637     raeburn  3986:                 }
1.1095    raeburn  3987:                 if (ref($mimetype)) {
                   3988:                     $$mimetype = $type;
                   3989:                 } 
1.637     raeburn  3990:             }
1.477     raeburn  3991:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3992:                                  $home);
1.481     raeburn  3993:             if ($fetchresult eq 'ok') {
                   3994:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3995:             } else {
                   3996:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3997:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3998:                 return '/adm/notfound.html';
                   3999:             }
1.477     raeburn  4000:         }
                   4001:     }
1.485     raeburn  4002:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  4003:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 4004:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  4005:     }
                   4006:     return $fetchresult;
                   4007: }
                   4008: 
1.637     raeburn  4009: sub build_filepath {
                   4010:     my ($fpath) = @_;
                   4011:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   4012:     unless ($fpath eq '') {
                   4013:         my @parts=split('/',$fpath);
                   4014:         foreach my $part (@parts) {
                   4015:             $filepath.= '/'.$part;
                   4016:             if ((-e $filepath)!=1) {
                   4017:                 mkdir($filepath,0777);
                   4018:             }
                   4019:         }
                   4020:     }
                   4021:     return $filepath;
                   4022: }
                   4023: 
                   4024: sub store_edited_file {
1.638     albertel 4025:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  4026:     my $file = $primary_url;
                   4027:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   4028:     my $fpath = '';
                   4029:     my $fname = $file;
                   4030:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   4031:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   4032:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  4033:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  4034:     print $fh $content;
                   4035:     close($fh);
1.638     albertel 4036:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  4037:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4038: 			  $home);
1.637     raeburn  4039:     if ($$fetchresult eq 'ok') {
                   4040:         return '/uploaded/'.$fpath.'/'.$fname;
                   4041:     } else {
1.638     albertel 4042:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   4043: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  4044:         return '/adm/notfound.html';
                   4045:     }
                   4046: }
                   4047: 
1.531     albertel 4048: sub clean_filename {
1.831     albertel 4049:     my ($fname,$args)=@_;
1.315     www      4050: # Replace Windows backslashes by forward slashes
1.257     www      4051:     $fname=~s/\\/\//g;
1.831     albertel 4052:     if (!$args->{'keep_path'}) {
                   4053:         # Get rid of everything but the actual filename
                   4054: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   4055:     }
1.315     www      4056: # Replace spaces by underscores
                   4057:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  4058: # Transliterate non-ascii text to ascii
                   4059:     my $lang = &Apache::lonlocal::current_language();
                   4060:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      4061: # Replace all other weird characters by nothing
1.831     albertel 4062:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 4063: # Replace all .\d. sequences with _\d. so they no longer look like version
                   4064: # numbers
                   4065:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.140  raeburn  4066: # Replace three or more adjacent underscores with one for consistency
                   4067: # with loncfile::filename_check() so complete url can be extracted by
                   4068: # lonnet::decode_symb()
                   4069:     $fname=~s/_{3,}/_/g;
1.531     albertel 4070:     return $fname;
                   4071: }
1.1172.2.110  raeburn  4072: 
1.1051    raeburn  4073: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   4074: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   4075: # image with the same aspect ratio as the original, but with dimensions which do 
                   4076: # not exceed $resizewidth and $resizeheight.
                   4077:  
1.984     neumanie 4078: sub resizeImage {
1.1051    raeburn  4079:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   4080:     my $ima = Image::Magick->new;
                   4081:     my $resized;
                   4082:     if (-e $img_path) {
                   4083:         $ima->Read($img_path);
                   4084:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   4085:             my $width = $ima->Get('width');
                   4086:             my $height = $ima->Get('height');
                   4087:             if ($width > $resizewidth) {
                   4088: 	        my $factor = $width/$resizewidth;
                   4089:                 my $newheight = $height/$factor;
                   4090:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   4091:                 $resized = 1;
                   4092:             }
                   4093:         }
                   4094:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   4095:             my $width = $ima->Get('width');
                   4096:             my $height = $ima->Get('height');
                   4097:             if ($height > $resizeheight) {
                   4098:                 my $factor = $height/$resizeheight;
                   4099:                 my $newwidth = $width/$factor;
                   4100:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   4101:                 $resized = 1;
                   4102:             }
                   4103:         }
                   4104:         if ($resized) {
                   4105:             $ima->Write($img_path);
                   4106:         }
                   4107:     }
                   4108:     return;
1.977     amueller 4109: }
                   4110: 
1.608     albertel 4111: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 4112: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  4113: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  4114: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.146.  .13(raeb 4115:-23): #                                    canceloverwrite, scantron, toollogo or ''. 
1.1090    raeburn  4116: #                   if 'coursedoc': upload to the current course
                   4117: #                   if 'existingfile': write file to tmp/overwrites directory 
                   4118: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   4119: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 4120: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  4121: #        $parser - instruction to parse file for objects ($parser = parse) or
                   4122: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   4123: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   4124: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  4125: #        $allfiles - reference to hash for embedded objects
                   4126: #        $codebase - reference to hash for codebase of java objects
1.1172.2.146.  .13(raeb 4127:-23): #        $destuname - username for permanent storage of uploaded file
                   4128:-23): #        $destudom - domain for permanaent storage of uploaded file
1.860     raeburn  4129: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   4130: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  4131: #        $resizewidth - width (pixels) to which to resize uploaded image
                   4132: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  4133: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  4134: #                    from File::MMagic.
1.858     raeburn  4135: # 
1.686     albertel 4136: # output: url of file in userspace, or error: <message> 
                   4137: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 4138: 
1.531     albertel 4139: sub userfileupload {
1.1090    raeburn  4140:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  4141:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 4142:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 4143:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 4144:     $fname=&clean_filename($fname);
1.1090    raeburn  4145:     # See if there is anything left
1.257     www      4146:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  4147:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   4148:     if ($fname =~ /^\./) {
                   4149:         my ($s,$usec) = &gettimeofday();
                   4150:         while (length($usec) < 6) {
                   4151:             $usec = '0'.$usec;
                   4152:         }
                   4153:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   4154:     }
1.1090    raeburn  4155:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   4156:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   4157:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   4158:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  4159:         my $now = time;
1.1090    raeburn  4160:         my $filepath;
1.1095    raeburn  4161:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  4162:              $filepath = 'tmp/helprequests/'.$now;
                   4163:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   4164:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   4165:                          '_'.$env{'user.domain'}.'/pending';
                   4166:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   4167:             my ($docuname,$docudom);
1.1172.2.96  raeburn  4168:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  4169:                 $docudom = $destudom;
                   4170:             } else {
                   4171:                 $docudom = $env{'user.domain'};
                   4172:             }
1.1172.2.96  raeburn  4173:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  4174:                 $docuname = $destuname;
                   4175:             } else {
                   4176:                 $docuname = $env{'user.name'};
                   4177:             }
                   4178:             if (exists($env{'form.group'})) {
                   4179:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4180:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4181:             }
                   4182:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   4183:             if ($context eq 'canceloverwrite') {
                   4184:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   4185:                 if (-e  $tempfile) {
                   4186:                     my @info = stat($tempfile);
                   4187:                     if ($info[9] eq $env{'form.timestamp'}) {
                   4188:                         unlink($tempfile);
                   4189:                     }
                   4190:                 }
                   4191:                 return;
1.523     raeburn  4192:             }
                   4193:         }
1.1090    raeburn  4194:         # Create the directory if not present
1.741     raeburn  4195:         my @parts=split(/\//,$filepath);
                   4196:         my $fullpath = $perlvar{'lonDaemons'};
                   4197:         for (my $i=0;$i<@parts;$i++) {
                   4198:             $fullpath .= '/'.$parts[$i];
                   4199:             if ((-e $fullpath)!=1) {
                   4200:                 mkdir($fullpath,0777);
                   4201:             }
                   4202:         }
1.1172.2.96  raeburn  4203:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  4204:         print $fh $env{'form.'.$formname};
                   4205:         close($fh);
1.1090    raeburn  4206:         if ($context eq 'existingfile') {
                   4207:             my @info = stat($fullpath.'/'.$fname);
                   4208:             return ($fullpath.'/'.$fname,$info[9]);
                   4209:         } else {
                   4210:             return $fullpath.'/'.$fname;
                   4211:         }
1.523     raeburn  4212:     }
1.995     raeburn  4213:     if ($subdir eq 'scantron') {
                   4214:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4215:     } else {
1.995     raeburn  4216:         $fname="$subdir/$fname";
                   4217:     }
1.1090    raeburn  4218:     if ($context eq 'coursedoc') {
1.638     albertel 4219: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4220: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4221:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4222:             return &finishuserfileupload($docuname,$docudom,
                   4223: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4224: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4225:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4226:         } else {
1.1172.2.21  raeburn  4227:             if ($env{'form.folder'}) {
                   4228:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4229:             }
1.638     albertel 4230:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4231: 				       $fname,$formname,$parser,
1.1095    raeburn  4232: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4233:         }
1.719     banghart 4234:     } elsif (defined($destuname)) {
                   4235:         my $docuname=$destuname;
                   4236:         my $docudom=$destudom;
1.860     raeburn  4237: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4238: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4239:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4240:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4241:     } else {
1.638     albertel 4242:         my $docuname=$env{'user.name'};
                   4243:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  4244:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4245:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4246:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4247:         }
1.860     raeburn  4248: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4249: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4250:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4251:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4252:     }
1.271     www      4253: }
                   4254: 
                   4255: sub finishuserfileupload {
1.860     raeburn  4256:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4257:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4258:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4259:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4260:   
1.860     raeburn  4261:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4262:     $file=$fname;
                   4263:     if ($fname=~m|/|) {
                   4264:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4265: 	$path.=$fnamepath.'/';
                   4266:     }
1.259     www      4267:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4268:     my $count;
                   4269:     for ($count=4;$count<=$#parts;$count++) {
                   4270:         $filepath.="/$parts[$count]";
                   4271:         if ((-e $filepath)!=1) {
                   4272: 	    mkdir($filepath,0777);
                   4273:         }
                   4274:     }
1.984     neumanie 4275: 
1.258     www      4276: # Save the file
                   4277:     {
1.1172.2.96  raeburn  4278: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4279: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4280: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4281: 	    return '/adm/notfound.html';
                   4282: 	}
1.1090    raeburn  4283:         if ($context eq 'overwrite') {
1.1117    foxr     4284:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4285:             my $target = $filepath.'/'.$file;
                   4286:             if (-e $source) {
                   4287:                 my @info = stat($source);
                   4288:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4289:                     unless (&File::Copy::move($source,$target)) {
                   4290:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4291:                         return "Moving from $source failed";
                   4292:                     }
                   4293:                 } else {
                   4294:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4295:                 }
                   4296:             } else {
                   4297:                 return "Temporary file: $source missing";
                   4298:             }
                   4299:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4300: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4301: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4302: 	    return '/adm/notfound.html';
                   4303: 	}
1.570     albertel 4304: 	close(FH);
1.1051    raeburn  4305:         if ($resizewidth && $resizeheight) {
                   4306:             my $mm = new File::MMagic;
                   4307:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4308:             if ($mime_type =~ m{^image/}) {
                   4309: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4310:             }  
1.977     amueller 4311: 	}
1.258     www      4312:     }
1.1152    raeburn  4313:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4314:         if (ref($mimetype)) {
                   4315:             if ($$mimetype eq '') {
                   4316:                 my $mm = new File::MMagic;
                   4317:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4318:                 $$mimetype = $type;
                   4319:             }
                   4320:         }
                   4321:     }
1.1172.2.109  raeburn  4322:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4323:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4324:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4325:                                                        $allfiles,$codebase);
                   4326:             unless ($parse_result eq 'ok') {
                   4327:                 &logthis('Failed to parse '.$filepath.$file.
                   4328: 	   	         ' for embedded media: '.$parse_result); 
                   4329:             }
1.637     raeburn  4330:         }
1.1172.2.109  raeburn  4331:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4332:         my $format = $env{'form.scantron_format'};
                   4333:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4334:     }
1.860     raeburn  4335:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4336:         my $input = $filepath.'/'.$file;
                   4337:         my $output = $filepath.'/'.'tn-'.$file;
1.1172.2.146.  .13(raeb 4338:-23):         my $makethumb;
1.860     raeburn  4339:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.146.  .13(raeb 4340:-23):         if ($context eq 'toollogo') {
                   4341:-23):             my ($fullwidth,$fullheight) = &check_dimensions($input);
                   4342:-23):             if ($fullwidth ne '' && $fullheight ne '') {
                   4343:-23):                 if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
                   4344:-23):                     $makethumb = 1;
                   4345:-23):                 }
                   4346:-23):             }
                   4347:-23):         } else {
                   4348:-23):             $makethumb = 1;
                   4349:-23):         }
                   4350:-23):         if ($makethumb) {
                   4351:-23):             my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4352:-23):             system({$args[0]} @args);
                   4353:-23):             if (-e $filepath.'/'.'tn-'.$file) {
                   4354:-23):                 $fetchthumb  = 1;
                   4355:-23):             }
1.860     raeburn  4356:         }
                   4357:     }
1.858     raeburn  4358:  
1.259     www      4359: # Notify homeserver to grep it
                   4360: #
1.984     neumanie 4361:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4362:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4363:     if ($fetchresult eq 'ok') {
1.860     raeburn  4364:         if ($fetchthumb) {
                   4365:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4366:             if ($thumbresult ne 'ok') {
                   4367:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4368:                          $docuhome.': '.$thumbresult);
                   4369:             }
                   4370:         }
1.259     www      4371: #
1.258     www      4372: # Return the URL to it
1.494     albertel 4373:         return '/uploaded/'.$path.$file;
1.263     www      4374:     } else {
1.494     albertel 4375:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4376: 		 ': '.$fetchresult);
1.263     www      4377:         return '/adm/notfound.html';
1.858     raeburn  4378:     }
1.493     albertel 4379: }
                   4380: 
1.637     raeburn  4381: sub extract_embedded_items {
1.961     raeburn  4382:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4383:     my @state = ();
1.1164    raeburn  4384:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4385:     my %javafiles = (
                   4386:                       codebase => '',
                   4387:                       code => '',
                   4388:                       archive => ''
                   4389:                     );
                   4390:     my %mediafiles = (
                   4391:                       src => '',
                   4392:                       movie => '',
                   4393:                      );
1.648     raeburn  4394:     my $p;
                   4395:     if ($content) {
                   4396:         $p = HTML::LCParser->new($content);
                   4397:     } else {
1.961     raeburn  4398:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4399:     }
1.641     albertel 4400:     while (my $t=$p->get_token()) {
1.640     albertel 4401: 	if ($t->[0] eq 'S') {
                   4402: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4403: 	    push(@state, $tagname);
1.648     raeburn  4404:             if (lc($tagname) eq 'allow') {
                   4405:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4406:             }
1.640     albertel 4407: 	    if (lc($tagname) eq 'img') {
                   4408: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4409: 	    }
1.886     albertel 4410: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4411:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4412: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4413:                 }
1.886     albertel 4414: 	    }
1.645     raeburn  4415:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4416:                 my $src;
1.645     raeburn  4417:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4418:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4419:                 } else {
1.1164    raeburn  4420:                     if ($attr->{'src'} ne '') {
                   4421:                         $src = $attr->{'src'};
                   4422:                         &add_filetype($allfiles,$src,'src');
                   4423:                     }
                   4424:                 }
                   4425:                 my $text = $p->get_trimmed_text();
                   4426:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4427:                     my @swfargs = split(/,/,$1);
                   4428:                     foreach my $item (@swfargs) {
                   4429:                         $item =~ s/["']//g;
                   4430:                         $item =~ s/^\s+//;
                   4431:                         $item =~ s/\s+$//;
                   4432:                     }
                   4433:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4434:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4435:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4436:                         } else {
                   4437:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4438:                         }
                   4439:                     }
1.645     raeburn  4440:                 }
                   4441:             }
                   4442:             if (lc($tagname) eq 'link') {
                   4443:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4444:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4445:                 }
                   4446:             }
1.640     albertel 4447: 	    if (lc($tagname) eq 'object' ||
                   4448: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4449: 		foreach my $item (keys(%javafiles)) {
                   4450: 		    $javafiles{$item} = '';
                   4451: 		}
1.1164    raeburn  4452:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4453:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4454:                 }
1.640     albertel 4455: 	    }
                   4456: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4457: 		my $name = lc($attr->{'name'});
                   4458: 		foreach my $item (keys(%javafiles)) {
                   4459: 		    if ($name eq $item) {
                   4460: 			$javafiles{$item} = $attr->{'value'};
                   4461: 			last;
                   4462: 		    }
                   4463: 		}
1.1164    raeburn  4464:                 my $pathfrom;
1.640     albertel 4465: 		foreach my $item (keys(%mediafiles)) {
                   4466: 		    if ($name eq $item) {
1.1164    raeburn  4467:                         $pathfrom = $attr->{'value'};
                   4468:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4469: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4470: 			last;
                   4471: 		    }
                   4472: 		}
1.1164    raeburn  4473:                 if ($name eq 'flashvars') {
                   4474:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4475:                 }
                   4476:                 if ($pathfrom ne '') {
                   4477:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4478:                                          $pathfrom);
                   4479:                 }
1.640     albertel 4480: 	    }
                   4481: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4482: 		foreach my $item (keys(%javafiles)) {
                   4483: 		    if ($attr->{$item}) {
                   4484: 			$javafiles{$item} = $attr->{$item};
                   4485: 			last;
                   4486: 		    }
                   4487: 		}
                   4488: 		foreach my $item (keys(%mediafiles)) {
                   4489: 		    if ($attr->{$item}) {
                   4490: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4491: 			last;
                   4492: 		    }
                   4493: 		}
1.1164    raeburn  4494:                 if (lc($tagname) eq 'embed') {
                   4495:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4496:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4497:                                              $attr->{'src'});
                   4498:                     }
                   4499:                 }
1.640     albertel 4500: 	    }
1.1172.2.35  raeburn  4501:             if (lc($tagname) eq 'iframe') {
                   4502:                 my $src = $attr->{'src'} ;
                   4503:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4504:                     &add_filetype($allfiles,$src,'src');
                   4505:                 } elsif ($src =~ m{^/}) {
                   4506:                     if ($env{'request.course.id'}) {
                   4507:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4508:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4509:                         my $url = &hreflocation('',$fullpath);
                   4510:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4511:                             my $relpath = $1;
                   4512:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4513:                                 &add_filetype($allfiles,$1,'src');
                   4514:                             }
                   4515:                         }
                   4516:                     }
                   4517:                 }
                   4518:             }
1.1164    raeburn  4519:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4520:                 pop(@state);
1.1164    raeburn  4521:             }
1.640     albertel 4522: 	} elsif ($t->[0] eq 'E') {
                   4523: 	    my ($tagname) = ($t->[1]);
                   4524: 	    if ($javafiles{'codebase'} ne '') {
                   4525: 		$javafiles{'codebase'} .= '/';
                   4526: 	    }  
                   4527: 	    if (lc($tagname) eq 'applet' ||
                   4528: 		lc($tagname) eq 'object' ||
                   4529: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4530: 		) {
                   4531: 		foreach my $item (keys(%javafiles)) {
                   4532: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4533: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4534: 			&add_filetype($allfiles,$file,$item);
                   4535: 		    }
                   4536: 		}
                   4537: 	    } 
                   4538: 	    pop @state;
                   4539: 	}
                   4540:     }
1.1164    raeburn  4541:     foreach my $id (sort(keys(%flashvars))) {
                   4542:         if ($shockwave{$id} ne '') {
                   4543:             my @pairs = split(/\&/,$flashvars{$id});
                   4544:             foreach my $pair (@pairs) {
                   4545:                 my ($key,$value) = split(/\=/,$pair);
                   4546:                 if ($key eq 'thumb') {
                   4547:                     &add_filetype($allfiles,$value,$key);
                   4548:                 } elsif ($key eq 'content') {
                   4549:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4550:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4551:                     if ($ext ne '') {
                   4552:                         &add_filetype($allfiles,$path.$value,$ext);
                   4553:                     }
                   4554:                 }
                   4555:             }
                   4556:         }
                   4557:     }
1.637     raeburn  4558:     return 'ok';
                   4559: }
                   4560: 
1.639     albertel 4561: sub add_filetype {
                   4562:     my ($allfiles,$file,$type)=@_;
                   4563:     if (exists($allfiles->{$file})) {
                   4564: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4565: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4566: 	}
                   4567:     } else {
                   4568: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4569:     }
                   4570: }
                   4571: 
1.1164    raeburn  4572: sub embedded_dependency {
                   4573:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4574:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4575:         if (($identifier ne '') &&
                   4576:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4577:             ($pathfrom ne '')) {
                   4578:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4579:             foreach my $dep (@{$related->{$identifier}}) {
                   4580:                 &add_filetype($allfiles,$path.$dep,'object');
                   4581:             }
                   4582:         }
                   4583:     }
                   4584:     return;
                   4585: }
                   4586: 
1.1172.2.146.  .13(raeb 4587:-23): sub check_dimensions {
                   4588:-23):     my ($inputfile) = @_;
                   4589:-23):     my ($fullwidth,$fullheight);
                   4590:-23):     if (($inputfile =~ m|^[/\w.\-]+$|) && (-e $inputfile)) {
                   4591:-23):         my $mm = new File::MMagic;
                   4592:-23):         my $mime_type = $mm->checktype_filename($inputfile);
                   4593:-23):         if ($mime_type =~ m{^image/}) {
                   4594:-23):             if (open(PIPE,"identify $inputfile 2>&1 |")) {
                   4595:-23):                 my $imageinfo = <PIPE>;
                   4596:-23):                 if (!close(PIPE)) {
                   4597:-23):                     &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
                   4598:-23):                 }
                   4599:-23):                 chomp($imageinfo);
                   4600:-23):                 my ($fullsize) =
                   4601:-23):                     ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
                   4602:-23):                 if ($fullsize) {
                   4603:-23):                     ($fullwidth,$fullheight) = split(/x/,$fullsize);
                   4604:-23):                 }
                   4605:-23):             }
                   4606:-23):         }
                   4607:-23):     }
                   4608:-23):     return ($fullwidth,$fullheight);
                   4609:-23): }
                   4610:-23): 
1.1172.2.109  raeburn  4611: sub bubblesheet_converter {
                   4612:     my ($cdom,$fullpath,$config,$format) = @_;
                   4613:     if ((&domain($cdom) ne '') &&
                   4614:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4615:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4616:         my (%csvcols,%csvoptions);
                   4617:         if (ref($config->{'fields'}) eq 'HASH') {
                   4618:             %csvcols = %{$config->{'fields'}};
                   4619:         }
                   4620:         if (ref($config->{'options'}) eq 'HASH') {
                   4621:             %csvoptions = %{$config->{'options'}};
                   4622:         }
                   4623:         my %csvbynum = reverse(%csvcols);
                   4624:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4625:         if (keys(%scantronconf)) {
                   4626:             my %bynum = (
                   4627:                           $scantronconf{CODEstart} => 'CODEstart',
                   4628:                           $scantronconf{IDstart}   => 'IDstart',
                   4629:                           $scantronconf{PaperID}   => 'PaperID',
                   4630:                           $scantronconf{FirstName} => 'FirstName',
                   4631:                           $scantronconf{LastName}  => 'LastName',
                   4632:                           $scantronconf{Qstart}    => 'Qstart',
                   4633:                         );
                   4634:             my @ordered;
                   4635:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4636:                 push(@ordered,$bynum{$item});
                   4637:             }
                   4638:             my %mapstart = (
                   4639:                               CODEstart => 'CODE',
                   4640:                               IDstart   => 'ID',
                   4641:                               PaperID   => 'PaperID',
                   4642:                               FirstName => 'FirstName',
                   4643:                               LastName  => 'LastName',
                   4644:                               Qstart    => 'FirstQuestion',
                   4645:                            );
                   4646:             my %maplength = (
                   4647:                               CODEstart => 'CODElength',
                   4648:                               IDstart   => 'IDlength',
                   4649:                               PaperID   => 'PaperIDlength',
                   4650:                               FirstName => 'FirstNamelength',
                   4651:                               LastName  => 'LastNamelength',
                   4652:             );
                   4653:             if (open(my $fh,'<',$fullpath)) {
                   4654:                 my $output;
                   4655:                 my %lettdig = &letter_to_digits();
                   4656:                 my %diglett = reverse(%lettdig);
                   4657:                 my $numletts = scalar(keys(%lettdig));
                   4658:                 my $num = 0;
                   4659:                 while (my $line=<$fh>) {
                   4660:                     $num ++;
                   4661:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4662:                     $line =~ s{[\r\n]+$}{};
                   4663:                     my %found;
1.1172.2.143  raeburn  4664:                     my @values = split(/,/,$line,-1);
1.1172.2.109  raeburn  4665:                     my ($qstart,$record);
                   4666:                     for (my $i=0; $i<@values; $i++) {
                   4667:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4668:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4669:                             if ($values[$i] eq '') {
                   4670:                                 $values[$i] = $scantronconf{'Qoff'};
                   4671:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4672:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4673:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4674:                                 }
                   4675:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4676:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4677:                                     $values[$i] = $diglett{$values[$i]};
                   4678:                                 }
                   4679:                             } else {
                   4680:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4681:                                     my $digit;
                   4682:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4683:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4684:                                         if ($values[$i] eq 'J') {
                   4685:                                             $digit += $numletts;
                   4686:                                         }
                   4687:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4688:                                         $digit = $values[$i]-1;
                   4689:                                         if ($values[$i] eq '0') {
                   4690:                                             $digit += $numletts;
                   4691:                                         }
                   4692:                                     }
                   4693:                                     my $qval='';
                   4694:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4695:                                         if ($j == $digit) {
                   4696:                                             $qval .= $scantronconf{'Qon'};
                   4697:                                         } else {
                   4698:                                             $qval .= $scantronconf{'Qoff'};
                   4699:                                         }
                   4700:                                     }
                   4701:                                     $values[$i] = $qval;
                   4702:                                 }
                   4703:                             }
                   4704:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4705:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4706:                             }
                   4707:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4708:                             if ($numblank > 0) {
                   4709:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4710:                             }
                   4711:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4712:                                 $qstart = $i;
                   4713:                                 $found{$csvbynum{$i}} = $values[$i];
                   4714:                             } else {
                   4715:                                 $found{'FirstQuestion'} .= $values[$i];
                   4716:                             }
                   4717:                         } elsif (exists($csvbynum{$i})) {
                   4718:                             if ($csvoptions{'rem'}) {
                   4719:                                 $values[$i] =~ s/^\s+//;
                   4720:                             }
                   4721:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4722:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4723:                                     $values[$i] = '0'.$values[$i];
                   4724:                                 }
                   4725:                             }
                   4726:                             $found{$csvbynum{$i}} = $values[$i];
                   4727:                         }
                   4728:                     }
                   4729:                     foreach my $item (@ordered) {
                   4730:                         my $currlength = 1+length($record);
                   4731:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4732:                         if ($numspaces > 0) {
                   4733:                             $record .= (' ' x $numspaces);
                   4734:                         }
                   4735:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4736:                             unless ($item eq 'Qstart') {
                   4737:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4738:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4739:                                 }
                   4740:                             }
                   4741:                             $record .= $found{$mapstart{$item}};
                   4742:                         }
                   4743:                     }
                   4744:                     $output .= "$record\n";
                   4745:                 }
                   4746:                 close($fh);
                   4747:                 if ($output) {
                   4748:                     if (open(my $fh,'>',$fullpath)) {
                   4749:                         print $fh $output;
                   4750:                         close($fh);
                   4751:                     }
                   4752:                 }
                   4753:             }
                   4754:         }
                   4755:         return;
                   4756:     }
                   4757: }
                   4758: 
                   4759: sub letter_to_digits {
                   4760:     my %lettdig = (
                   4761:                     A => 1,
                   4762:                     B => 2,
                   4763:                     C => 3,
                   4764:                     D => 4,
                   4765:                     E => 5,
                   4766:                     F => 6,
                   4767:                     G => 7,
                   4768:                     H => 8,
                   4769:                     I => 9,
                   4770:                     J => 0,
                   4771:                   );
                   4772:     return %lettdig;
                   4773: }
                   4774: 
                   4775: sub get_scantron_config {
                   4776:     my ($which,$cdom) = @_;
                   4777:     my @lines = &get_scantronformat_file($cdom);
                   4778:     my %config;
                   4779:     #FIXME probably should move to XML it has already gotten a bit much now
                   4780:     foreach my $line (@lines) {
                   4781:         my ($name,$descrip)=split(/:/,$line);
                   4782:         if ($name ne $which ) { next; }
                   4783:         chomp($line);
                   4784:         my @config=split(/:/,$line);
                   4785:         $config{'name'}=$config[0];
                   4786:         $config{'description'}=$config[1];
                   4787:         $config{'CODElocation'}=$config[2];
                   4788:         $config{'CODEstart'}=$config[3];
                   4789:         $config{'CODElength'}=$config[4];
                   4790:         $config{'IDstart'}=$config[5];
                   4791:         $config{'IDlength'}=$config[6];
                   4792:         $config{'Qstart'}=$config[7];
                   4793:         $config{'Qlength'}=$config[8];
                   4794:         $config{'Qoff'}=$config[9];
                   4795:         $config{'Qon'}=$config[10];
                   4796:         $config{'PaperID'}=$config[11];
                   4797:         $config{'PaperIDlength'}=$config[12];
                   4798:         $config{'FirstName'}=$config[13];
                   4799:         $config{'FirstNamelength'}=$config[14];
                   4800:         $config{'LastName'}=$config[15];
                   4801:         $config{'LastNamelength'}=$config[16];
                   4802:         $config{'BubblesPerRow'}=$config[17];
                   4803:         last;
                   4804:     }
                   4805:     return %config;
                   4806: }
                   4807: 
                   4808: sub get_scantronformat_file {
                   4809:     my ($cdom) = @_;
                   4810:     if ($cdom eq '') {
                   4811:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4812:     }
                   4813:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4814:     my $gottab = 0;
                   4815:     my @lines;
                   4816:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4817:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4818:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4819:             if ($formatfile ne '-1') {
                   4820:                 @lines = split("\n",$formatfile,-1);
                   4821:                 $gottab = 1;
                   4822:             }
                   4823:         }
                   4824:     }
                   4825:     if (!$gottab) {
                   4826:         my $confname = $cdom.'-domainconfig';
                   4827:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4828:         my $formatfile = &getfile($default);
                   4829:         if ($formatfile ne '-1') {
                   4830:             @lines = split("\n",$formatfile,-1);
                   4831:             $gottab = 1;
                   4832:         }
                   4833:     }
                   4834:     if (!$gottab) {
                   4835:         my @domains = &current_machine_domains();
                   4836:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4837:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4838:                 @lines = <$fh>;
                   4839:                 close($fh);
                   4840:             }
                   4841:         } else {
                   4842:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4843:                 @lines = <$fh>;
                   4844:                 close($fh);
                   4845:             }
                   4846:         }
1.1172.2.146.  .8(raebu 4847:23):         chomp(@lines);
1.1172.2.109  raeburn  4848:     }
                   4849:     return @lines;
                   4850: }
                   4851: 
1.493     albertel 4852: sub removeuploadedurl {
1.984     neumanie 4853:     my ($url)=@_;	
                   4854:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4855:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4856: }
                   4857: 
                   4858: sub removeuserfile {
                   4859:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4860:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4861:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4862:     if ($result eq 'ok') {	
1.798     raeburn  4863:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4864:             my $metafile = $fname.'.meta';
                   4865:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4866: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4867:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4868:             my $sqlresult = 
1.823     albertel 4869:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4870:                                         'portfolio_metadata',$group,
                   4871:                                         'delete');
1.798     raeburn  4872:         }
                   4873:     }
                   4874:     return $result;
1.257     www      4875: }
1.15      www      4876: 
1.530     albertel 4877: sub mkdiruserfile {
                   4878:     my ($docuname,$docudom,$dir)=@_;
                   4879:     my $home=&homeserver($docuname,$docudom);
                   4880:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4881: }
                   4882: 
1.531     albertel 4883: sub renameuserfile {
                   4884:     my ($docuname,$docudom,$old,$new)=@_;
                   4885:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4886:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4887:                         &escape("$old").':'.&escape("$new"),$home);
                   4888:     if ($result eq 'ok') {
                   4889:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4890:             my $oldmeta = $old.'.meta';
                   4891:             my $newmeta = $new.'.meta';
                   4892:             my $metaresult = 
                   4893:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4894: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4895:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4896:             my $sqlresult = 
1.823     albertel 4897:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4898:                                         'portfolio_metadata',$group,
                   4899:                                         'delete');
1.798     raeburn  4900:         }
                   4901:     }
                   4902:     return $result;
1.531     albertel 4903: }
                   4904: 
1.14      www      4905: # ------------------------------------------------------------------------- Log
                   4906: 
                   4907: sub log {
                   4908:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4909:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4910: }
                   4911: 
                   4912: # ------------------------------------------------------------------ Course Log
1.352     www      4913: #
                   4914: # This routine flushes several buffers of non-mission-critical nature
                   4915: #
1.157     www      4916: 
                   4917: sub flushcourselogs {
1.352     www      4918:     &logthis('Flushing log buffers');
                   4919: #
                   4920: # course logs
                   4921: # This is a log of all transactions in a course, which can be used
                   4922: # for data mining purposes
                   4923: #
                   4924: # It also collects the courseid database, which lists last transaction
                   4925: # times and course titles for all courseids
                   4926: #
                   4927:     my %courseidbuffer=();
1.921     raeburn  4928:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4929:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4930: 		          &escape($courselogs{$crsid}),
                   4931: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4932: 	    delete $courselogs{$crsid};
                   4933:         } else {
                   4934:             &logthis('Failed to flush log buffer for '.$crsid);
                   4935:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4936:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4937:                         " exceeded maximum size, deleting.</font>");
                   4938:                delete $courselogs{$crsid};
                   4939:             }
1.352     www      4940:         }
1.920     raeburn  4941:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4942:             'description' => $coursedescrbuf{$crsid},
                   4943:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4944:             'type'        => $coursetypebuf{$crsid},
                   4945:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4946:         };
1.191     harris41 4947:     }
1.352     www      4948: #
                   4949: # Write course id database (reverse lookup) to homeserver of courses 
                   4950: # Is used in pickcourse
                   4951: #
1.840     albertel 4952:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4953:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4954:                                     $courseidbuffer{$crs_home},
                   4955:                                     $crs_home,'timeonly');
1.352     www      4956:     }
                   4957: #
                   4958: # File accesses
                   4959: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4960: #
1.449     matthew  4961:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4962:         if ($entry =~ /___count$/) {
                   4963:             my ($dom,$name);
1.807     albertel 4964:             ($dom,$name,undef)=
1.811     albertel 4965: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4966:             if (! defined($dom) || $dom eq '' || 
                   4967:                 ! defined($name) || $name eq '') {
1.620     albertel 4968:                 my $cid = $env{'request.course.id'};
1.1172.2.142  raeburn  4969: #
                   4970: # FIXME 11/29/2021
                   4971: # Typo in rev. 1.458 (2003/12/09)??
                   4972: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
                   4973: #
1.1172.2.146.  .13(raeb 4974:-23): # While these remain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
1.1172.2.142  raeburn  4975: # $dom and $name will always be null, so the &inc() call will default to storing this data
                   4976: # in a nohist_accesscount.db file for the user rather than the course.
                   4977: #
                   4978: # That said there is a lot of noise in the data being stored.
                   4979: # So counts for prtspool/  and adm/ etc. are recorded.
                   4980: #
                   4981: # A review of which items ending '___count' are written to %accesshash should likely be
                   4982: # made before deciding whether to set these to 'course.' instead of 'request.'
                   4983: #
                   4984: # Under the current scheme each user receives a nohist_accesscount.db file listing
                   4985: # accesses for things which are not published resources, regardless of course, and
                   4986: # there is not a nohist_accesscount.db file in a course, which might log accesses from
                   4987: # anyone in the course for things which are not published resources.
                   4988: #
                   4989: # For an author, nohist_accesscount.db ends up having records for other items
                   4990: # mixed up with the legitimate access counts for the author's published resources.
                   4991: #
1.620     albertel 4992:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4993:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4994:             }
1.450     matthew  4995:             my $value = $accesshash{$entry};
                   4996:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4997:             my %temphash=($url => $value);
1.449     matthew  4998:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4999:             if ($result eq 'ok') {
                   5000:                 delete $accesshash{$entry};
                   5001:             }
                   5002:         } else {
1.811     albertel 5003:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      5004:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  5005:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  5006:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   5007:                 delete $accesshash{$entry};
                   5008:             }
1.185     www      5009:         }
1.191     harris41 5010:     }
1.352     www      5011: #
                   5012: # Roles
                   5013: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   5014: #
1.800     albertel 5015:     foreach my $entry (keys(%userrolehash)) {
1.351     www      5016:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      5017: 	    split(/\:/,$entry);
                   5018:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      5019:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      5020:                 $rudom,$runame) eq 'ok') {
                   5021: 	    delete $userrolehash{$entry};
                   5022:         }
                   5023:     }
1.662     raeburn  5024: #
1.1172.2.90  raeburn  5025: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  5026: #
                   5027:     my %domrolebuffer = ();
1.1000    raeburn  5028:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 5029:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  5030:         if ($domrolebuffer{$rudom}) {
                   5031:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   5032:                       '='.&escape($domainrolehash{$entry});
                   5033:         } else {
                   5034:             $domrolebuffer{$rudom}.=&escape($entry).
                   5035:                       '='.&escape($domainrolehash{$entry});
                   5036:         }
                   5037:         delete $domainrolehash{$entry};
                   5038:     }
                   5039:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  5040:         my %servers;
                   5041:         if (defined(&domain($dom,'primary'))) {
                   5042:             my $primary=&domain($dom,'primary');
                   5043:             my $hostname=&hostname($primary);
                   5044:             $servers{$primary} = $hostname;
                   5045:         } else {
                   5046:             %servers = &get_servers($dom,'library');
                   5047:         }
1.841     albertel 5048: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  5049: 	    if (&reply('domroleput:'.$dom.':'.
                   5050: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   5051: 	        last;
                   5052: 	    } else {
1.841     albertel 5053: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   5054: 	    }
1.662     raeburn  5055:         }
                   5056:     }
1.186     www      5057:     $dumpcount++;
1.157     www      5058: }
                   5059: 
                   5060: sub courselog {
                   5061:     my $what=shift;
1.158     www      5062:     $what=time.':'.$what;
1.620     albertel 5063:     unless ($env{'request.course.id'}) { return ''; }
                   5064:     $coursedombuf{$env{'request.course.id'}}=
                   5065:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5066:     $coursenumbuf{$env{'request.course.id'}}=
                   5067:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   5068:     $coursehombuf{$env{'request.course.id'}}=
                   5069:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   5070:     $coursedescrbuf{$env{'request.course.id'}}=
                   5071:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   5072:     $courseinstcodebuf{$env{'request.course.id'}}=
                   5073:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   5074:     $courseownerbuf{$env{'request.course.id'}}=
                   5075:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  5076:     $coursetypebuf{$env{'request.course.id'}}=
                   5077:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 5078:     if (defined $courselogs{$env{'request.course.id'}}) {
                   5079: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      5080:     } else {
1.620     albertel 5081: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      5082:     }
1.620     albertel 5083:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      5084: 	&flushcourselogs();
                   5085:     }
1.158     www      5086: }
                   5087: 
                   5088: sub courseacclog {
                   5089:     my $fnsymb=shift;
1.620     albertel 5090:     unless ($env{'request.course.id'}) { return ''; }
                   5091:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      5092:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      5093:         $what.=':POST';
1.583     matthew  5094:         # FIXME: Probably ought to escape things....
1.800     albertel 5095: 	foreach my $key (keys(%env)) {
                   5096:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  5097:                 my $formitem = $1;
                   5098:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   5099:                     $what.=':'.$formitem.'='.$env{$key};
                   5100:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131  raeburn  5101:                     if ($formitem eq 'proctorpassword') {
1.1172.2.132  raeburn  5102:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131  raeburn  5103:                     } else {
                   5104:                         $what.=':'.$formitem.'='.$env{$key};
                   5105:                     }
1.975     raeburn  5106:                 }
1.158     www      5107:             }
1.191     harris41 5108:         }
1.583     matthew  5109:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   5110:         # FIXME: We should not be depending on a form parameter that someone
                   5111:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 5112:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  5113:             $what.= ':POST';
                   5114:             # FIXME: Probably ought to escape things....
                   5115:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   5116:                                  'crsdiscuss') {
1.620     albertel 5117:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  5118:             }
                   5119:         }
1.158     www      5120:     }
                   5121:     &courselog($what);
1.149     www      5122: }
                   5123: 
1.185     www      5124: sub countacc {
                   5125:     my $url=&declutter(shift);
1.458     matthew  5126:     return if (! defined($url) || $url eq '');
1.620     albertel 5127:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      5128: #
                   5129: # Mark that this url was used in this course
                   5130: #
1.620     albertel 5131:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      5132: #
                   5133: # Increase the access count for this resource in this child process
                   5134: #
1.281     www      5135:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  5136:     $accesshash{$key}++;
1.185     www      5137: }
1.349     www      5138: 
1.361     www      5139: sub linklog {
                   5140:     my ($from,$to)=@_;
                   5141:     $from=&declutter($from);
                   5142:     $to=&declutter($to);
                   5143:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   5144:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   5145: }
1.1160    www      5146: 
                   5147: sub statslog {
                   5148:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   5149:     if ($users<2) { return; }
                   5150:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   5151:             'course'       => $env{'request.course.id'},
                   5152:             'sections'     => '"all"',
                   5153:             'num_students' => $users,
                   5154:             'part'         => $part,
                   5155:             'symb'         => $symb,
                   5156:             'mean_tries'   => $av_attempts,
                   5157:             'deg_of_diff'  => $degdiff});
                   5158:     foreach my $key (keys(%dynstore)) {
                   5159:         $accesshash{$key}=$dynstore{$key};
                   5160:     }
                   5161: }
1.361     www      5162:   
1.349     www      5163: sub userrolelog {
                   5164:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 5165:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      5166:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5167:        $userrolehash
                   5168:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      5169:                     =$tend.':'.$tstart;
1.662     raeburn  5170:     }
1.1169    droeschl 5171:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 5172:        $userrolehash
                   5173:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   5174:                     =$tend.':'.$tstart;
                   5175:     }
1.1172.2.90  raeburn  5176:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  5177:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5178:        $domainrolehash
                   5179:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   5180:                     = $tend.':'.$tstart;
                   5181:     }
1.351     www      5182: }
                   5183: 
1.957     raeburn  5184: sub courserolelog {
                   5185:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  5186:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   5187:         my $cdom = $1;
                   5188:         my $cnum = $2;
                   5189:         my $sec = $3;
                   5190:         my $namespace = 'rolelog';
                   5191:         my %storehash = (
                   5192:                            role    => $trole,
                   5193:                            start   => $tstart,
                   5194:                            end     => $tend,
                   5195:                            selfenroll => $selfenroll,
                   5196:                            context    => $context,
                   5197:                         );
                   5198:         if ($trole eq 'gr') {
                   5199:             $namespace = 'groupslog';
                   5200:             $storehash{'group'} = $sec;
                   5201:         } else {
                   5202:             $storehash{'section'} = $sec;
1.1172.2.146.  .16(raeb 5203:-23):             my ($curruserdomstr,$newuserdomstr);
                   5204:-23):             if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'})) {
                   5205:-23):                 $curruserdomstr = $env{'course.'.$env{'request.course.id'}.'.internal.userdomains'};
                   5206:-23):             } else {
                   5207:-23):                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
                   5208:-23):                 $curruserdomstr = $courseinfo{'internal.userdomains'};
                   5209:-23):             }
                   5210:-23):             if ($curruserdomstr ne '') {
                   5211:-23):                 my @udoms = split(/,/,$curruserdomstr);
                   5212:-23):                 unless (grep(/^\Q$domain\E/,@udoms)) {
                   5213:-23):                     push(@udoms,$domain);
                   5214:-23):                     $newuserdomstr = join(',',sort(@udoms));
                   5215:-23):                 }
                   5216:-23):             } else {
                   5217:-23):                 $newuserdomstr = $domain;
                   5218:-23):             }
                   5219:-23):             if ($newuserdomstr ne '') {
                   5220:-23):                 my $putresult = &put('environment',{ 'internal.userdomains' => $newuserdomstr },
                   5221:-23):                                      $cdom,$cnum);
                   5222:-23):                 if ($putresult eq 'ok') {
                   5223:-23):                     unless (($selfenroll) || ($context eq 'selfenroll')) {
                   5224:-23):                         if (($context eq 'createcourse') || ($context eq 'requestcourses') ||
                   5225:-23):                             ($context eq 'automated') || ($context eq 'domain')) {
                   5226:-23):                             $env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'} = $newuserdomstr;
                   5227:-23):                         } elsif ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   5228:-23):                             &appenv({'course.'.$cdom.'_'.$cnum.'.internal.userdomains' => $newuserdomstr});
                   5229:-23):                         }
                   5230:-23):                     }
                   5231:-23):                 }
                   5232:-23):             }
1.1172.2.9  raeburn  5233:         }
                   5234:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   5235:                    $domain,$cnum,$cdom);
                   5236:         if (($trole ne 'st') || ($sec ne '')) {
                   5237:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  5238:         }
                   5239:     }
                   5240:     return;
                   5241: }
                   5242: 
1.1172.2.9  raeburn  5243: sub domainrolelog {
                   5244:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5245:     if ($area =~ m{^/($match_domain)/$}) {
                   5246:         my $cdom = $1;
                   5247:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   5248:         my $namespace = 'rolelog';
                   5249:         my %storehash = (
                   5250:                            role    => $trole,
                   5251:                            start   => $tstart,
                   5252:                            end     => $tend,
                   5253:                            context => $context,
                   5254:                         );
                   5255:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5256:                    $domain,$domconfiguser,$cdom);
                   5257:     }
                   5258:     return;
                   5259: 
                   5260: }
                   5261: 
                   5262: sub coauthorrolelog {
                   5263:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5264:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5265:         my $audom = $1;
                   5266:         my $auname = $2;
                   5267:         my $namespace = 'rolelog';
                   5268:         my %storehash = (
                   5269:                            role    => $trole,
                   5270:                            start   => $tstart,
                   5271:                            end     => $tend,
                   5272:                            context => $context,
                   5273:                         );
                   5274:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5275:                    $domain,$auname,$audom);
                   5276:     }
                   5277:     return;
                   5278: }
                   5279: 
1.351     www      5280: sub get_course_adv_roles {
1.948     raeburn  5281:     my ($cid,$codes) = @_;
1.620     albertel 5282:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5283:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5284:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5285:     my %nothide=();
1.800     albertel 5286:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5287:         if ($user !~ /:/) {
                   5288: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5289:         } else {
                   5290:             $nothide{$user}=1;
                   5291:         }
1.470     www      5292:     }
1.1172.2.23  raeburn  5293:     my @possdoms = ($coursehash{'domain'});
                   5294:     if ($coursehash{'checkforpriv'}) {
                   5295:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5296:     }
1.351     www      5297:     my %returnhash=();
                   5298:     my %dumphash=
                   5299:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5300:     my $now=time;
1.997     raeburn  5301:     my %privileged;
1.1000    raeburn  5302:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5303: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5304:         if (($tstart) && ($tstart<0)) { next; }
                   5305:         if (($tend) && ($tend<$now)) { next; }
                   5306:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5307:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5308: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  5309:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5310:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5311: 	if ($role eq 'cr') { next; }
1.948     raeburn  5312:         if ($codes) {
                   5313:             if ($section) { $role .= ':'.$section; }
                   5314:             if ($returnhash{$role}) {
                   5315:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5316:             } else {
                   5317:                 $returnhash{$role}=$username.':'.$domain;
                   5318:             }
1.351     www      5319:         } else {
1.988     raeburn  5320:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5321:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5322:             if ($returnhash{$key}) {
                   5323: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5324:             } else {
                   5325:                 $returnhash{$key}=$username.':'.$domain;
                   5326:             }
1.351     www      5327:         }
1.948     raeburn  5328:     }
1.400     www      5329:     return %returnhash;
                   5330: }
                   5331: 
                   5332: sub get_my_roles {
1.937     raeburn  5333:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5334:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5335:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5336:     my (%dumphash,%nothide);
1.1086    raeburn  5337:     if ($context eq 'userroles') {
1.1166    raeburn  5338:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5339:     } else {
1.1172.2.23  raeburn  5340:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5341:         if ($hidepriv) {
                   5342:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5343:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5344:                 if ($user !~ /:/) {
                   5345:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5346:                 } else {
                   5347:                     $nothide{$user} = 1;
                   5348:                 }
                   5349:             }
                   5350:         }
1.858     raeburn  5351:     }
1.400     www      5352:     my %returnhash=();
                   5353:     my $now=time;
1.999     raeburn  5354:     my %privileged;
1.800     albertel 5355:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5356:         my ($role,$tend,$tstart);
                   5357:         if ($context eq 'userroles') {
1.1149    raeburn  5358:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5359: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5360:         } else {
                   5361:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5362:         }
1.400     www      5363:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5364:         my $status = 'active';
1.939     raeburn  5365:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5366:             $status = 'previous';
                   5367:         } 
                   5368:         if (($tstart) && ($now<$tstart)) {
                   5369:             $status = 'future';
                   5370:         }
                   5371:         if (ref($types) eq 'ARRAY') {
                   5372:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5373:                 next;
                   5374:             } 
                   5375:         } else {
                   5376:             if ($status ne 'active') {
                   5377:                 next;
                   5378:             }
                   5379:         }
1.867     raeburn  5380:         my ($rolecode,$username,$domain,$section,$area);
                   5381:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  5382:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5383:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5384:         } else {
                   5385:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5386:         }
1.832     raeburn  5387:         if (ref($roledoms) eq 'ARRAY') {
                   5388:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5389:                 next;
                   5390:             }
                   5391:         }
                   5392:         if (ref($roles) eq 'ARRAY') {
                   5393:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5394:                 if ($role =~ /^cr\//) {
                   5395:                     if (!grep(/^cr$/,@{$roles})) {
                   5396:                         next;
                   5397:                     }
1.1104    raeburn  5398:                 } elsif ($role =~ /^gr\//) {
                   5399:                     if (!grep(/^gr$/,@{$roles})) {
                   5400:                         next;
                   5401:                     }
1.922     raeburn  5402:                 } else {
                   5403:                     next;
                   5404:                 }
1.832     raeburn  5405:             }
1.867     raeburn  5406:         }
1.937     raeburn  5407:         if ($hidepriv) {
1.1172.2.23  raeburn  5408:             my @privroles = ('dc','su');
1.999     raeburn  5409:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  5410:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5411:             } else {
1.1172.2.23  raeburn  5412:                 my $possdoms = [$domain];
                   5413:                 if (ref($roledoms) eq 'ARRAY') {
                   5414:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5415:                 }
1.1172.2.23  raeburn  5416:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5417:                     if (!$nothide{$username.':'.$domain}) {
                   5418:                         next;
                   5419:                     }
                   5420:                 }
1.937     raeburn  5421:             }
                   5422:         }
1.933     raeburn  5423:         if ($withsec) {
                   5424:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5425:                 $tstart.':'.$tend;
                   5426:         } else {
                   5427:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5428:         }
1.832     raeburn  5429:     }
1.373     www      5430:     return %returnhash;
1.399     www      5431: }
                   5432: 
1.1172.2.89  raeburn  5433: sub get_all_adhocroles {
                   5434:     my ($dom) = @_;
                   5435:     my @roles_by_num = ();
                   5436:     my %domdefaults = &get_domain_defaults($dom);
                   5437:     my (%description,%access_in_dom,%access_info);
                   5438:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5439:         my $count = 0;
                   5440:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5441:         my %ordered;
                   5442:         foreach my $role (sort(keys(%domcurrent))) {
                   5443:             my ($order,$desc,$access_in_dom);
                   5444:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5445:                 $order = $domcurrent{$role}{'order'};
                   5446:                 $desc = $domcurrent{$role}{'desc'};
                   5447:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5448:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5449:             }
                   5450:             if ($order eq '') {
                   5451:                 $order = $count;
                   5452:             }
                   5453:             $ordered{$order} = $role;
                   5454:             if ($desc ne '') {
                   5455:                 $description{$role} = $desc;
                   5456:             } else {
                   5457:                 $description{$role}= $role;
                   5458:             }
                   5459:             $count++;
                   5460:         }
                   5461:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5462:             push(@roles_by_num,$ordered{$item});
                   5463:         }
                   5464:     }
                   5465:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5466: }
                   5467: 
                   5468: sub get_my_adhocroles {
                   5469:     my ($cid,$checkreg) = @_;
                   5470:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5471:     if ($env{'request.course.id'} eq $cid) {
                   5472:         $cdom = $env{'course.'.$cid.'.domain'};
                   5473:         $cnum = $env{'course.'.$cid.'.num'};
                   5474:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5475:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5476:         $cdom = $1;
                   5477:         $cnum = $2;
                   5478:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5479:                                      $cdom,$cnum);
                   5480:     }
                   5481:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5482:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5483:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5484:         if ($rosterhash{$user} ne '') {
                   5485:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5486:             return ([],{}) if ($type eq 'auto');
                   5487:         }
                   5488:     }
                   5489:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5490:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5491:             my $then=$env{'user.login.time'};
                   5492:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5493:             if (!$update) {
                   5494:                 $update = $then;
                   5495:             }
                   5496:             my @liveroles;
                   5497:             foreach my $role ('dh','da') {
                   5498:                 if ($env{"user.role.$role./$cdom/"}) {
                   5499:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5500:                     my $limit = $update;
                   5501:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5502:                         $limit = $then;
                   5503:                     }
                   5504:                     my $activerole = 1;
                   5505:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5506:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5507:                     if ($activerole) {
                   5508:                         push(@liveroles,$role);
                   5509:                     }
                   5510:                 }
                   5511:             }
                   5512:             if (@liveroles) {
1.1172.2.89  raeburn  5513:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5514:                     my ($accessref,$accessinfo,%access_in_dom);
                   5515:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5516:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5517:                         if (@{$roles_by_num}) {
                   5518:                             my %settings;
                   5519:                             if ($env{'request.course.id'} eq $cid) {
                   5520:                                 foreach my $envkey (keys(%env)) {
                   5521:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5522:                                         $settings{$1} = $env{$envkey};
                   5523:                                     }
                   5524:                                 }
                   5525:                             } else {
                   5526:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5527:                             }
                   5528:                             my %setincrs;
                   5529:                             if ($settings{'internal.adhocaccess'}) {
                   5530:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5531:                             }
                   5532:                             my @statuses;
                   5533:                             if ($env{'environment.inststatus'}) {
                   5534:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5535:                             }
                   5536:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5537:                             if (ref($accessref) eq 'HASH') {
                   5538:                                 %access_in_dom = %{$accessref};
                   5539:                             }
                   5540:                             foreach my $role (@{$roles_by_num}) {
                   5541:                                 my ($curraccess,@okstatus,@personnel);
                   5542:                                 if ($setincrs{$role}) {
                   5543:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5544:                                     if ($curraccess eq 'status') {
                   5545:                                         @okstatus = split(/\&/,$rest);
                   5546:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5547:                                         @personnel = split(/\&/,$rest);
                   5548:                                     }
                   5549:                                 } else {
                   5550:                                     $curraccess = $access_in_dom{$role};
                   5551:                                     if (ref($accessinfo) eq 'HASH') {
                   5552:                                         if ($curraccess eq 'status') {
                   5553:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5554:                                                 @okstatus = @{$accessinfo->{$role}};
                   5555:                                             }
                   5556:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5557:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5558:                                                 @personnel = @{$accessinfo->{$role}};
                   5559:                                             }
                   5560:                                         }
                   5561:                                     }
                   5562:                                 }
                   5563:                                 if ($curraccess eq 'none') {
                   5564:                                     next;
                   5565:                                 } elsif ($curraccess eq 'all') {
                   5566:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5567:                                 } elsif ($curraccess eq 'dh') {
                   5568:                                     if (grep(/^dh$/,@liveroles)) {
                   5569:                                         push(@possroles,$role);
                   5570:                                     } else {
                   5571:                                         next;
                   5572:                                     }
                   5573:                                 } elsif ($curraccess eq 'da') {
                   5574:                                     if (grep(/^da$/,@liveroles)) {
                   5575:                                         push(@possroles,$role);
                   5576:                                     } else {
                   5577:                                         next;
                   5578:                                     }
1.1172.2.89  raeburn  5579:                                 } elsif ($curraccess eq 'status') {
                   5580:                                     if (@okstatus) {
                   5581:                                         if (!@statuses) {
                   5582:                                             if (grep(/^default$/,@okstatus)) {
                   5583:                                                 push(@possroles,$role);
                   5584:                                             }
                   5585:                                         } else {
                   5586:                                             foreach my $status (@okstatus) {
                   5587:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5588:                                                     push(@possroles,$role);
                   5589:                                                     last;
                   5590:                                                 }
                   5591:                                             }
                   5592:                                         }
                   5593:                                     }
                   5594:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5595:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5596:                                         if ($curraccess eq 'exc') {
                   5597:                                             push(@possroles,$role);
                   5598:                                         }
                   5599:                                     } elsif ($curraccess eq 'inc') {
                   5600:                                         push(@possroles,$role);
                   5601:                                     }
                   5602:                                 }
                   5603:                             }
                   5604:                         }
                   5605:                     }
                   5606:                 }
                   5607:             }
                   5608:         }
                   5609:     }
                   5610:     unless (ref($description) eq 'HASH') {
                   5611:         if (ref($roles_by_num) eq 'ARRAY') {
                   5612:             my %desc;
                   5613:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5614:             $description = \%desc;
                   5615:         } else {
                   5616:             $description = {};
                   5617:         }
                   5618:     }
                   5619:     return (\@possroles,$description);
                   5620: }
                   5621: 
1.399     www      5622: # ----------------------------------------------------- Frontpage Announcements
                   5623: #
                   5624: #
                   5625: 
                   5626: sub postannounce {
                   5627:     my ($server,$text)=@_;
1.844     albertel 5628:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5629:     unless ($text=~/\w/) { $text=''; }
                   5630:     return &reply('setannounce:'.&escape($text),$server);
                   5631: }
                   5632: 
                   5633: sub getannounce {
1.448     albertel 5634: 
1.1172.2.96  raeburn  5635:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5636: 	my $announcement='';
1.800     albertel 5637: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5638: 	close($fh);
1.399     www      5639: 	if ($announcement=~/\w/) { 
                   5640: 	    return 
                   5641:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5642:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5643: 	} else {
                   5644: 	    return '';
                   5645: 	}
                   5646:     } else {
                   5647: 	return '';
                   5648:     }
1.351     www      5649: }
1.353     www      5650: 
                   5651: # ---------------------------------------------------------- Course ID routines
                   5652: # Deal with domain's nohist_courseid.db files
                   5653: #
                   5654: 
                   5655: sub courseidput {
1.921     raeburn  5656:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5657:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5658:     my $outcome;
                   5659:     if ($caller eq 'timeonly') {
                   5660:         my $cids = '';
                   5661:         foreach my $item (keys(%$storehash)) {
                   5662:             $cids.=&escape($item).'&';
                   5663:         }
                   5664:         $cids=~s/\&$//;
                   5665:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5666:                           $coursehome);       
                   5667:     } else {
                   5668:         my $items = '';
                   5669:         foreach my $item (keys(%$storehash)) {
                   5670:             $items.= &escape($item).'='.
                   5671:                      &freeze_escape($$storehash{$item}).'&';
                   5672:         }
                   5673:         $items=~s/\&$//;
                   5674:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5675:                           $coursehome);
1.918     raeburn  5676:     }
                   5677:     if ($outcome eq 'unknown_cmd') {
                   5678:         my $what;
                   5679:         foreach my $cid (keys(%$storehash)) {
                   5680:             $what .= &escape($cid).'=';
1.921     raeburn  5681:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5682:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5683:             }
                   5684:             $what =~ s/\:$/&/;
                   5685:         }
                   5686:         $what =~ s/\&$//;  
                   5687:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5688:     } else {
                   5689:         return $outcome;
                   5690:     }
1.353     www      5691: }
                   5692: 
                   5693: sub courseiddump {
1.921     raeburn  5694:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5695:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5696:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5697:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5698:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5699:     my $as_hash = 1;
                   5700:     my %returnhash;
                   5701:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5702:     my %libserv = &all_library();
                   5703:     foreach my $tryserver (keys(%libserv)) {
                   5704:         if ( (  $hostidflag == 1 
                   5705: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5706: 	     || (!defined($hostidflag)) ) {
                   5707: 
1.918     raeburn  5708: 	    if (($domfilter eq '') ||
                   5709: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5710:                 my $rep;
                   5711:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5712:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5713:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5714:                                 &escape($descfilter), &escape($instcodefilter),
                   5715:                                 &escape($ownerfilter), &escape($coursefilter),
                   5716:                                 &escape($typefilter), &escape($regexp_ok),
                   5717:                                 $as_hash, &escape($selfenrollonly),
                   5718:                                 &escape($catfilter), $showhidden, $caller,
                   5719:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5720:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5721:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5722:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5723:                 } else {
                   5724:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5725:                              $sincefilter.':'.&escape($descfilter).':'.
                   5726:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5727:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5728:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5729:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5730:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5731:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5732:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5733:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5734:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5735:                 }
                   5736: 
1.918     raeburn  5737:                 my @pairs=split(/\&/,$rep);
                   5738:                 foreach my $item (@pairs) {
                   5739:                     my ($key,$value)=split(/\=/,$item,2);
                   5740:                     $key = &unescape($key);
                   5741:                     next if ($key =~ /^error: 2 /);
                   5742:                     my $result = &thaw_unescape($value);
                   5743:                     if (ref($result) eq 'HASH') {
                   5744:                         $returnhash{$key}=$result;
                   5745:                     } else {
1.921     raeburn  5746:                         my @responses = split(/:/,$value);
                   5747:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5748:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5749:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5750:                         }
1.1008    raeburn  5751:                     }
1.353     www      5752:                 }
                   5753:             }
                   5754:         }
                   5755:     }
                   5756:     return %returnhash;
                   5757: }
                   5758: 
1.1055    raeburn  5759: sub courselastaccess {
                   5760:     my ($cdom,$cnum,$hostidref) = @_;
                   5761:     my %returnhash;
                   5762:     if ($cdom && $cnum) {
                   5763:         my $chome = &homeserver($cnum,$cdom);
                   5764:         if ($chome ne 'no_host') {
                   5765:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5766:             &extract_lastaccess(\%returnhash,$rep);
                   5767:         }
                   5768:     } else {
                   5769:         if (!$cdom) { $cdom=''; }
                   5770:         my %libserv = &all_library();
                   5771:         foreach my $tryserver (keys(%libserv)) {
                   5772:             if (ref($hostidref) eq 'ARRAY') {
                   5773:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5774:             } 
                   5775:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5776:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5777:                 &extract_lastaccess(\%returnhash,$rep);
                   5778:             }
                   5779:         }
                   5780:     }
                   5781:     return %returnhash;
                   5782: }
                   5783: 
                   5784: sub extract_lastaccess {
                   5785:     my ($returnhash,$rep) = @_;
                   5786:     if (ref($returnhash) eq 'HASH') {
                   5787:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5788:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5789:                  $rep eq '') {
                   5790:             my @pairs=split(/\&/,$rep);
                   5791:             foreach my $item (@pairs) {
                   5792:                 my ($key,$value)=split(/\=/,$item,2);
                   5793:                 $key = &unescape($key);
                   5794:                 next if ($key =~ /^error: 2 /);
                   5795:                 $returnhash->{$key} = &thaw_unescape($value);
                   5796:             }
                   5797:         }
                   5798:     }
                   5799:     return;
                   5800: }
                   5801: 
1.658     raeburn  5802: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5803: 
                   5804: sub dcmailput {
1.685     raeburn  5805:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5806:     my $status = &Apache::lonnet::critical(
1.740     www      5807:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5808:        &escape($message),$server);
1.662     raeburn  5809:     return $status;
                   5810: }
                   5811: 
1.658     raeburn  5812: sub dcmaildump {
                   5813:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5814:     my %returnhash=();
1.846     albertel 5815: 
                   5816:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5817:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5818:                                                          &escape($enddate).':';
                   5819: 	my @esc_senders=map { &escape($_)} @$senders;
                   5820: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5821: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5822:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5823:             if (($key) && ($value)) {
                   5824:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5825:             }
                   5826:         }
                   5827:     }
                   5828:     return %returnhash;
                   5829: }
1.662     raeburn  5830: # ---------------------------------------------------------- Domain roles
                   5831: 
                   5832: sub get_domain_roles {
                   5833:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5834:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5835:         $startdate = '.';
                   5836:     }
1.1018    raeburn  5837:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5838:         $enddate = '.';
                   5839:     }
1.922     raeburn  5840:     my $rolelist;
                   5841:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5842:         $rolelist = join('&',@{$roles});
1.922     raeburn  5843:     }
1.662     raeburn  5844:     my %personnel = ();
1.841     albertel 5845: 
                   5846:     my %servers = &get_servers($dom,'library');
                   5847:     foreach my $tryserver (keys(%servers)) {
                   5848: 	%{$personnel{$tryserver}}=();
                   5849: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5850: 					    &escape($startdate).':'.
                   5851: 					    &escape($enddate).':'.
                   5852: 					    &escape($rolelist), $tryserver))) {
                   5853: 	    my ($key,$value) = split(/\=/,$line,2);
                   5854: 	    if (($key) && ($value)) {
                   5855: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5856: 	    }
                   5857: 	}
1.662     raeburn  5858:     }
                   5859:     return %personnel;
                   5860: }
1.658     raeburn  5861: 
1.1172.2.89  raeburn  5862: sub get_active_domroles {
                   5863:     my ($dom,$roles) = @_;
                   5864:     return () unless (ref($roles) eq 'ARRAY');
                   5865:     my $now = time;
                   5866:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5867:     my %domroles;
                   5868:     foreach my $server (keys(%dompersonnel)) {
                   5869:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5870:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5871:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5872:         }
                   5873:     }
                   5874:     return %domroles;
                   5875: }
                   5876: 
1.1057    www      5877: # ----------------------------------------------------------- Interval timing 
1.149     www      5878: 
1.1153    www      5879: {
                   5880: # Caches needed for speedup of navmaps
                   5881: # We don't want to cache this for very long at all (5 seconds at most)
                   5882: # 
                   5883: # The user for whom we cache
                   5884: my $cachedkey='';
                   5885: # The cached times for this user
                   5886: my %cachedtimes=();
                   5887: # When this was last done
1.1172.2.66  raeburn  5888: my $cachedtime='';
1.1153    www      5889: 
                   5890: sub load_all_first_access {
1.1172.2.146.  .1(raebu 5891:22):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5892:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.146.  .1(raebu 5893:22):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5894:22):         (!$ignorecache)) {
1.1154    raeburn  5895:         return;
                   5896:     }
                   5897:     $cachedtime=time;
                   5898:     $cachedkey=$uname.':'.$udom;
                   5899:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5900: }
                   5901: 
1.504     albertel 5902: sub get_first_access {
1.1172.2.146.  .1(raebu 5903:22):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5904:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5905:     if ($argsymb) { $symb=$argsymb; }
                   5906:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5907:     if ($argmap) { $map = $argmap; }
1.926     albertel 5908:     if ($type eq 'course') {
                   5909: 	$res='course';
                   5910:     } elsif ($type eq 'map') {
1.588     albertel 5911: 	$res=&symbread($map);
                   5912:     } else {
                   5913: 	$res=$symb;
                   5914:     }
1.1172.2.146.  .1(raebu 5915:22):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5916:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5917: }
                   5918: 
                   5919: sub set_first_access {
1.1162    raeburn  5920:     my ($type,$interval)=@_;
1.790     albertel 5921:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5922:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5923:     if ($type eq 'course') {
                   5924: 	$res='course';
                   5925:     } elsif ($type eq 'map') {
1.588     albertel 5926: 	$res=&symbread($map);
                   5927:     } else {
                   5928: 	$res=$symb;
                   5929:     }
1.1153    www      5930:     $cachedkey='';
1.1162    raeburn  5931:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5932:     if ($firstaccess) {
                   5933:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5934:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5935:                  "in $courseid");
                   5936:         return 'already_set';
                   5937:     } else {
1.1162    raeburn  5938:         my $start = time;
                   5939: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5940:                           $udom,$uname);
                   5941:         if ($putres eq 'ok') {
                   5942:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5943:                  $udom,$uname); 
                   5944:             &appenv(
                   5945:                      {
                   5946:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5947:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5948:                      }
                   5949:                   );
1.1172.2.97  raeburn  5950:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5951:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5952:             }
1.1172.2.102  raeburn  5953:         } elsif ($putres ne 'refused') {
                   5954:             &logthis("Result: $putres when attempting to set first access time ".
                   5955:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5956:         }
                   5957:         return $putres;
1.505     albertel 5958:     }
                   5959:     return 'already_set';
1.504     albertel 5960: }
1.1153    www      5961: }
1.1172.2.32  raeburn  5962: 
                   5963: sub checkout {
                   5964:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5965:     my $now=time;
                   5966:     my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134  raeburn  5967:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5968:     my $infostr=&escape(
                   5969:                  'CHECKOUTTOKEN&'.
                   5970:                  $tuname.'&'.
                   5971:                  $tudom.'&'.
                   5972:                  $tcrsid.'&'.
                   5973:                  $symb.'&'.
1.1172.2.134  raeburn  5974:                  $now.'&'.$ip);
1.1172.2.32  raeburn  5975:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5976:     if ($token=~/^error\:/) {
                   5977:         &logthis("<font color=\"blue\">WARNING: ".
                   5978:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5979:                  "</font>");
                   5980:         return '';
                   5981:     }
                   5982: 
                   5983:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5984:     $token=~tr/a-z/A-Z/;
                   5985: 
                   5986:     my %infohash=('resource.0.outtoken' => $token,
                   5987:                   'resource.0.checkouttime' => $now,
1.1172.2.134  raeburn  5988:                   'resource.0.outremote' => $ip);
1.1172.2.32  raeburn  5989: 
                   5990:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5991:        return '';
                   5992:     } else {
                   5993:         &logthis("<font color=\"blue\">WARNING: ".
                   5994:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5995:                  "</font>");
                   5996:     }
                   5997: 
                   5998:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5999:                          &escape('Checkout '.$infostr.' - '.
                   6000:                                                  $token)) ne 'ok') {
                   6001:         return '';
                   6002:     } else {
                   6003:         &logthis("<font color=\"blue\">WARNING: ".
                   6004:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   6005:                  "</font>");
                   6006:     }
                   6007:     return $token;
                   6008: }
                   6009: 
                   6010: # ------------------------------------------------------------ Check in an item
                   6011: 
                   6012: sub checkin {
                   6013:     my $token=shift;
                   6014:     my $now=time;
                   6015:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   6016:     $lonhost=~tr/A-Z/a-z/;
                   6017:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   6018:     $dtoken=~s/\W/\_/g;
1.1172.2.134  raeburn  6019:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  6020:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   6021:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   6022: 
                   6023:     unless (($tuname) && ($tudom)) {
                   6024:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   6025:         return '';
                   6026:     }
                   6027: 
                   6028:     unless (&allowed('mgr',$tcrsid)) {
                   6029:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   6030:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   6031:         return '';
                   6032:     }
                   6033: 
                   6034:     my %infohash=('resource.0.intoken' => $token,
                   6035:                   'resource.0.checkintime' => $now,
1.1172.2.134  raeburn  6036:                   'resource.0.inremote' => $ip);
1.1172.2.32  raeburn  6037: 
                   6038:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   6039:        return '';
                   6040:     }
                   6041: 
                   6042:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   6043:                          &escape('Checkin - '.$token)) ne 'ok') {
                   6044:         return '';
                   6045:     }
                   6046: 
                   6047:     return ($symb,$tuname,$tudom,$tcrsid);
                   6048: }
                   6049: 
1.110     www      6050: # --------------------------------------------- Set Expire Date for Spreadsheet
                   6051: 
                   6052: sub expirespread {
                   6053:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 6054:     my $cid=$env{'request.course.id'}; 
1.110     www      6055:     if ($cid) {
                   6056:        my $now=time;
                   6057:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 6058:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   6059:                             $env{'course.'.$cid.'.num'}.
1.110     www      6060: 	        	    ':nohist_expirationdates:'.
                   6061:                             &escape($key).'='.$now,
1.620     albertel 6062:                             $env{'course.'.$cid.'.home'})
1.110     www      6063:     }
                   6064:     return 'ok';
1.14      www      6065: }
                   6066: 
1.109     www      6067: # ----------------------------------------------------- Devalidate Spreadsheets
                   6068: 
                   6069: sub devalidate {
1.325     www      6070:     my ($symb,$uname,$udom)=@_;
1.620     albertel 6071:     my $cid=$env{'request.course.id'}; 
1.109     www      6072:     if ($cid) {
1.391     matthew  6073:         # delete the stored spreadsheets for
                   6074:         # - the student level sheet of this user in course's homespace
                   6075:         # - the assessment level sheet for this resource 
                   6076:         #   for this user in user's homespace
1.553     albertel 6077: 	# - current conditional state info
1.325     www      6078: 	my $key=$uname.':'.$udom.':';
1.109     www      6079:         my $status=
1.299     matthew  6080: 	    &del('nohist_calculatedsheets',
1.391     matthew  6081: 		 [$key.'studentcalc:'],
1.620     albertel 6082: 		 $env{'course.'.$cid.'.domain'},
                   6083: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 6084: 		.' '.
                   6085: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  6086: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      6087:         unless ($status eq 'ok ok') {
                   6088:            &logthis('Could not devalidate spreadsheet '.
1.325     www      6089:                     $uname.' at '.$udom.' for '.
1.109     www      6090: 		    $symb.': '.$status);
1.133     albertel 6091:         }
1.553     albertel 6092: 	&delenv('user.state.'.$cid);
1.109     www      6093:     }
                   6094: }
                   6095: 
1.265     albertel 6096: sub get_scalar {
                   6097:     my ($string,$end) = @_;
                   6098:     my $value;
                   6099:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   6100: 	$value = $1;
                   6101:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   6102: 	$value = $1;
                   6103:     }
                   6104:     return &unescape($value);
                   6105: }
                   6106: 
                   6107: sub array2str {
                   6108:   my (@array) = @_;
                   6109:   my $result=&arrayref2str(\@array);
                   6110:   $result=~s/^__ARRAY_REF__//;
                   6111:   $result=~s/__END_ARRAY_REF__$//;
                   6112:   return $result;
                   6113: }
                   6114: 
1.204     albertel 6115: sub arrayref2str {
                   6116:   my ($arrayref) = @_;
1.265     albertel 6117:   my $result='__ARRAY_REF__';
1.204     albertel 6118:   foreach my $elem (@$arrayref) {
1.265     albertel 6119:     if(ref($elem) eq 'ARRAY') {
                   6120:       $result.=&arrayref2str($elem).'&';
                   6121:     } elsif(ref($elem) eq 'HASH') {
                   6122:       $result.=&hashref2str($elem).'&';
                   6123:     } elsif(ref($elem)) {
                   6124:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 6125:     } else {
                   6126:       $result.=&escape($elem).'&';
                   6127:     }
                   6128:   }
                   6129:   $result=~s/\&$//;
1.265     albertel 6130:   $result .= '__END_ARRAY_REF__';
1.204     albertel 6131:   return $result;
                   6132: }
                   6133: 
1.168     albertel 6134: sub hash2str {
1.204     albertel 6135:   my (%hash) = @_;
                   6136:   my $result=&hashref2str(\%hash);
1.265     albertel 6137:   $result=~s/^__HASH_REF__//;
                   6138:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 6139:   return $result;
                   6140: }
                   6141: 
                   6142: sub hashref2str {
                   6143:   my ($hashref)=@_;
1.265     albertel 6144:   my $result='__HASH_REF__';
1.800     albertel 6145:   foreach my $key (sort(keys(%$hashref))) {
                   6146:     if (ref($key) eq 'ARRAY') {
                   6147:       $result.=&arrayref2str($key).'=';
                   6148:     } elsif (ref($key) eq 'HASH') {
                   6149:       $result.=&hashref2str($key).'=';
                   6150:     } elsif (ref($key)) {
1.265     albertel 6151:       $result.='=';
1.800     albertel 6152:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 6153:     } else {
1.1132    raeburn  6154: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 6155:     }
                   6156: 
1.800     albertel 6157:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   6158:       $result.=&arrayref2str($hashref->{$key}).'&';
                   6159:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   6160:       $result.=&hashref2str($hashref->{$key}).'&';
                   6161:     } elsif(ref($hashref->{$key})) {
1.265     albertel 6162:        $result.='&';
1.800     albertel 6163:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 6164:     } else {
1.800     albertel 6165:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 6166:     }
                   6167:   }
1.168     albertel 6168:   $result=~s/\&$//;
1.265     albertel 6169:   $result .= '__END_HASH_REF__';
1.168     albertel 6170:   return $result;
                   6171: }
                   6172: 
                   6173: sub str2hash {
1.265     albertel 6174:     my ($string)=@_;
                   6175:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   6176:     return %$hash;
                   6177: }
                   6178: 
                   6179: sub str2hashref {
1.168     albertel 6180:   my ($string) = @_;
1.265     albertel 6181: 
                   6182:   my %hash;
                   6183: 
                   6184:   if($string !~ /^__HASH_REF__/) {
                   6185:       if (! ($string eq '' || !defined($string))) {
                   6186: 	  $hash{'error'}='Not hash reference';
                   6187:       }
                   6188:       return (\%hash, $string);
                   6189:   }
                   6190: 
                   6191:   $string =~ s/^__HASH_REF__//;
                   6192: 
                   6193:   while($string !~ /^__END_HASH_REF__/) {
                   6194:       #key
                   6195:       my $key='';
                   6196:       if($string =~ /^__HASH_REF__/) {
                   6197:           ($key, $string)=&str2hashref($string);
                   6198:           if(defined($key->{'error'})) {
                   6199:               $hash{'error'}='Bad data';
                   6200:               return (\%hash, $string);
                   6201:           }
                   6202:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6203:           ($key, $string)=&str2arrayref($string);
                   6204:           if($key->[0] eq 'Array reference error') {
                   6205:               $hash{'error'}='Bad data';
                   6206:               return (\%hash, $string);
                   6207:           }
                   6208:       } else {
                   6209:           $string =~ s/^(.*?)=//;
1.267     albertel 6210: 	  $key=&unescape($1);
1.265     albertel 6211:       }
                   6212:       $string =~ s/^=//;
                   6213: 
                   6214:       #value
                   6215:       my $value='';
                   6216:       if($string =~ /^__HASH_REF__/) {
                   6217:           ($value, $string)=&str2hashref($string);
                   6218:           if(defined($value->{'error'})) {
                   6219:               $hash{'error'}='Bad data';
                   6220:               return (\%hash, $string);
                   6221:           }
                   6222:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6223:           ($value, $string)=&str2arrayref($string);
                   6224:           if($value->[0] eq 'Array reference error') {
                   6225:               $hash{'error'}='Bad data';
                   6226:               return (\%hash, $string);
                   6227:           }
                   6228:       } else {
                   6229: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   6230:       }
                   6231:       $string =~ s/^&//;
                   6232: 
                   6233:       $hash{$key}=$value;
1.204     albertel 6234:   }
1.265     albertel 6235: 
                   6236:   $string =~ s/^__END_HASH_REF__//;
                   6237: 
                   6238:   return (\%hash, $string);
1.204     albertel 6239: }
                   6240: 
                   6241: sub str2array {
1.265     albertel 6242:     my ($string)=@_;
                   6243:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   6244:     return @$array;
                   6245: }
                   6246: 
                   6247: sub str2arrayref {
1.204     albertel 6248:   my ($string) = @_;
1.265     albertel 6249:   my @array;
                   6250: 
                   6251:   if($string !~ /^__ARRAY_REF__/) {
                   6252:       if (! ($string eq '' || !defined($string))) {
                   6253: 	  $array[0]='Array reference error';
                   6254:       }
                   6255:       return (\@array, $string);
                   6256:   }
                   6257: 
                   6258:   $string =~ s/^__ARRAY_REF__//;
                   6259: 
                   6260:   while($string !~ /^__END_ARRAY_REF__/) {
                   6261:       my $value='';
                   6262:       if($string =~ /^__HASH_REF__/) {
                   6263:           ($value, $string)=&str2hashref($string);
                   6264:           if(defined($value->{'error'})) {
                   6265:               $array[0] ='Array reference error';
                   6266:               return (\@array, $string);
                   6267:           }
                   6268:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6269:           ($value, $string)=&str2arrayref($string);
                   6270:           if($value->[0] eq 'Array reference error') {
                   6271:               $array[0] ='Array reference error';
                   6272:               return (\@array, $string);
                   6273:           }
                   6274:       } else {
                   6275: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   6276:       }
                   6277:       $string =~ s/^&//;
                   6278: 
                   6279:       push(@array, $value);
1.191     harris41 6280:   }
1.265     albertel 6281: 
                   6282:   $string =~ s/^__END_ARRAY_REF__//;
                   6283: 
                   6284:   return (\@array, $string);
1.168     albertel 6285: }
                   6286: 
1.167     albertel 6287: # -------------------------------------------------------------------Temp Store
                   6288: 
1.168     albertel 6289: sub tmpreset {
                   6290:   my ($symb,$namespace,$domain,$stuname) = @_;
                   6291:   if (!$symb) {
                   6292:     $symb=&symbread();
1.620     albertel 6293:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6294:   }
                   6295:   $symb=escape($symb);
                   6296: 
1.620     albertel 6297:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 6298:   $namespace=~s/\//\_/g;
                   6299:   $namespace=~s/\W//g;
                   6300: 
1.620     albertel 6301:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6302:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6303:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6304:       $stuname=&get_requestor_ip();
1.591     albertel 6305:   }
1.1117    foxr     6306:   my $path=LONCAPA::tempdir();
1.168     albertel 6307:   my %hash;
                   6308:   if (tie(%hash,'GDBM_File',
                   6309: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6310: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6311:     foreach my $key (keys(%hash)) {
1.180     albertel 6312:       if ($key=~ /:$symb/) {
1.168     albertel 6313: 	delete($hash{$key});
                   6314:       }
                   6315:     }
                   6316:   }
                   6317: }
                   6318: 
1.167     albertel 6319: sub tmpstore {
1.168     albertel 6320:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6321: 
                   6322:   if (!$symb) {
                   6323:     $symb=&symbread();
1.620     albertel 6324:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6325:   }
                   6326:   $symb=escape($symb);
                   6327: 
                   6328:   if (!$namespace) {
                   6329:     # I don't think we would ever want to store this for a course.
                   6330:     # it seems this will only be used if we don't have a course.
1.620     albertel 6331:     #$namespace=$env{'request.course.id'};
1.168     albertel 6332:     #if (!$namespace) {
1.620     albertel 6333:       $namespace=$env{'request.state'};
1.168     albertel 6334:     #}
                   6335:   }
                   6336:   $namespace=~s/\//\_/g;
                   6337:   $namespace=~s/\W//g;
1.620     albertel 6338:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6339:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6340:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6341:       $stuname=&get_requestor_ip();
1.591     albertel 6342:   }
1.168     albertel 6343:   my $now=time;
                   6344:   my %hash;
1.1117    foxr     6345:   my $path=LONCAPA::tempdir();
1.168     albertel 6346:   if (tie(%hash,'GDBM_File',
                   6347: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6348: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6349:     $hash{"version:$symb"}++;
                   6350:     my $version=$hash{"version:$symb"};
                   6351:     my $allkeys=''; 
                   6352:     foreach my $key (keys(%$storehash)) {
                   6353:       $allkeys.=$key.':';
1.591     albertel 6354:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6355:     }
                   6356:     $hash{"$version:$symb:timestamp"}=$now;
                   6357:     $allkeys.='timestamp';
                   6358:     $hash{"$version:keys:$symb"}=$allkeys;
                   6359:     if (untie(%hash)) {
                   6360:       return 'ok';
                   6361:     } else {
                   6362:       return "error:$!";
                   6363:     }
                   6364:   } else {
                   6365:     return "error:$!";
                   6366:   }
                   6367: }
1.167     albertel 6368: 
1.168     albertel 6369: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6370: 
1.168     albertel 6371: sub tmprestore {
                   6372:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6373: 
1.168     albertel 6374:   if (!$symb) {
                   6375:     $symb=&symbread();
1.620     albertel 6376:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6377:   }
                   6378:   $symb=escape($symb);
                   6379: 
1.620     albertel 6380:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6381: 
1.620     albertel 6382:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6383:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6384:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6385:       $stuname=&get_requestor_ip();
1.591     albertel 6386:   }
1.168     albertel 6387:   my %returnhash;
                   6388:   $namespace=~s/\//\_/g;
                   6389:   $namespace=~s/\W//g;
                   6390:   my %hash;
1.1117    foxr     6391:   my $path=LONCAPA::tempdir();
1.168     albertel 6392:   if (tie(%hash,'GDBM_File',
                   6393: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6394: 	  &GDBM_READER(),0640)) {
1.168     albertel 6395:     my $version=$hash{"version:$symb"};
                   6396:     $returnhash{'version'}=$version;
                   6397:     my $scope;
                   6398:     for ($scope=1;$scope<=$version;$scope++) {
                   6399:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6400:       my @keys=split(/:/,$vkeys);
                   6401:       my $key;
                   6402:       $returnhash{"$scope:keys"}=$vkeys;
                   6403:       foreach $key (@keys) {
1.591     albertel 6404: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6405: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6406:       }
                   6407:     }
1.168     albertel 6408:     if (!(untie(%hash))) {
                   6409:       return "error:$!";
                   6410:     }
                   6411:   } else {
                   6412:     return "error:$!";
                   6413:   }
                   6414:   return %returnhash;
1.167     albertel 6415: }
                   6416: 
1.9       www      6417: # ----------------------------------------------------------------------- Store
                   6418: 
                   6419: sub store {
1.1172.2.64  raeburn  6420:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6421:     my $home='';
                   6422: 
1.168     albertel 6423:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6424: 
1.213     www      6425:     $symb=&symbclean($symb);
1.122     albertel 6426:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6427: 
1.620     albertel 6428:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6429:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6430: 
                   6431:     &devalidate($symb,$stuname,$domain);
1.109     www      6432: 
                   6433:     $symb=escape($symb);
1.187     www      6434:     if (!$namespace) { 
1.620     albertel 6435:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6436:           return ''; 
                   6437:        } 
                   6438:     }
1.620     albertel 6439:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6440: 
1.1172.2.138  raeburn  6441:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6442:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6443: 
1.12      www      6444:     my $namevalue='';
1.800     albertel 6445:     foreach my $key (keys(%$storehash)) {
                   6446:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6447:     }
1.12      www      6448:     $namevalue=~s/\&$//;
1.187     www      6449:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6450:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6451: }
                   6452: 
1.47      www      6453: # -------------------------------------------------------------- Critical Store
                   6454: 
                   6455: sub cstore {
1.1172.2.64  raeburn  6456:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6457:     my $home='';
                   6458: 
1.168     albertel 6459:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6460: 
1.213     www      6461:     $symb=&symbclean($symb);
1.122     albertel 6462:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6463: 
1.620     albertel 6464:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6465:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6466: 
                   6467:     &devalidate($symb,$stuname,$domain);
1.109     www      6468: 
                   6469:     $symb=escape($symb);
1.187     www      6470:     if (!$namespace) { 
1.620     albertel 6471:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6472:           return ''; 
                   6473:        } 
                   6474:     }
1.620     albertel 6475:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6476: 
1.1172.2.138  raeburn  6477:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6478:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6479: 
1.47      www      6480:     my $namevalue='';
1.800     albertel 6481:     foreach my $key (keys(%$storehash)) {
                   6482:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6483:     }
1.47      www      6484:     $namevalue=~s/\&$//;
1.187     www      6485:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6486:     return critical
1.1172.2.64  raeburn  6487:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6488: }
                   6489: 
1.9       www      6490: # --------------------------------------------------------------------- Restore
                   6491: 
                   6492: sub restore {
1.124     www      6493:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6494:     my $home='';
                   6495: 
1.168     albertel 6496:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6497: 
1.122     albertel 6498:     if (!$symb) {
1.1172.2.26  raeburn  6499:         return if ($namespace eq 'courserequests');
                   6500:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6501:     } else {
1.1172.2.26  raeburn  6502:         unless ($namespace eq 'courserequests') {
                   6503:             $symb=&escape(&symbclean($symb));
                   6504:         }
1.122     albertel 6505:     }
1.188     www      6506:     if (!$namespace) { 
1.620     albertel 6507:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6508:           return ''; 
                   6509:        } 
                   6510:     }
1.620     albertel 6511:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6512:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6513:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6514:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6515: 
1.12      www      6516:     my %returnhash=();
1.800     albertel 6517:     foreach my $line (split(/\&/,$answer)) {
                   6518: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6519:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6520:     }
1.75      www      6521:     my $version;
                   6522:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6523:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6524:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6525:        }
1.75      www      6526:     }
1.13      www      6527:     return %returnhash;
1.34      www      6528: }
                   6529: 
                   6530: # ---------------------------------------------------------- Course Description
1.1118    foxr     6531: #
                   6532: #  
1.34      www      6533: 
                   6534: sub coursedescription {
1.731     albertel 6535:     my ($courseid,$args)=@_;
1.34      www      6536:     $courseid=~s/^\///;
1.49      www      6537:     $courseid=~s/\_/\//g;
1.34      www      6538:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6539:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6540:     my $normalid=$cdomain.'_'.$cnum;
                   6541:     # need to always cache even if we get errors otherwise we keep 
                   6542:     # trying and trying and trying to get the course description.
                   6543:     my %envhash=();
                   6544:     my %returnhash=();
1.731     albertel 6545:     
                   6546:     my $expiretime=600;
                   6547:     if ($env{'request.course.id'} eq $normalid) {
                   6548: 	$expiretime=120;
                   6549:     }
                   6550: 
                   6551:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6552:     if (!$args->{'freshen_cache'}
                   6553: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6554: 	foreach my $key (keys(%env)) {
                   6555: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6556: 	    my ($setting) = $1;
                   6557: 	    $returnhash{$setting} = $env{$key};
                   6558: 	}
                   6559: 	return %returnhash;
                   6560:     }
                   6561: 
1.1118    foxr     6562:     # get the data again
                   6563: 
1.731     albertel 6564:     if (!$args->{'one_time'}) {
                   6565: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6566:     }
1.811     albertel 6567: 
1.34      www      6568:     if ($chome ne 'no_host') {
1.302     albertel 6569:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6570:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6571: 	   my $username = $env{'user.name'}; # Defult username
                   6572: 	   if(defined $args->{'user'}) {
                   6573: 	       $username = $args->{'user'};
                   6574: 	   }
1.129     albertel 6575:            $returnhash{'home'}= $chome;
                   6576: 	   $returnhash{'domain'} = $cdomain;
                   6577: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6578:            if (!defined($returnhash{'type'})) {
                   6579:                $returnhash{'type'} = 'Course';
                   6580:            }
1.130     albertel 6581:            while (my ($name,$value) = each %returnhash) {
1.53      www      6582:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6583:            }
1.270     www      6584:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6585:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6586: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6587:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6588:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6589:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6590:        }
                   6591:     }
1.731     albertel 6592:     if (!$args->{'one_time'}) {
1.949     raeburn  6593: 	&appenv(\%envhash);
1.731     albertel 6594:     }
1.302     albertel 6595:     return %returnhash;
1.461     www      6596: }
                   6597: 
1.1080    raeburn  6598: sub update_released_required {
                   6599:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6600:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6601:         $cid = $env{'request.course.id'};
                   6602:         $cdom = $env{'course.'.$cid.'.domain'};
                   6603:         $cnum = $env{'course.'.$cid.'.num'};
                   6604:         $chome = $env{'course.'.$cid.'.home'};
                   6605:     }
                   6606:     if ($needsrelease) {
                   6607:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6608:         my $needsupdate;
                   6609:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6610:             $needsupdate = 1;
                   6611:         } else {
                   6612:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6613:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6614:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6615:                 $needsupdate = 1;
                   6616:             }
                   6617:         }
                   6618:         if ($needsupdate) {
                   6619:             my %needshash = (
                   6620:                              'internal.releaserequired' => $needsrelease,
                   6621:                             );
                   6622:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6623:             if ($putresult eq 'ok') {
                   6624:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6625:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6626:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6627:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6628:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6629:                 }
                   6630:             }
                   6631:         }
                   6632:     }
                   6633:     return;
                   6634: }
                   6635: 
1.461     www      6636: # -------------------------------------------------See if a user is privileged
                   6637: 
                   6638: sub privileged {
1.1172.2.23  raeburn  6639:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6640:     my $now = time;
1.1172.2.23  raeburn  6641:     my $roles;
                   6642:     if (ref($possroles) eq 'ARRAY') {
                   6643:         $roles = $possroles;
                   6644:     } else {
                   6645:         $roles = ['dc','su'];
                   6646:     }
                   6647:     if (ref($possdomains) eq 'ARRAY') {
                   6648:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6649:         foreach my $dom (@{$possdomains}) {
                   6650:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6651:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6652:                 foreach my $role (@{$roles}) {
                   6653:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6654:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6655:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6656:                             return 1 unless (($end && $end < $now) ||
                   6657:                                              ($start && $start > $now));
                   6658:                         }
                   6659:                     }
                   6660:                 }
                   6661:             }
                   6662:         }
                   6663:     } else {
                   6664:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6665:         my $now = time;
1.1170    droeschl 6666: 
1.1172.2.58  raeburn  6667:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6668:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6669:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6670:                 return 1 unless ($tend && $tend < $now)
                   6671:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6672:             }
1.1172.2.23  raeburn  6673:         }
                   6674:     }
1.461     www      6675:     return 0;
1.9       www      6676: }
1.1       albertel 6677: 
1.1172.2.23  raeburn  6678: sub privileged_by_domain {
                   6679:     my ($domains,$roles) = @_;
                   6680:     my %privileged = ();
                   6681:     my $cachetime = 60*60*24;
                   6682:     my $now = time;
                   6683:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6684:         return %privileged;
                   6685:     }
                   6686:     foreach my $dom (@{$domains}) {
                   6687:         next if (ref($privileged{$dom}) eq 'HASH');
                   6688:         my $needroles;
                   6689:         foreach my $role (@{$roles}) {
                   6690:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6691:             if (defined($cached)) {
                   6692:                 if (ref($result) eq 'HASH') {
                   6693:                     $privileged{$dom}{$role} = $result;
                   6694:                 }
                   6695:             } else {
                   6696:                 $needroles = 1;
                   6697:             }
                   6698:         }
                   6699:         if ($needroles) {
                   6700:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6701:             $privileged{$dom} = {};
                   6702:             foreach my $server (keys(%dompersonnel)) {
                   6703:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6704:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6705:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6706:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6707:                         next if ($end && $end < $now);
                   6708:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6709:                             $dompersonnel{$server}{$item};
                   6710:                     }
                   6711:                 }
                   6712:             }
                   6713:             if (ref($privileged{$dom}) eq 'HASH') {
                   6714:                 foreach my $role (@{$roles}) {
                   6715:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6716:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6717:                     } else {
                   6718:                         my %hash = ();
                   6719:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6720:                     }
                   6721:                 }
                   6722:             }
                   6723:         }
                   6724:     }
                   6725:     return %privileged;
                   6726: }
                   6727: 
1.103     harris41 6728: # -------------------------------------------------------- Get user privileges
1.11      www      6729: 
                   6730: sub rolesinit {
1.1169    droeschl 6731:     my ($domain, $username) = @_;
                   6732:     my %userroles = ('user.login.time' => time);
                   6733:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6734: 
                   6735:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6736:     # also, blocking can be triggered by an activating timer
                   6737:     # it's saved in the user's %env.
                   6738:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6739:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6740:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
1.1172.2.146.  .18(raeb 6741:-24):         %timerintchk, %timerintenv,%coauthorenv);
1.1169    droeschl 6742: 
1.1162    raeburn  6743:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6744:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6745:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6746:     }
1.1169    droeschl 6747: 
1.1162    raeburn  6748:     foreach my $key (keys(%timerinterval)) {
                   6749:         my ($cid,$rest) = split(/\0/,$key);
                   6750:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6751:     }
1.1169    droeschl 6752: 
1.11      www      6753:     my %allroles=();
1.1162    raeburn  6754:     my %allgroups=();
1.1172.2.146.  .18(raeb 6755:-24):     my %gotcoauconfig=();
          .20(raeb 6756:-24):     my %domdefaults=();
1.11      www      6757: 
1.1172.2.58  raeburn  6758:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6759:         my $role = $rolesdump{$area};
                   6760:         $area =~ s/\_\w\w$//;
                   6761: 
                   6762:         my ($trole, $tend, $tstart, $group_privs);
                   6763: 
                   6764:         if ($role =~ /^cr/) {
                   6765:         # Custom role, defined by a user 
                   6766:         # e.g., user.role.cr/msu/smith/mynewrole
                   6767:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6768:                 $trole = $1;
                   6769:                 ($tend, $tstart) = split('_', $2);
                   6770:             } else {
                   6771:                 $trole = $role;
                   6772:             }
                   6773:         } elsif ($role =~ m|^gr/|) {
                   6774:         # Role of member in a group, defined within a course/community
                   6775:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6776:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6777:             next if $tstart eq '-1';
                   6778:             ($trole, $group_privs) = split(/\//, $trole);
                   6779:             $group_privs = &unescape($group_privs);
                   6780:         } else {
                   6781:         # Just a normal role, defined in roles.tab
                   6782:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6783:         }
                   6784: 
                   6785:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6786:                  $username);
                   6787:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6788: 
                   6789:         # role expired or not available yet?
                   6790:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6791:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6792: 
                   6793:         next if $area eq '' or $trole eq '';
                   6794: 
                   6795:         my $spec = "$trole.$area";
                   6796:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6797: 
                   6798:         if ($trole =~ /^cr\//) {
                   6799:         # Custom role, defined by a user
                   6800:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6801:         } elsif ($trole eq 'gr') {
                   6802:         # Role of a member in a group, defined within a course/community
                   6803:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6804:             next;
                   6805:         } else {
                   6806:         # Normal role, defined in roles.tab
                   6807:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.1172.2.146.  .18(raeb 6808:-24):             if (($trole eq 'ca') || ($trole eq 'aa')) {
                   6809:-24):                 (undef,my ($audom,$auname)) = split(/\//,$area);
                   6810:-24):                 unless ($gotcoauconfig{$area}) {
                   6811:-24):                     my @ca_settings = ('authoreditors');
                   6812:-24):                     my %info = &userenvironment($audom,$auname,@ca_settings);
                   6813:-24):                     $gotcoauconfig{$area} = 1;
                   6814:-24):                     foreach my $item (@ca_settings) {
                   6815:-24):                         if (exists($info{$item})) {
                   6816:-24):                             my $name = $item;
                   6817:-24):                             if ($item eq 'authoreditors') {
                   6818:-24):                                 $name = 'editors';
          .20(raeb 6819:-24):                                 unless ($info{'authoreditors'}) {
                   6820:-24):                                     my %domdefs;
                   6821:-24):                                     if (ref($domdefaults{$audom}) eq 'HASH') {
                   6822:-24):                                         %domdefs = %{$domdefaults{$audom}};
                   6823:-24):                                     } else {
                   6824:-24):                                         %domdefs = &get_domain_defaults($audom);
                   6825:-24):                                         $domdefaults{$audom} = \%domdefs;
                   6826:-24):                                     }
                   6827:-24):                                     if ($domdefs{$name} ne '') {
                   6828:-24):                                         $info{'authoreditors'} = $domdefs{$name};
                   6829:-24):                                     } else {
                   6830:-24):                                         $info{'authoreditors'} = 'edit,xml';
                   6831:-24):                                     }
                   6832:-24):                                 }
          .18(raeb 6833:-24):                             }
                   6834:-24):                             $coauthorenv{"environment.internal.$name.$area"} = $info{$item};
                   6835:-24):                         }
                   6836:-24):                     }
                   6837:-24):                 }
                   6838:-24):             }
1.1169    droeschl 6839:         }
                   6840: 
                   6841:         my $cid = $tdomain.'_'.$trest;
                   6842:         unless ($firstaccchk{$cid}) {
                   6843:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6844:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6845:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6846:                         $coursetimerstarts{$cid}{$item}; 
                   6847:                 }
                   6848:             }
                   6849:             $firstaccchk{$cid} = 1;
                   6850:         }
                   6851:         unless ($timerintchk{$cid}) {
                   6852:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6853:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6854:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6855:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6856:                 }
1.12      www      6857:             }
1.1169    droeschl 6858:             $timerintchk{$cid} = 1;
1.191     harris41 6859:         }
1.11      www      6860:     }
1.1169    droeschl 6861: 
1.1172.2.91  raeburn  6862:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6863:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6864:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6865:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6866: 
1.1172.2.146.  .18(raeb 6867:-24):     return (\%userroles,\%firstaccenv,\%timerintenv,\%coauthorenv);
1.11      www      6868: }
                   6869: 
1.567     raeburn  6870: sub set_arearole {
1.1172.2.19  raeburn  6871:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6872:     unless ($nolog) {
1.567     raeburn  6873: # log the associated role with the area
1.1172.2.19  raeburn  6874:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6875:     }
1.743     albertel 6876:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6877: }
                   6878: 
                   6879: sub custom_roleprivs {
                   6880:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6881:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6882:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6883:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6884:         my ($rdummy,$roledef)=
                   6885:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6886:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6887:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6888:             if (defined($syspriv)) {
1.1043    raeburn  6889:                 if ($trest =~ /^$match_community$/) {
                   6890:                     $syspriv =~ s/bre\&S//; 
                   6891:                 }
1.567     raeburn  6892:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6893:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6894:             }
                   6895:             if ($tdomain ne '') {
                   6896:                 if (defined($dompriv)) {
                   6897:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6898:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6899:                 }
                   6900:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6901:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6902:                         my $rolename = $1;
                   6903:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6904:                     }
1.567     raeburn  6905:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6906:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6907:                 }
                   6908:             }
                   6909:         }
                   6910:     }
                   6911: }
                   6912: 
1.1172.2.89  raeburn  6913: sub course_adhocrole_privs {
                   6914:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6915:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6916:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6917:         my (%currprivs,%storeprivs);
                   6918:         foreach my $item (split(/:/,$coursepriv)) {
                   6919:             my ($priv,$restrict) = split(/\&/,$item);
                   6920:             $currprivs{$priv} = $restrict;
                   6921:         }
                   6922:         my (%possadd,%possremove,%full);
                   6923:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6924:             my ($priv,$restrict)=split(/\&/,$item);
                   6925:             $full{$priv} = $restrict;
                   6926:         }
                   6927:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
1.1172.2.146.  .6(raebu 6928:22):             next if ($item eq '');
                   6929:22):             my ($rule,$rest) = split(/=/,$item);
                   6930:22):             next unless (($rule eq 'off') || ($rule eq 'on'));
                   6931:22):             foreach my $priv (split(/:/,$rest)) {
                   6932:22):                 if ($priv ne '') {
                   6933:22):                     if ($rule eq 'off') {
                   6934:22):                         $possremove{$priv} = 1;
                   6935:22):                     } else {
                   6936:22):                         $possadd{$priv} = 1;
                   6937:22):                     }
                   6938:22):                 }
                   6939:22):             }
                   6940:22):         }
                   6941:22):         foreach my $priv (sort(keys(%full))) {
                   6942:22):             if (exists($currprivs{$priv})) {
                   6943:22):                 unless (exists($possremove{$priv})) {
                   6944:22):                     $storeprivs{$priv} = $currprivs{$priv};
                   6945:22):                 }
                   6946:22):             } elsif (exists($possadd{$priv})) {
                   6947:22):                 $storeprivs{$priv} = $full{$priv};
                   6948:22):             }
                   6949:22):         }
                   6950:22):         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6951:22):     }
                   6952:22):     return $coursepriv;
1.1172.2.89  raeburn  6953: }
                   6954: 
1.678     raeburn  6955: sub group_roleprivs {
                   6956:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6957:     my $access = 1;
                   6958:     my $now = time;
                   6959:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6960:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6961:     if ($access) {
1.811     albertel 6962:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6963:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6964:     }
                   6965: }
1.567     raeburn  6966: 
                   6967: sub standard_roleprivs {
                   6968:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6969:     if (defined($pr{$trole.':s'})) {
                   6970:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6971:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6972:     }
                   6973:     if ($tdomain ne '') {
                   6974:         if (defined($pr{$trole.':d'})) {
                   6975:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6976:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6977:         }
                   6978:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6979:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6980:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6981:         }
                   6982:     }
                   6983: }
                   6984: 
                   6985: sub set_userprivs {
1.1064    raeburn  6986:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6987:     my $author=0;
                   6988:     my $adv=0;
1.1172.2.91  raeburn  6989:     my $rar=0;
1.678     raeburn  6990:     my %grouproles = ();
                   6991:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6992:         my @groupkeys; 
1.1000    raeburn  6993:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6994:             push(@groupkeys,$role);
                   6995:         }
                   6996:         if (ref($groups_roles) eq 'HASH') {
                   6997:             foreach my $key (keys(%{$groups_roles})) {
                   6998:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6999:                     push(@groupkeys,$key);
                   7000:                 }
                   7001:             }
                   7002:         }
                   7003:         if (@groupkeys > 0) {
                   7004:             foreach my $role (@groupkeys) {
                   7005:                 my ($trole,$area,$sec,$extendedarea);
                   7006:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   7007:                     $trole = $1;
                   7008:                     $area = $2;
                   7009:                     $sec = $3;
                   7010:                     $extendedarea = $area.$sec;
                   7011:                     if (exists($$allgroups{$area})) {
                   7012:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   7013:                             my $spec = $trole.'.'.$extendedarea;
                   7014:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  7015:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  7016:                         }
1.678     raeburn  7017:                     }
                   7018:                 }
                   7019:             }
                   7020:         }
                   7021:     }
1.800     albertel 7022:     foreach my $group (keys(%grouproles)) {
                   7023:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  7024:     }
1.800     albertel 7025:     foreach my $role (keys(%{$allroles})) {
                   7026:         my %thesepriv;
1.941     raeburn  7027:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 7028:         foreach my $item (split(/:/,$$allroles{$role})) {
                   7029:             if ($item ne '') {
                   7030:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  7031:                 if ($restrictions eq '') {
                   7032:                     $thesepriv{$privilege}='F';
                   7033:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   7034:                     $thesepriv{$privilege}.=$restrictions;
                   7035:                 }
                   7036:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  7037:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  7038:             }
                   7039:         }
                   7040:         my $thesestr='';
1.1104    raeburn  7041:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 7042: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   7043: 	}
                   7044:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  7045:     }
1.1172.2.91  raeburn  7046:     return ($author,$adv,$rar);
1.567     raeburn  7047: }
                   7048: 
1.994     raeburn  7049: sub role_status {
1.1104    raeburn  7050:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  7051:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  7052:         my ($one,$two) = split(m{\./},$rolekey,2);
                   7053:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  7054:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  7055:             $$where = '/'.$two;
1.994     raeburn  7056:             $$trolecode=$$role.'.'.$$where;
                   7057:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   7058:             $$tstatus='is';
1.1104    raeburn  7059:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  7060:                 $$tstatus='future';
1.1034    raeburn  7061:                 if ($$tstart<$now) {
                   7062:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  7063:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  7064:                             my (%allroles,%allgroups,$group_privs,
                   7065:                                 %groups_roles,@rolecodes);
1.1002    raeburn  7066:                             my %userroles = (
                   7067:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   7068:                             );
1.1064    raeburn  7069:                             @rolecodes = ('cm'); 
1.1002    raeburn  7070:                             my $spec=$$role.'.'.$$where;
                   7071:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   7072:                             if ($$role =~ /^cr\//) {
                   7073:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  7074:                                 push(@rolecodes,'cr');
1.1002    raeburn  7075:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  7076:                                 push(@rolecodes,$$role);
1.1002    raeburn  7077:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   7078:                                                     $env{'user.name'});
1.1064    raeburn  7079:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  7080:                                 (undef,my $group_privs) = split(/\//,$trole);
                   7081:                                 $group_privs = &unescape($group_privs);
                   7082:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  7083:                                 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  7084:                                 &get_groups_roles($tdomain,$trest,
                   7085:                                                   \%course_roles,\@rolecodes,
                   7086:                                                   \%groups_roles);
1.1002    raeburn  7087:                             } else {
1.1064    raeburn  7088:                                 push(@rolecodes,$$role);
1.1002    raeburn  7089:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   7090:                             }
1.1172.2.91  raeburn  7091:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   7092:                                                                    \%groups_roles);
1.1064    raeburn  7093:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  7094:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  7095:                         }
                   7096:                     }
1.1034    raeburn  7097:                     $$tstatus = 'is';
1.1002    raeburn  7098:                 }
1.994     raeburn  7099:             }
                   7100:             if ($$tend) {
1.1104    raeburn  7101:                 if ($$tend<$update) {
1.994     raeburn  7102:                     $$tstatus='expired';
                   7103:                 } elsif ($$tend<$now) {
                   7104:                     $$tstatus='will_not';
                   7105:                 }
                   7106:             }
                   7107:         }
                   7108:     }
                   7109: }
                   7110: 
1.1104    raeburn  7111: sub get_groups_roles {
                   7112:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   7113:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   7114:                   (ref($rolecodes) eq 'ARRAY') && 
                   7115:                   (ref($groups_roles) eq 'HASH')); 
                   7116:     if (keys(%{$cdom_courseroles}) > 0) {
                   7117:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   7118:         if ($cdom ne '' && $cnum ne '') {
                   7119:             foreach my $key (keys(%{$cdom_courseroles})) {
                   7120:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   7121:                     my $crsrole = $1;
                   7122:                     my $crssec = $2;
                   7123:                     if ($crsrole =~ /^cr/) {
                   7124:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   7125:                             push(@{$rolecodes},'cr');
                   7126:                         }
                   7127:                     } else {
                   7128:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   7129:                             push(@{$rolecodes},$crsrole);
                   7130:                         }
                   7131:                     }
                   7132:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   7133:                     if ($crssec ne '') {
                   7134:                         $rolekey .= "/$crssec";
                   7135:                     }
                   7136:                     $rolekey .= './';
                   7137:                     $groups_roles->{$rolekey} = $rolecodes;
                   7138:                 }
                   7139:             }
                   7140:         }
                   7141:     }
                   7142:     return;
                   7143: }
                   7144: 
                   7145: sub delete_env_groupprivs {
                   7146:     my ($where,$courseroles,$possroles) = @_;
                   7147:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   7148:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   7149:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   7150:         %{$courseroles->{$udom}} =
                   7151:             &get_my_roles('','','userroles',['active'],
                   7152:                           $possroles,[$udom],1);
                   7153:     }
                   7154:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   7155:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   7156:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   7157:             my $area = '/'.$cdom.'/'.$cnum;
                   7158:             my $privkey = "user.priv.$crsrole.$area";
                   7159:             if ($crssec ne '') {
                   7160:                 $privkey .= '/'.$crssec;
                   7161:             }
                   7162:             $privkey .= ".$area/$group";
                   7163:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   7164:         }
                   7165:     }
                   7166:     return;
                   7167: }
                   7168: 
1.994     raeburn  7169: sub check_adhoc_privs {
1.1172.2.86  raeburn  7170:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  7171:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  7172:     if ($sec) {
                   7173:         $cckey .= '/'.$sec;
                   7174:     }
1.1172.2.9  raeburn  7175:     my $setprivs;
1.994     raeburn  7176:     if ($env{$cckey}) {
                   7177:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  7178:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  7179:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  7180:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  7181:             $setprivs = 1;
1.994     raeburn  7182:         }
                   7183:     } else {
1.1172.2.87  raeburn  7184:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  7185:         $setprivs = 1;
1.994     raeburn  7186:     }
1.1172.2.9  raeburn  7187:     return $setprivs;
1.994     raeburn  7188: }
                   7189: 
                   7190: sub set_adhoc_privileges {
1.1172.2.84  raeburn  7191: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  7192:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  7193:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  7194:     if ($sec ne '') {
                   7195:         $area .= '/'.$sec;
                   7196:     }
1.994     raeburn  7197:     my $spec = $role.'.'.$area;
                   7198:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  7199:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  7200:     my %rolehash = ();
1.1172.2.89  raeburn  7201:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   7202:         my $rolename = $1;
1.1172.2.84  raeburn  7203:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  7204:         my %domdef = &get_domain_defaults($dcdom);
                   7205:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   7206:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   7207:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   7208:             }
                   7209:         }
1.1172.2.84  raeburn  7210:     } else {
                   7211:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   7212:     }
1.1172.2.91  raeburn  7213:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  7214:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  7215:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1172.2.146.  .1(raebu 7216:22):     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   7217:22):             ($caller eq 'tiny')) {
1.1088    raeburn  7218:         &appenv( {'request.role'        => $spec,
                   7219:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  7220:                   'request.course.sec'  => $sec, 
1.1088    raeburn  7221:                  }
                   7222:                );
                   7223:         my $tadv=0;
                   7224:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   7225:         &appenv({'request.role.adv'    => $tadv});
                   7226:     }
1.994     raeburn  7227: }
                   7228: 
1.12      www      7229: # --------------------------------------------------------------- get interface
                   7230: 
                   7231: sub get {
1.131     albertel 7232:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7233:    my $items='';
1.800     albertel 7234:    foreach my $item (@$storearr) {
                   7235:        $items.=&escape($item).'&';
1.191     harris41 7236:    }
1.12      www      7237:    $items=~s/\&$//;
1.620     albertel 7238:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7239:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 7240:    my $uhome=&homeserver($uname,$udomain);
                   7241: 
1.133     albertel 7242:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7243:    my @pairs=split(/\&/,$rep);
1.273     albertel 7244:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   7245:      return @pairs;
                   7246:    }
1.15      www      7247:    my %returnhash=();
1.42      www      7248:    my $i=0;
1.800     albertel 7249:    foreach my $item (@$storearr) {
                   7250:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7251:       $i++;
1.191     harris41 7252:    }
1.15      www      7253:    return %returnhash;
1.27      www      7254: }
                   7255: 
                   7256: # --------------------------------------------------------------- del interface
                   7257: 
                   7258: sub del {
1.133     albertel 7259:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      7260:    my $items='';
1.800     albertel 7261:    foreach my $item (@$storearr) {
                   7262:        $items.=&escape($item).'&';
1.191     harris41 7263:    }
1.984     neumanie 7264: 
1.27      www      7265:    $items=~s/\&$//;
1.620     albertel 7266:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7267:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7268:    my $uhome=&homeserver($uname,$udomain);
                   7269:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7270: }
                   7271: 
                   7272: # -------------------------------------------------------------- dump interface
                   7273: 
1.1172.2.22  raeburn  7274: sub unserialize {
                   7275:     my ($rep, $escapedkeys) = @_;
                   7276: 
                   7277:     return {} if $rep =~ /^error/;
                   7278: 
                   7279:     my %returnhash=();
                   7280:     foreach my $item (split(/\&/,$rep)) {
                   7281:         my ($key, $value) = split(/=/, $item, 2);
                   7282:         $key = unescape($key) unless $escapedkeys;
                   7283:         next if $key =~ /^error: 2 /;
                   7284:         $returnhash{$key} = &thaw_unescape($value);
                   7285:     }
                   7286:     return \%returnhash;
                   7287: }
                   7288: 
                   7289: # see Lond::dump_with_regexp
                   7290: # if $escapedkeys hash keys won't get unescaped.
1.15      www      7291: sub dump {
1.1172.2.146.  .1(raebu 7292:22):     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755     albertel 7293:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7294:     if (!$uname) { $uname=$env{'user.name'}; }
                   7295:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 7296: 
1.1172.2.55  raeburn  7297:     if ($regexp) {
                   7298:         $regexp=&escape($regexp);
                   7299:     } else {
                   7300:         $regexp='.';
                   7301:     }
1.1172.2.22  raeburn  7302:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   7303:         # user is hosted on this machine
1.1172.2.55  raeburn  7304:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  7305:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  7306:         return %{&unserialize($reply, $escapedkeys)};
                   7307:     }
1.1172.2.146.  .1(raebu 7308:22):     my $rep;
                   7309:22):     if ($encrypt) {
                   7310:22):         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7311:22):     } else {
                   7312:22):         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7313:22):     }
1.755     albertel 7314:     my @pairs=split(/\&/,$rep);
                   7315:     my %returnhash=();
1.1098    foxr     7316:     if (!($rep =~ /^error/ )) {
                   7317: 	foreach my $item (@pairs) {
                   7318: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  7319:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     7320: 	    next if ($key =~ /^error: 2 /);
                   7321: 	    $returnhash{$key}=&thaw_unescape($value);
                   7322: 	}
1.755     albertel 7323:     }
                   7324:     return %returnhash;
1.407     www      7325: }
                   7326: 
1.1098    foxr     7327: 
1.717     albertel 7328: # --------------------------------------------------------- dumpstore interface
                   7329: 
                   7330: sub dumpstore {
                   7331:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  7332:    # same as dump but keys must be escaped. They may contain colon separated
                   7333:    # lists of values that may themself contain colons (e.g. symbs).
                   7334:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7335: }
                   7336: 
1.407     www      7337: # -------------------------------------------------------------- keys interface
                   7338: 
                   7339: sub getkeys {
                   7340:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7341:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7342:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7343:    my $uhome=&homeserver($uname,$udomain);
                   7344:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7345:    my @keyarray=();
1.800     albertel 7346:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7347:       next if ($key =~ /^error: 2 /);
1.800     albertel 7348:       push(@keyarray,&unescape($key));
1.407     www      7349:    }
                   7350:    return @keyarray;
1.318     matthew  7351: }
                   7352: 
1.319     matthew  7353: # --------------------------------------------------------------- currentdump
                   7354: sub currentdump {
1.328     matthew  7355:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7356:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7357:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7358:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7359:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  7360:    my $rep;
                   7361: 
                   7362:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7363:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   7364:                    $courseid)));
                   7365:    } else {
                   7366:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7367:    }
                   7368: 
1.318     matthew  7369:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7370:    #
1.318     matthew  7371:    my %returnhash=();
1.319     matthew  7372:    #
                   7373:    if ($rep eq "unknown_cmd") { 
                   7374:        # an old lond will not know currentdump
                   7375:        # Do a dump and make it look like a currentdump
1.822     albertel 7376:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7377:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7378:        my %hash = @tmp;
                   7379:        @tmp=();
1.424     matthew  7380:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7381:    } else {
                   7382:        my @pairs=split(/\&/,$rep);
1.800     albertel 7383:        foreach my $pair (@pairs) {
                   7384:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7385:            my ($symb,$param) = split(/:/,$key);
                   7386:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7387:                                                         &thaw_unescape($value);
1.319     matthew  7388:        }
1.191     harris41 7389:    }
1.12      www      7390:    return %returnhash;
1.424     matthew  7391: }
                   7392: 
                   7393: sub convert_dump_to_currentdump{
                   7394:     my %hash = %{shift()};
                   7395:     my %returnhash;
                   7396:     # Code ripped from lond, essentially.  The only difference
                   7397:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7398:     # we might run in to problems with parameter names =~ /^v\./
                   7399:     while (my ($key,$value) = each(%hash)) {
                   7400:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7401: 	$symb  = &unescape($symb);
                   7402: 	$param = &unescape($param);
1.424     matthew  7403:         next if ($v eq 'version' || $symb eq 'keys');
                   7404:         next if (exists($returnhash{$symb}) &&
                   7405:                  exists($returnhash{$symb}->{$param}) &&
                   7406:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7407:         $returnhash{$symb}->{$param}=$value;
                   7408:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7409:     }
                   7410:     #
                   7411:     # Remove all of the keys in the hashes which keep track of
                   7412:     # the version of the parameter.
                   7413:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7414:         # use a foreach because we are going to delete from the hash.
                   7415:         foreach my $key (keys(%$param_hash)) {
                   7416:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7417:         }
                   7418:     }
                   7419:     return \%returnhash;
1.12      www      7420: }
                   7421: 
1.627     albertel 7422: # ------------------------------------------------------ critical inc interface
                   7423: 
                   7424: sub cinc {
                   7425:     return &inc(@_,'critical');
                   7426: }
                   7427: 
1.449     matthew  7428: # --------------------------------------------------------------- inc interface
                   7429: 
                   7430: sub inc {
1.627     albertel 7431:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7432:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7433:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7434:     my $uhome=&homeserver($uname,$udomain);
                   7435:     my $items='';
                   7436:     if (! ref($store)) {
                   7437:         # got a single value, so use that instead
                   7438:         $items = &escape($store).'=&';
                   7439:     } elsif (ref($store) eq 'SCALAR') {
                   7440:         $items = &escape($$store).'=&';        
                   7441:     } elsif (ref($store) eq 'ARRAY') {
                   7442:         $items = join('=&',map {&escape($_);} @{$store});
                   7443:     } elsif (ref($store) eq 'HASH') {
                   7444:         while (my($key,$value) = each(%{$store})) {
                   7445:             $items.= &escape($key).'='.&escape($value).'&';
                   7446:         }
                   7447:     }
                   7448:     $items=~s/\&$//;
1.627     albertel 7449:     if ($critical) {
                   7450: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7451:     } else {
                   7452: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7453:     }
1.449     matthew  7454: }
                   7455: 
1.12      www      7456: # --------------------------------------------------------------- put interface
                   7457: 
                   7458: sub put {
1.1172.2.146.  .1(raebu 7459:22):    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620     albertel 7460:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7461:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7462:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7463:    my $items='';
1.800     albertel 7464:    foreach my $item (keys(%$storehash)) {
                   7465:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7466:    }
1.12      www      7467:    $items=~s/\&$//;
1.1172.2.146.  .1(raebu 7468:22):    if ($encrypt) {
                   7469:22):        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
                   7470:22):    } else {
                   7471:22):        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   7472:22):    }
1.47      www      7473: }
                   7474: 
1.631     albertel 7475: # ------------------------------------------------------------ newput interface
                   7476: 
                   7477: sub newput {
                   7478:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7479:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7480:    if (!$uname) { $uname=$env{'user.name'}; }
                   7481:    my $uhome=&homeserver($uname,$udomain);
                   7482:    my $items='';
                   7483:    foreach my $key (keys(%$storehash)) {
                   7484:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7485:    }
                   7486:    $items=~s/\&$//;
                   7487:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7488: }
                   7489: 
                   7490: # ---------------------------------------------------------  putstore interface
                   7491: 
1.524     raeburn  7492: sub putstore {
1.1172.2.59  raeburn  7493:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7494:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7495:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7496:    my $uhome=&homeserver($uname,$udomain);
                   7497:    my $items='';
1.715     albertel 7498:    foreach my $key (keys(%$storehash)) {
                   7499:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7500:    }
1.715     albertel 7501:    $items=~s/\&$//;
1.716     albertel 7502:    my $esc_symb=&escape($symb);
                   7503:    my $esc_v=&escape($version);
1.715     albertel 7504:    my $reply =
1.716     albertel 7505:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7506: 	      $uhome);
1.1172.2.59  raeburn  7507:    if (($tolog) && ($reply eq 'ok')) {
                   7508:        my $namevalue='';
                   7509:        foreach my $key (keys(%{$storehash})) {
                   7510:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7511:        }
1.1172.2.134  raeburn  7512:        my $ip = &get_requestor_ip();
1.1172.2.135  raeburn  7513:        $namevalue .= 'ip='.&escape($ip).
1.1172.2.59  raeburn  7514:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7515:                      '&version='.$esc_v.
                   7516:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7517:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7518:    }
1.715     albertel 7519:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7520:        # gfall back to way things use to be done
1.715     albertel 7521:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7522: 			    $uname);
1.524     raeburn  7523:    }
1.715     albertel 7524:    return $reply;
                   7525: }
                   7526: 
                   7527: sub old_putstore {
1.716     albertel 7528:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7529:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7530:     if (!$uname) { $uname=$env{'user.name'}; }
                   7531:     my $uhome=&homeserver($uname,$udomain);
                   7532:     my %newstorehash;
1.800     albertel 7533:     foreach my $item (keys(%$storehash)) {
                   7534: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7535: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7536:     }
                   7537:     my $items='';
                   7538:     my %allitems = ();
1.800     albertel 7539:     foreach my $item (keys(%newstorehash)) {
                   7540: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7541: 	    my $key = $1.':keys:'.$2;
                   7542: 	    $allitems{$key} .= $3.':';
                   7543: 	}
1.800     albertel 7544: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7545:     }
1.800     albertel 7546:     foreach my $item (keys(%allitems)) {
                   7547: 	$allitems{$item} =~ s/\:$//;
                   7548: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7549:     }
                   7550:     $items=~s/\&$//;
                   7551:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7552: }
                   7553: 
1.47      www      7554: # ------------------------------------------------------ critical put interface
                   7555: 
                   7556: sub cput {
1.134     albertel 7557:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7558:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7559:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7560:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7561:    my $items='';
1.800     albertel 7562:    foreach my $item (keys(%$storehash)) {
                   7563:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7564:    }
1.47      www      7565:    $items=~s/\&$//;
1.134     albertel 7566:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7567: }
                   7568: 
                   7569: # -------------------------------------------------------------- eget interface
                   7570: 
                   7571: sub eget {
1.133     albertel 7572:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7573:    my $items='';
1.800     albertel 7574:    foreach my $item (@$storearr) {
                   7575:        $items.=&escape($item).'&';
1.191     harris41 7576:    }
1.12      www      7577:    $items=~s/\&$//;
1.620     albertel 7578:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7579:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7580:    my $uhome=&homeserver($uname,$udomain);
                   7581:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7582:    my @pairs=split(/\&/,$rep);
                   7583:    my %returnhash=();
1.42      www      7584:    my $i=0;
1.800     albertel 7585:    foreach my $item (@$storearr) {
                   7586:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7587:       $i++;
1.191     harris41 7588:    }
1.12      www      7589:    return %returnhash;
                   7590: }
                   7591: 
1.667     albertel 7592: # ------------------------------------------------------------ tmpput interface
                   7593: sub tmpput {
1.802     raeburn  7594:     my ($storehash,$server,$context)=@_;
1.667     albertel 7595:     my $items='';
1.800     albertel 7596:     foreach my $item (keys(%$storehash)) {
                   7597: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7598:     }
                   7599:     $items=~s/\&$//;
1.802     raeburn  7600:     if (defined($context)) {
                   7601:         $items .= ':'.&escape($context);
                   7602:     }
1.667     albertel 7603:     return &reply("tmpput:$items",$server);
                   7604: }
                   7605: 
                   7606: # ------------------------------------------------------------ tmpget interface
                   7607: sub tmpget {
1.688     albertel 7608:     my ($token,$server)=@_;
                   7609:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7610:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7611:     my %returnhash;
1.1172.2.85  raeburn  7612:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7613:         return %returnhash;
                   7614:     }
1.667     albertel 7615:     foreach my $item (split(/\&/,$rep)) {
                   7616: 	my ($key,$value)=split(/=/,$item);
                   7617: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7618:     }
                   7619:     return %returnhash;
                   7620: }
                   7621: 
1.1113    raeburn  7622: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7623: sub tmpdel {
                   7624:     my ($token,$server)=@_;
                   7625:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7626:     return &reply("tmpdel:$token",$server);
                   7627: }
                   7628: 
1.1172.2.13  raeburn  7629: # ------------------------------------------------------------ get_timebased_id
                   7630: 
                   7631: sub get_timebased_id {
                   7632:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7633:         $maxtries) = @_;
                   7634:     my ($newid,$error,$dellock);
                   7635:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7636:         return ('','ok','invalid call to get suffix');
                   7637:     }
                   7638: 
                   7639: # set defaults for any optional args for which values were not supplied
                   7640:     if ($who eq '') {
                   7641:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7642:     }
                   7643:     if (!$locktries) {
                   7644:         $locktries = 3;
                   7645:     }
                   7646:     if (!$maxtries) {
                   7647:         $maxtries = 10;
                   7648:     }
                   7649: 
                   7650:     if (($cdom eq '') || ($cnum eq '')) {
                   7651:         if ($env{'request.course.id'}) {
                   7652:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7653:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7654:         }
                   7655:         if (($cdom eq '') || ($cnum eq '')) {
                   7656:             return ('','ok','call to get suffix not in course context');
                   7657:         }
                   7658:     }
                   7659: 
                   7660: # construct locking item
                   7661:     my $lockhash = {
                   7662:                       $prefix."\0".'locked_'.$keyid => $who,
                   7663:                    };
                   7664:     my $tries = 0;
                   7665: 
                   7666: # attempt to get lock on nohist_$namespace file
                   7667:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7668:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7669:         $tries ++;
                   7670:         sleep 1;
                   7671:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7672:     }
                   7673: 
                   7674: # attempt to get unique identifier, based on current timestamp
                   7675:     if ($gotlock eq 'ok') {
                   7676:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7677:         my $id = time;
                   7678:         $newid = $id;
1.1172.2.56  raeburn  7679:         if ($idtype eq 'addcode') {
                   7680:             $newid .= &sixnum_code();
                   7681:         }
1.1172.2.13  raeburn  7682:         my $idtries = 0;
                   7683:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7684:             if ($idtype eq 'concat') {
                   7685:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7686:             } elsif ($idtype eq 'addcode') {
                   7687:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7688:             } else {
                   7689:                 $newid ++;
                   7690:             }
                   7691:             $idtries ++;
                   7692:         }
                   7693:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7694:             my %new_item =  (
                   7695:                               $prefix."\0".$newid => $who,
                   7696:                             );
                   7697:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7698:                                                  $cdom,$cnum);
                   7699:             if ($putresult ne 'ok') {
                   7700:                 undef($newid);
                   7701:                 $error = 'error saving new item: '.$putresult;
                   7702:             }
                   7703:         } else {
1.1172.2.56  raeburn  7704:              undef($newid);
1.1172.2.13  raeburn  7705:              $error = ('error: no unique suffix available for the new item ');
                   7706:         }
                   7707: #  remove lock
                   7708:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7709:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7710:     } else {
                   7711:         $error = "error: could not obtain lockfile\n";
                   7712:         $dellock = 'ok';
1.1172.2.58  raeburn  7713:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7714:             $dellock = 'nolock';
                   7715:         }
1.1172.2.13  raeburn  7716:     }
                   7717:     return ($newid,$dellock,$error);
                   7718: }
                   7719: 
1.1172.2.56  raeburn  7720: sub sixnum_code {
                   7721:     my $code;
                   7722:     for (0..6) {
                   7723:         $code .= int( rand(9) );
                   7724:     }
                   7725:     return $code;
                   7726: }
                   7727: 
1.765     albertel 7728: # -------------------------------------------------- portfolio access checking
                   7729: 
                   7730: sub portfolio_access {
1.1172.2.77  raeburn  7731:     my ($requrl,$clientip) = @_;
1.765     albertel 7732:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7733:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7734:     if ($result) {
                   7735:         my %setters;
                   7736:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142  raeburn  7737:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7738:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
                   7739:             if (($startblock && $endblock) || ($by_ip))  {
1.814     raeburn  7740:                 return 'B';
                   7741:             }
                   7742:         } else {
1.1172.2.142  raeburn  7743:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
                   7744:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7745:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7746:                 return 'B';
                   7747:             }
                   7748:         }
                   7749:     }
1.765     albertel 7750:     if ($result eq 'ok') {
1.766     albertel 7751:        return 'F';
1.765     albertel 7752:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7753:        return 'A';
1.765     albertel 7754:     }
1.766     albertel 7755:     return '';
1.765     albertel 7756: }
                   7757: 
                   7758: sub get_portfolio_access {
1.1172.2.77  raeburn  7759:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7760: 
                   7761:     if (!ref($access_hash)) {
                   7762: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7763: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7764: 						   $file_name);
                   7765: 	$access_hash = $access_controls{$file_name};
                   7766:     }
                   7767: 
1.1172.2.77  raeburn  7768:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7769:     my $now = time;
                   7770:     if (ref($access_hash) eq 'HASH') {
                   7771:         foreach my $key (keys(%{$access_hash})) {
                   7772:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7773:             if ($start > $now) {
                   7774:                 next;
                   7775:             }
                   7776:             if ($end && $end<$now) {
                   7777:                 next;
                   7778:             }
                   7779:             if ($scope eq 'public') {
                   7780:                 $public = $key;
                   7781:                 last;
                   7782:             } elsif ($scope eq 'guest') {
                   7783:                 $guest = $key;
                   7784:             } elsif ($scope eq 'domains') {
                   7785:                 push(@domains,$key);
                   7786:             } elsif ($scope eq 'users') {
                   7787:                 push(@users,$key);
                   7788:             } elsif ($scope eq 'course') {
                   7789:                 push(@courses,$key);
                   7790:             } elsif ($scope eq 'group') {
                   7791:                 push(@groups,$key);
1.1172.2.77  raeburn  7792:             } elsif ($scope eq 'ip') {
                   7793:                 push(@ips,$key);
1.765     albertel 7794:             }
                   7795:         }
                   7796:         if ($public) {
                   7797:             return 'ok';
1.1172.2.77  raeburn  7798:         } elsif (@ips > 0) {
                   7799:             my $allowed;
                   7800:             foreach my $ipkey (@ips) {
                   7801:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7802:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7803:                         $allowed = 1;
                   7804:                         last;
                   7805:                     }
                   7806:                 }
                   7807:             }
                   7808:             if ($allowed) {
                   7809:                 return 'ok';
                   7810:             }
1.765     albertel 7811:         }
                   7812:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7813:             if ($guest) {
                   7814:                 return $guest;
                   7815:             }
                   7816:         } else {
                   7817:             if (@domains > 0) {
                   7818:                 foreach my $domkey (@domains) {
                   7819:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7820:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7821:                             return 'ok';
                   7822:                         }
                   7823:                     }
                   7824:                 }
                   7825:             }
                   7826:             if (@users > 0) {
                   7827:                 foreach my $userkey (@users) {
1.865     raeburn  7828:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7829:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7830:                             if (ref($item) eq 'HASH') {
                   7831:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7832:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7833:                                     return 'ok';
                   7834:                                 }
                   7835:                             }
                   7836:                         }
                   7837:                     } 
1.765     albertel 7838:                 }
                   7839:             }
                   7840:             my %roleshash;
                   7841:             my @courses_and_groups = @courses;
                   7842:             push(@courses_and_groups,@groups); 
                   7843:             if (@courses_and_groups > 0) {
                   7844:                 my (%allgroups,%allroles); 
                   7845:                 my ($start,$end,$role,$sec,$group);
                   7846:                 foreach my $envkey (%env) {
1.1060    raeburn  7847:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7848:                         my $cid = $2.'_'.$3; 
                   7849:                         if ($1 eq 'gr') {
                   7850:                             $group = $4;
                   7851:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7852:                         } else {
                   7853:                             if ($4 eq '') {
                   7854:                                 $sec = 'none';
                   7855:                             } else {
                   7856:                                 $sec = $4;
                   7857:                             }
                   7858:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7859:                         }
1.811     albertel 7860:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7861:                         my $cid = $2.'_'.$3;
                   7862:                         if ($4 eq '') {
                   7863:                             $sec = 'none';
                   7864:                         } else {
                   7865:                             $sec = $4;
                   7866:                         }
                   7867:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7868:                     }
                   7869:                 }
                   7870:                 if (keys(%allroles) == 0) {
                   7871:                     return;
                   7872:                 }
                   7873:                 foreach my $key (@courses_and_groups) {
                   7874:                     my %content = %{$$access_hash{$key}};
                   7875:                     my $cnum = $content{'number'};
                   7876:                     my $cdom = $content{'domain'};
                   7877:                     my $cid = $cdom.'_'.$cnum;
                   7878:                     if (!exists($allroles{$cid})) {
                   7879:                         next;
                   7880:                     }    
                   7881:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7882:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7883:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7884:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7885:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7886:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7887:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7888:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7889:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7890:                                         if (grep/^all$/,@sections) {
                   7891:                                             return 'ok';
                   7892:                                         } else {
                   7893:                                             if (grep/^$sec$/,@sections) {
                   7894:                                                 return 'ok';
                   7895:                                             }
                   7896:                                         }
                   7897:                                     }
                   7898:                                 }
                   7899:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7900:                                     if (grep/^none$/,@groups) {
                   7901:                                         return 'ok';
                   7902:                                     }
                   7903:                                 } else {
                   7904:                                     if (grep/^all$/,@groups) {
                   7905:                                         return 'ok';
                   7906:                                     } 
                   7907:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7908:                                         if (grep/^$group$/,@groups) {
                   7909:                                             return 'ok';
                   7910:                                         }
                   7911:                                     }
                   7912:                                 } 
                   7913:                             }
                   7914:                         }
                   7915:                     }
                   7916:                 }
                   7917:             }
                   7918:             if ($guest) {
                   7919:                 return $guest;
                   7920:             }
                   7921:         }
                   7922:     }
                   7923:     return;
                   7924: }
                   7925: 
                   7926: sub course_group_datechecker {
                   7927:     my ($dates,$now,$status) = @_;
                   7928:     my ($start,$end) = split(/\./,$dates);
                   7929:     if (!$start && !$end) {
                   7930:         return 'ok';
                   7931:     }
                   7932:     if (grep/^active$/,@{$status}) {
                   7933:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7934:             return 'ok';
                   7935:         }
                   7936:     }
                   7937:     if (grep/^previous$/,@{$status}) {
                   7938:         if ($end > $now ) {
                   7939:             return 'ok';
                   7940:         }
                   7941:     }
                   7942:     if (grep/^future$/,@{$status}) {
                   7943:         if ($start > $now) {
                   7944:             return 'ok';
                   7945:         }
                   7946:     }
                   7947:     return; 
                   7948: }
                   7949: 
                   7950: sub parse_portfolio_url {
                   7951:     my ($url) = @_;
                   7952: 
                   7953:     my ($type,$udom,$unum,$group,$file_name);
                   7954:     
1.823     albertel 7955:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7956: 	$type = 1;
                   7957:         $udom = $1;
                   7958:         $unum = $2;
                   7959:         $file_name = $3;
1.823     albertel 7960:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7961: 	$type = 2;
                   7962:         $udom = $1;
                   7963:         $unum = $2;
                   7964:         $group = $3;
                   7965:         $file_name = $3.'/'.$4;
                   7966:     }
                   7967:     if (wantarray) {
                   7968: 	return ($type,$udom,$unum,$file_name,$group);
                   7969:     }
                   7970:     return $type;
                   7971: }
                   7972: 
                   7973: sub is_portfolio_url {
                   7974:     my ($url) = @_;
                   7975:     return scalar(&parse_portfolio_url($url));
                   7976: }
                   7977: 
1.798     raeburn  7978: sub is_portfolio_file {
                   7979:     my ($file) = @_;
1.820     raeburn  7980:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7981:         return 1;
                   7982:     }
                   7983:     return;
                   7984: }
                   7985: 
1.1172.2.146.  .13(raeb 7986:-23): sub is_coursetool_logo {
                   7987:-23):     my ($uri) = @_;
                   7988:-23):     if ($env{'request.course.id'}) {
                   7989:-23):         my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   7990:-23):         if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
                   7991:-23):             return 1;
                   7992:-23):         }
                   7993:-23):     }
                   7994:-23):     return;
                   7995:-23): }
                   7996:-23): 
1.976     raeburn  7997: sub usertools_access {
1.1084    raeburn  7998:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7999:     my ($access,%tools);
                   8000:     if ($context eq '') {
                   8001:         $context = 'tools';
                   8002:     }
                   8003:     if ($context eq 'requestcourses') {
                   8004:         %tools = (
                   8005:                       official   => 1,
                   8006:                       unofficial => 1,
1.1006    raeburn  8007:                       community  => 1,
1.1172.2.37  raeburn  8008:                       textbook   => 1,
1.1172.2.146.  .13(raeb 8009:-23):                       lti        => 1,
1.985     raeburn  8010:                  );
1.1172.2.9  raeburn  8011:     } elsif ($context eq 'requestauthor') {
                   8012:         %tools = (
                   8013:                       requestauthor => 1,
                   8014:                  );
1.1172.2.146.  .18(raeb 8015:-24):     } elsif ($context eq 'authordefaults') {
                   8016:-24):         %tools = (
                   8017:-24):                       webdav    => 1,
                   8018:-24):                  );
1.985     raeburn  8019:     } else {
                   8020:         %tools = (
                   8021:                       aboutme   => 1,
                   8022:                       blog      => 1,
                   8023:                       portfolio => 1,
1.1172.2.146.  .6(raebu 8024:22):                       timezone  => 1,
1.985     raeburn  8025:                  );
                   8026:     }
1.976     raeburn  8027:     return if (!defined($tools{$tool}));
                   8028: 
1.1172.2.35  raeburn  8029:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  8030:         $udom = $env{'user.domain'};
                   8031:         $uname = $env{'user.name'};
                   8032:     }
                   8033: 
1.978     raeburn  8034:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   8035:         if ($action ne 'reload') {
1.985     raeburn  8036:             if ($context eq 'requestcourses') {
                   8037:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  8038:             } elsif ($context eq 'requestauthor') {
                   8039:                 return $env{'environment.canrequest.author'};
1.1172.2.146.  .18(raeb 8040:-24):             } elsif ($context eq 'authordefaults') {
                   8041:-24):                 if ($tool eq 'webdav') {
                   8042:-24):                     return $env{'environment.availabletools.'.$tool};
                   8043:-24):                 }
1.985     raeburn  8044:             } else {
                   8045:                 return $env{'environment.availabletools.'.$tool};
                   8046:             }
                   8047:         }
1.976     raeburn  8048:     }
                   8049: 
1.1172.2.9  raeburn  8050:     my ($toolstatus,$inststatus,$envkey);
                   8051:     if ($context eq 'requestauthor') {
                   8052:         $envkey = $context;
1.1172.2.146.  .18(raeb 8053:-24):     } elsif ($context eq 'authordefaults') {
                   8054:-24):         if ($tool eq 'webdav') {
                   8055:-24):             $envkey = 'tools.'.$tool;
                   8056:-24):         }
1.1172.2.9  raeburn  8057:     } else {
                   8058:         $envkey = $context.'.'.$tool;
                   8059:     }
1.976     raeburn  8060: 
1.985     raeburn  8061:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8062:          ($action ne 'reload')) {
1.1172.2.9  raeburn  8063:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  8064:         $inststatus = $env{'environment.inststatus'};
                   8065:     } else {
1.1084    raeburn  8066:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  8067:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  8068:             $inststatus = $userenvref->{'inststatus'};
                   8069:         } else {
1.1172.2.9  raeburn  8070:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   8071:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  8072:             $inststatus = $userenv{'inststatus'};
                   8073:         }
1.976     raeburn  8074:     }
                   8075: 
                   8076:     if ($toolstatus ne '') {
                   8077:         if ($toolstatus) {
                   8078:             $access = 1;
                   8079:         } else {
                   8080:             $access = 0;
                   8081:         }
                   8082:         return $access;
                   8083:     }
                   8084: 
1.1084    raeburn  8085:     my ($is_adv,%domdef);
                   8086:     if (ref($is_advref) eq 'HASH') {
                   8087:         $is_adv = $is_advref->{'is_adv'};
                   8088:     } else {
                   8089:         $is_adv = &is_advanced_user($udom,$uname);
                   8090:     }
                   8091:     if (ref($domdefref) eq 'HASH') {
                   8092:         %domdef = %{$domdefref};
                   8093:     } else {
                   8094:         %domdef = &get_domain_defaults($udom);
                   8095:     }
1.976     raeburn  8096:     if (ref($domdef{$tool}) eq 'HASH') {
                   8097:         if ($is_adv) {
                   8098:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   8099:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   8100:                     $access = 1;
                   8101:                 } else {
                   8102:                     $access = 0;
                   8103:                 }
                   8104:                 return $access;
                   8105:             }
                   8106:         }
                   8107:         if ($inststatus ne '') {
                   8108:             my ($hasaccess,$hasnoaccess);
                   8109:             foreach my $affiliation (split(/:/,$inststatus)) {
                   8110:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   8111:                     if ($domdef{$tool}{$affiliation}) {
                   8112:                         $hasaccess = 1;
                   8113:                     } else {
                   8114:                         $hasnoaccess = 1;
                   8115:                     }
                   8116:                 }
                   8117:             }
                   8118:             if ($hasaccess || $hasnoaccess) {
                   8119:                 if ($hasaccess) {
                   8120:                     $access = 1;
                   8121:                 } elsif ($hasnoaccess) {
                   8122:                     $access = 0; 
                   8123:                 }
                   8124:                 return $access;
                   8125:             }
                   8126:         } else {
                   8127:             if ($domdef{$tool}{'default'} ne '') {
                   8128:                 if ($domdef{$tool}{'default'}) {
                   8129:                     $access = 1;
                   8130:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   8131:                     $access = 0;
                   8132:                 }
                   8133:                 return $access;
                   8134:             }
                   8135:         }
                   8136:     } else {
1.1172.2.6  raeburn  8137:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  8138:             $access = 1;
                   8139:         } else {
                   8140:             $access = 0;
                   8141:         }
1.976     raeburn  8142:         return $access;
                   8143:     }
                   8144: }
                   8145: 
1.1050    raeburn  8146: sub is_course_owner {
                   8147:     my ($cdom,$cnum,$udom,$uname) = @_;
                   8148:     if (($udom eq '') || ($uname eq '')) {
                   8149:         $udom = $env{'user.domain'};
                   8150:         $uname = $env{'user.name'};
                   8151:     }
                   8152:     unless (($udom eq '') || ($uname eq '')) {
                   8153:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   8154:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   8155:                 return 1;
                   8156:             } else {
                   8157:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   8158:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   8159:                     return 1;
                   8160:                 }
                   8161:             }
                   8162:         }
                   8163:     }
                   8164:     return;
                   8165: }
                   8166: 
1.976     raeburn  8167: sub is_advanced_user {
                   8168:     my ($udom,$uname) = @_;
1.1085    raeburn  8169:     if ($udom ne '' && $uname ne '') {
                   8170:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  8171:             if (wantarray) {
                   8172:                 return ($env{'user.adv'},$env{'user.author'});
                   8173:             } else {
                   8174:                 return $env{'user.adv'};
                   8175:             }
1.1085    raeburn  8176:         }
                   8177:     }
1.976     raeburn  8178:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   8179:     my %allroles;
1.1128    raeburn  8180:     my ($is_adv,$is_author);
1.976     raeburn  8181:     foreach my $role (keys(%roleshash)) {
                   8182:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   8183:         my $area = '/'.$tdomain.'/'.$trest;
                   8184:         if ($sec ne '') {
                   8185:             $area .= '/'.$sec;
                   8186:         }
                   8187:         if (($area ne '') && ($trole ne '')) {
                   8188:             my $spec=$trole.'.'.$area;
                   8189:             if ($trole =~ /^cr\//) {
                   8190:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   8191:             } elsif ($trole ne 'gr') {
                   8192:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   8193:             }
1.1128    raeburn  8194:             if ($trole eq 'au') {
                   8195:                 $is_author = 1;
                   8196:             }
1.976     raeburn  8197:         }
                   8198:     }
                   8199:     foreach my $role (keys(%allroles)) {
                   8200:         last if ($is_adv);
                   8201:         foreach my $item (split(/:/,$allroles{$role})) {
                   8202:             if ($item ne '') {
                   8203:                 my ($privilege,$restrictions)=split(/&/,$item);
                   8204:                 if ($privilege eq 'adv') {
                   8205:                     $is_adv = 1;
                   8206:                     last;
                   8207:                 }
                   8208:             }
                   8209:         }
                   8210:     }
1.1128    raeburn  8211:     if (wantarray) {
                   8212:         return ($is_adv,$is_author);
                   8213:     }
1.976     raeburn  8214:     return $is_adv;
                   8215: }
1.798     raeburn  8216: 
1.1035    raeburn  8217: sub check_can_request {
1.1172.2.146.  .13(raeb 8218:-23):     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  8219:     my $canreq = 0;
1.1172.2.146.  .13(raeb 8220:-23):     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8221:-23):         $uname = $env{'user.name'};
                   8222:-23):         $udom = $env{'user.domain'};
                   8223:-23):     }
1.1035    raeburn  8224:     my ($types,$typename) = &Apache::loncommon::course_types();
                   8225:     my @options = ('approval','validate','autolimit');
                   8226:     my $optregex = join('|',@options);
                   8227:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   8228:         foreach my $type (@{$types}) {
1.1172.2.146.  .13(raeb 8229:-23):             if (&usertools_access($uname,$udom,$type,undef,
                   8230:-23):                                   'requestcourses')) {
1.1035    raeburn  8231:                 $canreq ++;
1.1036    raeburn  8232:                 if (ref($request_domains) eq 'HASH') {
1.1172.2.146.  .13(raeb 8233:-23):                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  8234:                 }
1.1172.2.146.  .13(raeb 8235:-23):                 if ($dom eq $udom) {
1.1035    raeburn  8236:                     $can_request->{$type} = 1;
                   8237:                 }
                   8238:             }
1.1172.2.146.  .13(raeb 8239:-23):             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   8240:-23):                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  8241:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   8242:                 if (@curr > 0) {
1.1036    raeburn  8243:                     foreach my $item (@curr) {
                   8244:                         if (ref($request_domains) eq 'HASH') {
                   8245:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   8246:                             if ($otherdom ne '') {
                   8247:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   8248:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   8249:                                         push(@{$request_domains->{$type}},$otherdom);
                   8250:                                     }
                   8251:                                 } else {
                   8252:                                     push(@{$request_domains->{$type}},$otherdom);
                   8253:                                 }
                   8254:                             }
                   8255:                         }
                   8256:                     }
1.1172.2.146.  .13(raeb 8257:-23):                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  8258:                         $canreq ++;
1.1035    raeburn  8259:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   8260:                             $can_request->{$type} = 1;
                   8261:                         }
                   8262:                     }
                   8263:                 }
                   8264:             }
                   8265:         }
                   8266:     }
                   8267:     return $canreq;
                   8268: }
                   8269: 
1.341     www      8270: # ---------------------------------------------- Custom access rule evaluation
                   8271: 
                   8272: sub customaccess {
                   8273:     my ($priv,$uri)=@_;
1.807     albertel 8274:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      8275:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 8276:     $udom = &LONCAPA::clean_domain($udom);
                   8277:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      8278:     my $access=0;
1.800     albertel 8279:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 8280: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   8281: 	if ($type eq 'user') {
                   8282: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 8283: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 8284: 		if ($tdom) {
                   8285: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   8286: 		}
1.896     albertel 8287: 		if ($tuname) {
                   8288: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 8289: 		}
                   8290: 		$access=($effect eq 'allow');
                   8291: 		last;
                   8292: 	    }
                   8293: 	} else {
                   8294: 	    if ($role) {
                   8295: 		if ($role ne $urole) { next; }
                   8296: 	    }
                   8297: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   8298: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   8299: 		if ($tdom) {
                   8300: 		    if ($tdom ne $udom) { next; }
                   8301: 		}
                   8302: 		if ($tcrs) {
                   8303: 		    if ($tcrs ne $ucrs) { next; }
                   8304: 		}
                   8305: 		if ($tsec) {
                   8306: 		    if ($tsec ne $usec) { next; }
                   8307: 		}
                   8308: 		$access=($effect eq 'allow');
                   8309: 		last;
                   8310: 	    }
                   8311: 	    if ($realm eq '' && $role eq '') {
                   8312: 		$access=($effect eq 'allow');
                   8313: 	    }
1.402     bowersj2 8314: 	}
1.341     www      8315:     }
                   8316:     return $access;
                   8317: }
                   8318: 
1.103     harris41 8319: # ------------------------------------------------- Check for a user privilege
1.12      www      8320: 
                   8321: sub allowed {
1.1172.2.146.  .1(raebu 8322:22):     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705     albertel 8323:     my $ver_orguri=$uri;
1.439     www      8324:     $uri=&deversion($uri);
1.152     www      8325:     my $orguri=$uri;
1.52      www      8326:     $uri=&declutter($uri);
1.809     raeburn  8327: 
1.810     raeburn  8328:     if ($priv eq 'evb') {
1.1172.2.146.  .3(raebu 8329:22): # Evade communication block restrictions for specified role in a course or domain
1.810     raeburn  8330:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   8331:             return $1;
                   8332:         } else {
                   8333:             return;
                   8334:         }
                   8335:     }
                   8336: 
1.620     albertel 8337:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      8338: # Free bre access to adm and meta resources
1.1172.2.146.  .1(raebu 8339:22):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 8340: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   8341: 	&& ($priv eq 'bre')) {
1.14      www      8342: 	return 'F';
1.159     www      8343:     }
                   8344: 
1.545     banghart 8345: # Free bre access to user's own portfolio contents
1.714     raeburn  8346:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  8347:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  8348: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8349:         my %setters;
1.1172.2.142  raeburn  8350:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   8351:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   8352:         if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  8353:             return 'B';
                   8354:         } else {
                   8355:             return 'F';
                   8356:         }
1.545     banghart 8357:     }
                   8358: 
1.762     raeburn  8359: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8360:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8361:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8362:         if (exists($env{'request.course.id'})) {
                   8363:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8364:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8365:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8366:                 my $courseprivid=$env{'request.course.id'};
                   8367:                 $courseprivid=~s/\_/\//;
                   8368:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8369:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8370:                     return $1; 
1.762     raeburn  8371:                 } else {
                   8372:                     if ($env{'request.course.sec'}) {
                   8373:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8374:                     }
                   8375:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8376:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8377:                         return $2;
                   8378:                     }
1.714     raeburn  8379:                 }
                   8380:             }
                   8381:         }
                   8382:     }
                   8383: 
1.159     www      8384: # Free bre to public access
                   8385: 
                   8386:     if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8387:22):         my $copyright;
                   8388:22):         unless ($uri =~ /ext\.tool/) {
                   8389:22):             $copyright=&metadata($uri,'copyright');
                   8390:22):         }
1.620     albertel 8391: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8392:            return 'F'; 
                   8393:         }
1.238     www      8394:         if ($copyright eq 'priv') {
                   8395:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8396: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8397: 		return '';
                   8398:             }
                   8399:         }
                   8400:         if ($copyright eq 'domain') {
                   8401:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8402: 	    unless (($env{'user.domain'} eq $1) ||
                   8403:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8404: 		return '';
                   8405:             }
1.262     matthew  8406:         }
1.620     albertel 8407:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8408:             # Library role, so allow browsing of resources in this domain.
                   8409:             return 'F';
1.238     www      8410:         }
1.341     www      8411:         if ($copyright eq 'custom') {
                   8412: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8413:         }
1.14      www      8414:     }
1.264     matthew  8415:     # Domain coordinator is trying to create a course
1.620     albertel 8416:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8417:         # uri is the requested domain in this case.
                   8418:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8419:         # a role of dc for the domain in question.
1.620     albertel 8420:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8421:     }
1.29      www      8422: 
1.52      www      8423:     my $thisallowed='';
                   8424:     my $statecond=0;
                   8425:     my $courseprivid='';
                   8426: 
1.1039    raeburn  8427:     my $ownaccess;
1.1043    raeburn  8428:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8429:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8430:         if ($uri eq '') {
                   8431:             $ownaccess = 1;
                   8432:         } else {
                   8433:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8434:                 my $udom = $env{'user.domain'};
                   8435:                 my $uname = $env{'user.name'};
                   8436:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8437:                     $ownaccess = 1;
1.1040    raeburn  8438:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8439:                     unless ($uri =~ m{\.\./}) {
                   8440:                         $ownaccess = 1;
                   8441:                     }
                   8442:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8443:                     my $now = time;
                   8444:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8445:                         my $adom = $1;
                   8446:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8447:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142  raeburn  8448:                                 my ($start,$end) = split(/\./,$env{$key});
                   8449:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  8450:                                     $ownaccess = 1;
                   8451:                                     last;
                   8452:                                 }
                   8453:                             }
                   8454:                         }
                   8455:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8456:                         my $adom = $1;
                   8457:                         my $aname = $2;
1.1042    raeburn  8458:                         foreach my $role ('ca','aa') { 
                   8459:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8460:                                 my ($start,$end) =
1.1172.2.142  raeburn  8461:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8462:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8463:                                     $ownaccess = 1;
                   8464:                                     last;
                   8465:                                 }
1.1039    raeburn  8466:                             }
                   8467:                         }
                   8468:                     }
                   8469:                 }
                   8470:             }
                   8471:         }
                   8472:     }
                   8473: 
1.52      www      8474: # Course
                   8475: 
1.620     albertel 8476:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8477:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8478:             $thisallowed.=$1;
                   8479:         }
1.52      www      8480:     }
1.29      www      8481: 
1.52      www      8482: # Domain
                   8483: 
1.620     albertel 8484:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8485:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8486:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8487:             $thisallowed.=$1;
                   8488:         }
1.12      www      8489:     }
1.52      www      8490: 
1.1141    raeburn  8491: # User who is not author or co-author might still be able to edit
                   8492: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8493:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8494:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8495:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8496:             $thisallowed.=$1;
                   8497:         }
                   8498:     }
                   8499: 
1.52      www      8500: # Course: uri itself is a course
1.66      www      8501:     my $courseuri=$uri;
                   8502:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8503:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8504: 
1.620     albertel 8505:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8506:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8507:         if ($priv eq 'mip') {
                   8508:             my $rem = $1;
                   8509:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8510:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8511:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8512:                 if ($cdom ne '') {
                   8513:                     my %passwdconf = &get_passwdconf($cdom);
                   8514:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8515:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8516:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8517:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8518:                                 unless (@inststatuses) {
                   8519:                                     @inststatuses = ('default');
                   8520:                                 }
                   8521:                                 foreach my $status (@inststatuses) {
                   8522:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8523:                                         $thisallowed.=$rem;
                   8524:                                     }
                   8525:                                 }
                   8526:                             }
                   8527:                         }
                   8528:                     }
                   8529:                 }
                   8530:             }
                   8531:         } else {
                   8532:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8533:                 $thisallowed.=$1;
                   8534:             }
1.1039    raeburn  8535:         }
1.12      www      8536:     }
1.29      www      8537: 
1.665     albertel 8538: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8539: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8540:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8541: 	$thisallowed='';
1.671     raeburn  8542:         my ($match)=&is_on_map($uri);
                   8543:         if ($match) {
                   8544:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8545:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8546:                 my $value = $1;
1.1172.2.146.  .1(raebu 8547:22):                 my $deeplinkblock;
                   8548:22):                 unless ($nodeeplinkcheck) {
                   8549:22):                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8550:22):                 }
                   8551:22):                 if ($deeplinkblock) {
                   8552:22):                     $thisallowed='D';
                   8553:22):                 } elsif ($noblockcheck) {
1.1172.2.65  raeburn  8554:                     $thisallowed.=$value;
1.1162    raeburn  8555:                 } else {
1.1172.2.126  raeburn  8556:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8557:                     if (@blockers > 0) {
                   8558:                         $thisallowed = 'B';
                   8559:                     } else {
                   8560:                         $thisallowed.=$value;
                   8561:                     }
1.1162    raeburn  8562:                 }
1.671     raeburn  8563:             }
                   8564:         } else {
1.705     albertel 8565:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8566:             if ($refuri) {
                   8567:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8568:                     $thisallowed='F';
1.671     raeburn  8569:                 } else {
                   8570:                     $refuri=&declutter($refuri);
                   8571:                     my ($match) = &is_on_map($refuri);
                   8572:                     if ($match) {
1.1172.2.146.  .1(raebu 8573:22):                         my $deeplinkblock;
                   8574:22):                         unless ($nodeeplinkcheck) {
                   8575:22):                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8576:22):                         }
                   8577:22):                         if ($deeplinkblock) {
                   8578:22):                             $thisallowed='D';
                   8579:22):                         } elsif ($noblockcheck) {
1.1162    raeburn  8580:                             $thisallowed='F';
1.1172.2.65  raeburn  8581:                         } else {
1.1172.2.127  raeburn  8582:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8583:                             if (@blockers > 0) {
                   8584:                                 $thisallowed = 'B';
                   8585:                             } else {
                   8586:                                 $thisallowed='F';
                   8587:                             }
1.1162    raeburn  8588:                         }
1.671     raeburn  8589:                     }
1.669     raeburn  8590:                 }
1.671     raeburn  8591:             }
                   8592:         }
1.314     www      8593:     }
1.492     albertel 8594: 
1.766     albertel 8595:     if ($priv eq 'bre'
                   8596: 	&& $thisallowed ne 'F' 
                   8597: 	&& $thisallowed ne '2'
                   8598: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8599: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8600:     }
                   8601:     
1.52      www      8602: # Full access at system, domain or course-wide level? Exit.
1.29      www      8603:     if ($thisallowed=~/F/) {
                   8604: 	return 'F';
                   8605:     }
                   8606: 
1.52      www      8607: # If this is generating or modifying users, exit with special codes
1.29      www      8608: 
1.643     www      8609:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8610: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8611: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8612: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8613: 	    unless ($auname) { return $thisallowed; }
                   8614: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8615: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8616: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8617: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8618: 	}
1.52      www      8619: 	return $thisallowed;
                   8620:     }
                   8621: #
1.103     harris41 8622: # Gathered so far: system, domain and course wide privileges
1.52      www      8623: #
                   8624: # Course: See if uri or referer is an individual resource that is part of 
                   8625: # the course
                   8626: 
1.620     albertel 8627:     if ($env{'request.course.id'}) {
1.232     www      8628: 
1.1172.2.146.  .13(raeb 8629:-23):         if ($priv eq 'bre') {
                   8630:-23):             if (&is_coursetool_logo($uri)) {
                   8631:-23):                 return 'F';
                   8632:-23):             }
                   8633:-23):         }
                   8634:-23): 
1.1172.2.115  raeburn  8635: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8636: 
                   8637:         if ($priv eq 'mip') {
                   8638:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8639:                 return $thisallowed;
                   8640:             } else {
                   8641:                 return '';
                   8642:             }
                   8643:         }
                   8644: 
1.620     albertel 8645:        $courseprivid=$env{'request.course.id'};
                   8646:        if ($env{'request.course.sec'}) {
                   8647:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8648:        }
                   8649:        $courseprivid=~s/\_/\//;
                   8650:        my $checkreferer=1;
1.232     www      8651:        my ($match,$cond)=&is_on_map($uri);
                   8652:        if ($match) {
                   8653:            $statecond=$cond;
1.620     albertel 8654:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8655:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8656:                my $value = $1;
                   8657:                if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8658:22):                    my $deeplinkblock;
                   8659:22):                    unless ($nodeeplinkcheck) {
                   8660:22):                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8661:22):                    }
                   8662:22):                    if ($deeplinkblock) {
                   8663:22):                        $thisallowed = 'D';
                   8664:22):                    } elsif ($noblockcheck) {
1.1162    raeburn  8665:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8666:                    } else {
1.1172.2.126  raeburn  8667:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8668:                        if (@blockers > 0) {
                   8669:                            $thisallowed = 'B';
                   8670:                        } else {
                   8671:                            $thisallowed.=$value;
                   8672:                        }
1.1162    raeburn  8673:                    }
                   8674:                } else {
                   8675:                    $thisallowed.=$value;
                   8676:                }
1.52      www      8677:                $checkreferer=0;
                   8678:            }
1.29      www      8679:        }
1.1172.2.126  raeburn  8680: 
1.148     www      8681:        if ($checkreferer) {
1.620     albertel 8682: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8683:             unless ($refuri) {
1.800     albertel 8684:                 foreach my $key (keys(%env)) {
                   8685: 		    if ($key=~/^httpref\..*\*/) {
                   8686: 			my $pattern=$key;
1.156     www      8687:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8688:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8689:                         $pattern=~s/\//\\\//g;
1.152     www      8690:                         if ($orguri=~/$pattern/) {
1.800     albertel 8691: 			    $refuri=$env{$key};
1.148     www      8692:                         }
                   8693:                     }
1.191     harris41 8694:                 }
1.148     www      8695:             }
1.232     www      8696: 
1.148     www      8697:          if ($refuri) { 
1.152     www      8698: 	  $refuri=&declutter($refuri);
1.232     www      8699:           my ($match,$cond)=&is_on_map($refuri);
                   8700:             if ($match) {
                   8701:               my $refstatecond=$cond;
1.620     albertel 8702:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8703:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8704:                   my $value = $1;
                   8705:                   if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8706:22):                       my $deeplinkblock;
                   8707:22):                       unless ($nodeeplinkcheck) {
                   8708:22):                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8709:22):                       }
                   8710:22):                       if ($deeplinkblock) {
                   8711:22):                           $thisallowed = 'D';
                   8712:22):                       } elsif ($noblockcheck) {
1.1162    raeburn  8713:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8714:                       } else {
1.1172.2.127  raeburn  8715:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8716:                           if (@blockers > 0) {
                   8717:                               $thisallowed = 'B';
                   8718:                           } else {
                   8719:                               $thisallowed.=$value;
                   8720:                           }
1.1162    raeburn  8721:                       }
                   8722:                   } else {
                   8723:                       $thisallowed.=$value;
                   8724:                   }
1.53      www      8725:                   $uri=$refuri;
                   8726:                   $statecond=$refstatecond;
1.52      www      8727:               }
                   8728:           }
1.148     www      8729:         }
1.29      www      8730:        }
1.52      www      8731:    }
1.29      www      8732: 
1.52      www      8733: #
1.103     harris41 8734: # Gathered now: all privileges that could apply, and condition number
1.52      www      8735: # 
                   8736: #
                   8737: # Full or no access?
                   8738: #
1.29      www      8739: 
1.52      www      8740:     if ($thisallowed=~/F/) {
                   8741: 	return 'F';
                   8742:     }
1.29      www      8743: 
1.52      www      8744:     unless ($thisallowed) {
                   8745:         return '';
                   8746:     }
1.29      www      8747: 
1.52      www      8748: # Restrictions exist, deal with them
                   8749: #
                   8750: #   C:according to course preferences
                   8751: #   R:according to resource settings
                   8752: #   L:unless locked
                   8753: #   X:according to user session state
                   8754: #
                   8755: 
                   8756: # Possibly locked functionality, check all courses
1.1172.2.142  raeburn  8757: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      8758: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142  raeburn  8759: # courses, and 2 minutes for current course, in which user has st or ta role
                   8760: # which is neither expired nor a future role (unless current course).
1.52      www      8761: 
1.1172.2.142  raeburn  8762:     my ($needlockcheck,$now,$crsonly);
1.52      www      8763:     if ($thisallowed=~/L/) {
1.1172.2.142  raeburn  8764:         $now = time;
                   8765:         if ($priv eq 'bre') {
                   8766:             if ($uri ne '') {
                   8767:                 if ($orguri =~ m{^/+res/}) {
                   8768:                     if ($uri =~ m{^lib/templates/}) {
                   8769:                         if ($env{'request.course.id'}) {
                   8770:                             $crsonly = 1;
                   8771:                             $needlockcheck = 1;
                   8772:                         }
                   8773:                     } else {
                   8774:                         $needlockcheck = 1;
                   8775:                     }
                   8776:                 } elsif ($env{'request.course.id'}) {
                   8777:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   8778:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   8779:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   8780:                         $crsonly = 1;
                   8781:                     }
                   8782:                     $needlockcheck = 1;
                   8783:                 }
                   8784:             }
                   8785:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   8786:             $needlockcheck = 1;
                   8787:         }
                   8788:     }
                   8789:     if ($needlockcheck) {
                   8790:         foreach my $envkey (keys(%env)) {
1.54      www      8791:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8792:                my $courseid=$2;
                   8793:                my $roleid=$1.'.'.$2;
1.92      www      8794:                $courseid=~s/^\///;
1.1172.2.142  raeburn  8795:                unless ($env{'request.role'} eq $roleid) {
                   8796:                    my ($start,$end) = split(/\./,$env{$envkey});
                   8797:                    next unless (($now >= $start) && (!$end || $end > $now));
                   8798:                }
1.54      www      8799:                my $expiretime=600;
1.620     albertel 8800:                if ($env{'request.role'} eq $roleid) {
1.54      www      8801: 		  $expiretime=120;
                   8802:                }
                   8803: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8804:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8805:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8806: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8807:                }
1.620     albertel 8808:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8809:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8810: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8811:                        &log($env{'user.domain'},$env{'user.name'},
                   8812:                             $env{'user.home'},
1.57      www      8813:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8814:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8815:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8816: 		       return '';
                   8817:                    }
                   8818:                }
1.620     albertel 8819:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8820:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142  raeburn  8821: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 8822:                        &log($env{'user.domain'},$env{'user.name'},
                   8823:                             $env{'user.home'},
1.57      www      8824:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8825:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8826:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8827: 		       return '';
                   8828:                    }
                   8829:                }
                   8830: 	   }
1.29      www      8831:        }
1.52      www      8832:     }
1.1172.2.126  raeburn  8833: 
1.52      www      8834: #
                   8835: # Rest of the restrictions depend on selected course
                   8836: #
                   8837: 
1.620     albertel 8838:     unless ($env{'request.course.id'}) {
1.766     albertel 8839: 	if ($thisallowed eq 'A') {
                   8840: 	    return 'A';
1.814     raeburn  8841:         } elsif ($thisallowed eq 'B') {
                   8842:             return 'B';
1.766     albertel 8843: 	} else {
                   8844: 	    return '1';
                   8845: 	}
1.52      www      8846:     }
1.29      www      8847: 
1.52      www      8848: #
                   8849: # Now user is definitely in a course
                   8850: #
1.53      www      8851: 
                   8852: 
                   8853: # Course preferences
                   8854: 
                   8855:    if ($thisallowed=~/C/) {
1.620     albertel 8856:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8857:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8858:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8859: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8860: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8861: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8862: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8863: 			$env{'request.course.id'});
                   8864: 	   }
1.237     www      8865:            return '';
                   8866:        }
                   8867: 
1.620     albertel 8868:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8869: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8870: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8871: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8872: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8873: 			$env{'request.course.id'});
                   8874: 	   }
1.54      www      8875:            return '';
                   8876:        }
1.53      www      8877:    }
                   8878: 
                   8879: # Resource preferences
                   8880: 
                   8881:    if ($thisallowed=~/R/) {
1.620     albertel 8882:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8883:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8884: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8885: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8886: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8887: 	   }
                   8888: 	   return '';
1.54      www      8889:        }
1.53      www      8890:    }
1.30      www      8891: 
1.1172.2.146.  .1(raebu 8892:22): # Restricted for deeplinked session?
                   8893:22): 
                   8894:22):     if ($env{'request.deeplink.login'}) {
                   8895:22):         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
                   8896:22):             if (!$symb) { $symb=&symbread($uri,1); }
                   8897:22):             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
                   8898:22):                 return '';
                   8899:22):             }
                   8900:22):         }
                   8901:22):     }
                   8902:22): 
1.246     www      8903: # Restricted by state or randomout?
1.30      www      8904: 
1.52      www      8905:    if ($thisallowed=~/X/) {
1.620     albertel 8906:       if ($env{'acc.randomout'}) {
1.579     albertel 8907: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8908:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8909:             return ''; 
                   8910:          }
1.247     www      8911:       }
                   8912:       if (&condval($statecond)) {
1.52      www      8913: 	 return '2';
                   8914:       } else {
                   8915:          return '';
                   8916:       }
                   8917:    }
1.30      www      8918: 
1.766     albertel 8919:     if ($thisallowed eq 'A') {
                   8920: 	return 'A';
1.814     raeburn  8921:     } elsif ($thisallowed eq 'B') {
                   8922:         return 'B';
1.1172.2.146.  .1(raebu 8923:22):     } elsif ($thisallowed eq 'D') {
                   8924:22):         return 'D';
1.766     albertel 8925:     }
1.52      www      8926:    return 'F';
1.232     www      8927: }
1.1162    raeburn  8928: 
1.1172.2.13  raeburn  8929: # ------------------------------------------- Check construction space access
                   8930: 
                   8931: sub constructaccess {
                   8932:     my ($url,$setpriv)=@_;
                   8933: 
                   8934: # We do not allow editing of previous versions of files
                   8935:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8936: 
                   8937: # Get username and domain from URL
                   8938:     my ($ownername,$ownerdomain,$ownerhome);
                   8939: 
                   8940:     ($ownerdomain,$ownername) =
1.1172.2.146.  .19(raeb 8941:-24):         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8942: 
                   8943: # The URL does not really point to any authorspace, forget it
                   8944:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8945: 
                   8946: # Now we need to see if the user has access to the authorspace of
                   8947: # $ownername at $ownerdomain
                   8948: 
                   8949:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8950: # Real author for this?
                   8951:        $ownerhome = $env{'user.home'};
                   8952:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8953:           return ($ownername,$ownerdomain,$ownerhome);
                   8954:        }
                   8955:     } else {
                   8956: # Co-author for this?
                   8957:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8958:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8959:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8960:             return ($ownername,$ownerdomain,$ownerhome);
                   8961:         }
                   8962:     }
                   8963: 
                   8964: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8965: # we might as well leave
                   8966:    unless ($setpriv) { return ''; }
                   8967: 
                   8968: # Backdoor access?
                   8969:     my $allowed=&allowed('eco',$ownerdomain);
                   8970: # Nope
                   8971:     unless ($allowed) { return ''; }
                   8972: # Looks like we may have access, but could be locked by the owner of the construction space
                   8973:     if ($allowed eq 'U') {
                   8974:         my %blocked=&get('environment',['domcoord.author'],
                   8975:                          $ownerdomain,$ownername);
                   8976: # Is blocked by owner
                   8977:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8978:     }
                   8979:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8980: # Grant temporary access
                   8981:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8982:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8983:         if (!$update) { $update = $then; }
                   8984:         my $refresh=$env{'user.refresh.time'};
                   8985:         if (!$refresh) { $refresh = $update; }
                   8986:         my $now = time;
                   8987:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8988:                            $now,'ca','constructaccess');
                   8989:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8990:         return($ownername,$ownerdomain,$ownerhome);
                   8991:     }
                   8992: # No business here
                   8993:     return '';
                   8994: }
                   8995: 
1.1172.2.66  raeburn  8996: # ----------------------------------------------------------- Content Blocking
                   8997: 
                   8998: {
                   8999: # Caches for faster Course Contents display where content blocking
                   9000: # is in operation (i.e., interval param set) for timed quiz.
                   9001: #
                   9002: # User for whom data are being temporarily cached.
                   9003: my $cacheduser='';
1.1172.2.126  raeburn  9004: # Course for which data are being temporarily cached.
                   9005: my $cachedcid='';
1.1172.2.66  raeburn  9006: # Cached blockers for this user (a hash of blocking items).
                   9007: my %cachedblockers=();
                   9008: # When the data were last cached.
                   9009: my $cachedlast='';
                   9010: 
                   9011: sub load_all_blockers {
1.1172.2.128  raeburn  9012:     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  9013:     if (($uname ne '') && ($udom ne '')) {
                   9014:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126  raeburn  9015:             ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128  raeburn  9016:             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  9017:             return;
                   9018:         }
                   9019:     }
                   9020:     $cachedlast=time;
                   9021:     $cacheduser=$uname.':'.$udom;
1.1172.2.126  raeburn  9022:     $cachedcid=$env{'request.course.id'};
1.1172.2.128  raeburn  9023:     %cachedblockers = &get_commblock_resources();
1.1172.2.126  raeburn  9024:     return;
1.1172.2.66  raeburn  9025: }
                   9026: 
1.1162    raeburn  9027: sub get_comm_blocks {
                   9028:     my ($cdom,$cnum) = @_;
                   9029:     if ($cdom eq '' || $cnum eq '') {
                   9030:         return unless ($env{'request.course.id'});
                   9031:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9032:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9033:     }
                   9034:     my %commblocks;
                   9035:     my $hashid=$cdom.'_'.$cnum;
                   9036:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   9037:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   9038:         %commblocks = %{$blocksref};
                   9039:     } else {
                   9040:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   9041:         my $cachetime = 600;
                   9042:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   9043:     }
                   9044:     return %commblocks;
                   9045: }
                   9046: 
1.1172.2.66  raeburn  9047: sub get_commblock_resources {
                   9048:     my ($blocks) = @_;
                   9049:     my %blockers = ();
                   9050:     return %blockers unless ($env{'request.course.id'});
1.1172.2.142  raeburn  9051:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   9052:     if ($env{'request.course.sec'}) {
                   9053:         $courseurl .= '/'.$env{'request.course.sec'};
                   9054:     }
                   9055:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  9056:     my %commblocks;
                   9057:     if (ref($blocks) eq 'HASH') {
                   9058:         %commblocks = %{$blocks};
                   9059:     } else {
                   9060:         %commblocks = &get_comm_blocks();
                   9061:     }
1.1172.2.66  raeburn  9062:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  9063:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  9064:     return %blockers unless (ref($navmap));
                   9065:     my $now = time;
1.1162    raeburn  9066:     foreach my $block (keys(%commblocks)) {
                   9067:         if ($block =~ /^(\d+)____(\d+)$/) {
                   9068:             my ($start,$end) = ($1,$2);
                   9069:             if ($start <= $now && $end >= $now) {
                   9070:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   9071:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   9072:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  9073:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   9074:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  9075:                             }
                   9076:                         }
                   9077:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  9078:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   9079:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  9080:                             }
                   9081:                         }
                   9082:                     }
                   9083:                 }
                   9084:             }
                   9085:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   9086:             my $item = $1;
                   9087:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   9088:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142  raeburn  9089:                     my (@interval,$mapname);
1.1172.2.66  raeburn  9090:                     my $type = 'map';
                   9091:                     if ($item eq 'course') {
                   9092:                         $type = 'course';
                   9093:                         @interval=&EXT("resource.0.interval");
                   9094:                     } else {
                   9095:                         if ($item =~ /___\d+___/) {
                   9096:                             $type = 'resource';
                   9097:                             @interval=&EXT("resource.0.interval",$item);
1.1162    raeburn  9098:                         } else {
1.1172.2.142  raeburn  9099:                             $mapname = &deversion($item);
                   9100:                             if (ref($navmap)) {
                   9101:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
                   9102:                                 @interval = ($timelimit,'map');
1.1162    raeburn  9103:                             }
                   9104:                         }
1.1172.2.66  raeburn  9105:                     }
1.1172.2.146.  .1(raebu 9106:22):                     if ($interval[0] =~ /^(\d+)/) {
                   9107:22):                         my $timelimit = $1;
1.1172.2.66  raeburn  9108:                         my $first_access;
                   9109:                         if ($type eq 'resource') {
                   9110:                             $first_access=&get_first_access($interval[1],$item);
                   9111:                         } elsif ($type eq 'map') {
                   9112:                             $first_access=&get_first_access($interval[1],undef,$item);
                   9113:                         } else {
                   9114:                             $first_access=&get_first_access($interval[1]);
                   9115:                         }
                   9116:                         if ($first_access) {
1.1172.2.146.  .1(raebu 9117:22):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  9118:                             if ($timesup > $now) {
                   9119:                                 my $activeblock;
1.1172.2.142  raeburn  9120:                                 if ($type eq 'resource') {
                   9121:                                     if (ref($navmap)) {
                   9122:                                         my $res = $navmap->getBySymb($item);
                   9123:                                         if ($res->answerable()) {
                   9124:                                             $activeblock = 1;
                   9125:                                         }
                   9126:                                     }
                   9127:                                 } elsif ($type eq 'map') {
                   9128:                                     my $mapsymb = &symbread($mapname,1);
                   9129:                                     if (($mapsymb) && (ref($navmap))) {
                   9130:                                         my $mapres = $navmap->getBySymb($mapsymb);
                   9131:                                         if (ref($mapres)) {
                   9132:                                             my $first = $mapres->map_start();
                   9133:                                             my $finish = $mapres->map_finish();
                   9134:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   9135:                                             if (ref($it)) {
                   9136:                                                 my $res;
                   9137:                                                 while ($res = $it->next(undef,1)) {
                   9138:                                                     next unless (ref($res));
                   9139:                                                     my $symb = $res->symb();
                   9140:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
                   9141:                                                     @interval=&EXT("resource.0.interval",$symb);
                   9142:                                                     if ($interval[1] eq 'map') {
                   9143:                                                         if ($res->answerable()) {
                   9144:                                                             $activeblock = 1;
                   9145:                                                             last;
                   9146:                                                         }
                   9147:                                                     }
                   9148:                                                 }
                   9149:                                             }
                   9150:                                         }
1.1172.2.66  raeburn  9151:                                     }
                   9152:                                 }
                   9153:                                 if ($activeblock) {
                   9154:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   9155:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   9156:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   9157:                                          }
                   9158:                                     }
                   9159:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   9160:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   9161:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  9162:                                         }
1.1162    raeburn  9163:                                     }
                   9164:                                 }
                   9165:                             }
                   9166:                         }
                   9167:                     }
                   9168:                 }
                   9169:             }
                   9170:         }
                   9171:     }
1.1172.2.66  raeburn  9172:     return %blockers;
1.1162    raeburn  9173: }
                   9174: 
1.1172.2.66  raeburn  9175: sub has_comm_blocking {
1.1172.2.128  raeburn  9176:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  9177:     my @blockers;
                   9178:     return unless ($env{'request.course.id'});
                   9179:     return unless ($priv eq 'bre');
                   9180:     return if ($env{'request.state'} eq 'construct');
1.1172.2.142  raeburn  9181:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   9182:     if ($env{'request.course.sec'}) {
                   9183:         $courseurl .= '/'.$env{'request.course.sec'};
                   9184:     }
                   9185:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128  raeburn  9186:     my %blockinfo;
                   9187:     if (ref($blocks) eq 'HASH') {
                   9188:         %blockinfo = &get_commblock_resources($blocks);
                   9189:     } else {
                   9190:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   9191:         %blockinfo = %cachedblockers;
                   9192:     }
                   9193:     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  9194:     my (%possibles,@symbs);
                   9195:     if (!$symb) {
1.1172.2.128  raeburn  9196:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  9197:     }
1.1172.2.66  raeburn  9198:     if ($symb) {
                   9199:         @symbs = ($symb);
                   9200:     } elsif (keys(%possibles)) {
                   9201:         @symbs = keys(%possibles);
                   9202:     }
                   9203:     my $noblock;
                   9204:     foreach my $symb (@symbs) {
                   9205:         last if ($noblock);
                   9206:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128  raeburn  9207:         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  9208:             if ($block =~ /^firstaccess____(.+)$/) {
                   9209:                 my $item = $1;
1.1172.2.126  raeburn  9210:                 unless ($blocked) {
                   9211:                     if (($item eq $map) || ($item eq $symb)) {
                   9212:                         $noblock = 1;
                   9213:                         last;
                   9214:                     }
1.1172.2.66  raeburn  9215:                 }
1.1162    raeburn  9216:             }
1.1172.2.128  raeburn  9217:             if (ref($blockinfo{$block}) eq 'HASH') {
                   9218:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   9219:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  9220:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9221:                             push(@blockers,$block);
                   9222:                         }
                   9223:                     }
                   9224:                 }
1.1172.2.128  raeburn  9225:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   9226:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126  raeburn  9227:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9228:                             push(@blockers,$block);
                   9229:                         }
1.1172.2.66  raeburn  9230:                     }
                   9231:                 }
1.1162    raeburn  9232:             }
                   9233:         }
                   9234:     }
1.1172.2.126  raeburn  9235:     unless ($noblock) {
                   9236:         return @blockers;
                   9237:     }
                   9238:     return;
1.1172.2.66  raeburn  9239: }
1.1162    raeburn  9240: }
                   9241: 
1.1172.2.146.  .1(raebu 9242:22): sub deeplink_check {
                   9243:22):     my ($priv,$symb,$uri) = @_;
                   9244:22):     return unless ($env{'request.course.id'});
                   9245:22):     return unless ($priv eq 'bre');
                   9246:22):     return if ($env{'request.state'} eq 'construct');
                   9247:22):     return if ($env{'request.role.adv'});
                   9248:22):     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9249:22):     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9250:22):     my (%possibles,@symbs);
                   9251:22):     if (!$symb) {
                   9252:22):         $symb = &symbread($uri,1,1,1,\%possibles);
                   9253:22):     }
                   9254:22):     if ($symb) {
                   9255:22):         @symbs = ($symb);
                   9256:22):     } elsif (keys(%possibles)) {
                   9257:22):         @symbs = keys(%possibles);
                   9258:22):     }
                   9259:22): 
                   9260:22):     my ($deeplink_symb,$allow);
                   9261:22):     if ($env{'request.deeplink.login'}) {
                   9262:22):         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
                   9263:22):     }
                   9264:22):     foreach my $symb (@symbs) {
                   9265:22):         last if ($allow);
                   9266:22):         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   9267:22):         if ($deeplink eq '') {
                   9268:22):             $allow = 1;
                   9269:22):         } else {
                   9270:22):             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
                   9271:22):             if ($state ne 'only') {
                   9272:22):                 $allow = 1;
                   9273:22):             } else {
                   9274:22):                 my $check_deeplink_entry;
                   9275:22):                 if ($protect ne 'none') {
                   9276:22):                     my ($acctype,$item) = split(/:/,$protect);
                   9277:22):                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
                   9278:22):                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
                   9279:22):                             $check_deeplink_entry = 1
                   9280:22):                         }
                   9281:22):                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
                   9282:22):                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
                   9283:22):                             $check_deeplink_entry = 1;
                   9284:22):                         }
                   9285:22):                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   9286:22):                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   9287:22):                             $check_deeplink_entry = 1;
                   9288:22):                         }
                   9289:22):                     }
                   9290:22):                 }
                   9291:22):                 if (($protect eq 'none') || ($check_deeplink_entry)) {
                   9292:22):                     if ($scope eq 'res') {
                   9293:22):                         if ($symb eq $deeplink_symb) {
                   9294:22):                             $allow = 1;
                   9295:22):                         }
                   9296:22):                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
                   9297:22):                         my ($map_from_symb,$map_from_login);
                   9298:22):                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
                   9299:22):                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9300:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
                   9301:22):                         } else {
                   9302:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
                   9303:22):                         }
                   9304:22):                         if (($map_from_symb) && ($map_from_login)) {
                   9305:22):                             if ($map_from_symb eq $map_from_login) {
                   9306:22):                                 $allow = 1;
                   9307:22):                             } elsif ($scope eq 'rec') {
                   9308:22):                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
                   9309:22):                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
                   9310:22):                                     $allow = 1;
                   9311:22):                                 }
                   9312:22):                             }
                   9313:22):                         }
                   9314:22):                     }
                   9315:22):                 }
                   9316:22):             }
                   9317:22):         }
                   9318:22):     }
                   9319:22):     return if ($allow);
                   9320:22):     return 1;
                   9321:22): }
                   9322:22): 
1.1172.2.66  raeburn  9323: # -------------------------------- Deversion and split uri into path an filename
                   9324: 
1.1133    foxr     9325: #
1.1172.2.66  raeburn  9326: #   Removes the version from a URI and
1.1133    foxr     9327: #   splits it in to its filename and path to the filename.
                   9328: #   Seems like File::Basename could have done this more clearly.
                   9329: #   Parameters:
                   9330: #      $uri   - input URI
                   9331: #   Returns:
                   9332: #     Two element list consisting of 
                   9333: #     $pathname  - the URI up to and excluding the trailing /
                   9334: #     $filename  - The part of the URI following the last /
                   9335: #  NOTE:
                   9336: #    Another realization of this is simply:
                   9337: #    use File::Basename;
                   9338: #    ...
                   9339: #    $uri = shift;
                   9340: #    $filename = basename($uri);
                   9341: #    $path     = dirname($uri);
                   9342: #    return ($filename, $path);
                   9343: #
                   9344: #     The implementation below is probably faster however.
                   9345: #
1.710     albertel 9346: sub split_uri_for_cond {
                   9347:     my $uri=&deversion(&declutter(shift));
                   9348:     my @uriparts=split(/\//,$uri);
                   9349:     my $filename=pop(@uriparts);
                   9350:     my $pathname=join('/',@uriparts);
                   9351:     return ($pathname,$filename);
                   9352: }
1.232     www      9353: # --------------------------------------------------- Is a resource on the map?
                   9354: 
                   9355: sub is_on_map {
1.710     albertel 9356:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 9357:     #Trying to find the conditional for the file
1.620     albertel 9358:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 9359: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      9360:     if ($match) {
1.289     bowersj2 9361: 	return (1,$1);
                   9362:     } else {
1.434     www      9363: 	return (0,0);
1.289     bowersj2 9364:     }
1.12      www      9365: }
                   9366: 
1.427     www      9367: # --------------------------------------------------------- Get symb from alias
                   9368: 
                   9369: sub get_symb_from_alias {
                   9370:     my $symb=shift;
                   9371:     my ($map,$resid,$url)=&decode_symb($symb);
                   9372: # Already is a symb
                   9373:     if ($url) { return $symb; }
                   9374: # Must be an alias
                   9375:     my $aliassymb='';
                   9376:     my %bighash;
1.620     albertel 9377:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      9378:                             &GDBM_READER(),0640)) {
                   9379:         my $rid=$bighash{'mapalias_'.$symb};
                   9380: 	if ($rid) {
                   9381: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 9382: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   9383: 				    $resid,$bighash{'src_'.$rid});
1.427     www      9384: 	}
                   9385:         untie %bighash;
                   9386:     }
                   9387:     return $aliassymb;
                   9388: }
                   9389: 
1.12      www      9390: # ----------------------------------------------------------------- Define Role
                   9391: 
                   9392: sub definerole {
                   9393:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  9394:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9395:     foreach my $role (split(':',$sysrole)) {
                   9396: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9397:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9398:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9399: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9400:                return "refused:s:$crole&$cqual"; 
                   9401:             }
                   9402:         }
1.191     harris41 9403:     }
1.800     albertel 9404:     foreach my $role (split(':',$domrole)) {
                   9405: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9406:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9407:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9408: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9409:                return "refused:d:$crole&$cqual"; 
                   9410:             }
                   9411:         }
1.191     harris41 9412:     }
1.800     albertel 9413:     foreach my $role (split(':',$courole)) {
                   9414: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9415:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9416:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9417: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9418:                return "refused:c:$crole&$cqual"; 
                   9419:             }
                   9420:         }
1.191     harris41 9421:     }
1.1172.2.84  raeburn  9422:     my $uhome;
                   9423:     if (($uname ne '') && ($udom ne '')) {
                   9424:         $uhome = &homeserver($uname,$udom);
                   9425:         return $uhome if ($uhome eq 'no_host');
                   9426:     } else {
                   9427:         $uname = $env{'user.name'};
                   9428:         $udom = $env{'user.domain'};
                   9429:         $uhome = $env{'user.home'};
                   9430:     }
1.620     albertel 9431:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  9432:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9433:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  9434:     return reply($command,$uhome);
1.12      www      9435:   } else {
                   9436:     return 'refused';
                   9437:   }
1.105     harris41 9438: }
                   9439: 
                   9440: # ---------------- Make a metadata query against the network of library servers
                   9441: 
                   9442: sub metadata_query {
1.1172.2.33  raeburn  9443:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9444:     my %rhash;
1.845     albertel 9445:     my %libserv = &all_library();
1.244     matthew  9446:     my @server_list = (defined($server_array) ? @$server_array
                   9447:                                               : keys(%libserv) );
                   9448:     for my $server (@server_list) {
1.1172.2.33  raeburn  9449:         my $domains = '';
                   9450:         if (ref($domains_hash) eq 'HASH') {
                   9451:             $domains = $domains_hash->{$server};    
                   9452:         }
1.118     harris41 9453: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  9454: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9455: 	    $rhash{$server}=$reply;
                   9456: 	}
                   9457: 	else {
                   9458: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  9459: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9460: 			     $server);
                   9461: 	    $rhash{$server}=$reply;
                   9462: 	}
1.112     harris41 9463:     }
1.118     harris41 9464:     return \%rhash;
1.240     www      9465: }
                   9466: 
                   9467: # ----------------------------------------- Send log queries and wait for reply
                   9468: 
                   9469: sub log_query {
                   9470:     my ($uname,$udom,$query,%filters)=@_;
                   9471:     my $uhome=&homeserver($uname,$udom);
                   9472:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9473:     my $uhost=&hostname($uhome);
1.800     albertel 9474:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9475:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9476:                        $uhome);
1.479     albertel 9477:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9478:     return get_query_reply($queryid);
                   9479: }
                   9480: 
1.818     raeburn  9481: # -------------------------- Update MySQL table for portfolio file
                   9482: 
                   9483: sub update_portfolio_table {
1.821     raeburn  9484:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9485:     if ($group ne '') {
                   9486:         $file_name =~s /^\Q$group\E//;
                   9487:     }
1.818     raeburn  9488:     my $homeserver = &homeserver($uname,$udom);
                   9489:     my $queryid=
1.821     raeburn  9490:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9491:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9492:     my $reply = &get_query_reply($queryid);
                   9493:     return $reply;
                   9494: }
                   9495: 
1.899     raeburn  9496: # -------------------------- Update MySQL allusers table
                   9497: 
                   9498: sub update_allusers_table {
                   9499:     my ($uname,$udom,$names) = @_;
                   9500:     my $homeserver = &homeserver($uname,$udom);
                   9501:     my $queryid=
                   9502:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9503:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9504:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9505:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9506:                'generation='.&escape($names->{'generation'}).'%%'.
                   9507:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9508:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9509:     return;
1.899     raeburn  9510: }
                   9511: 
1.508     raeburn  9512: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9513: 
                   9514: sub fetch_enrollment_query {
1.511     raeburn  9515:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  9516:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9517:     my $maxtries = 1;
1.508     raeburn  9518:     if ($context eq 'automated') {
                   9519:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  9520:         $sleep = 2;
                   9521:         $loopmax = 100;
1.547     raeburn  9522:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9523:     } else {
                   9524:         $homeserver = &homeserver($cnum,$dom);
                   9525:     }
1.838     albertel 9526:     my $host=&hostname($homeserver);
1.506     raeburn  9527:     my $cmd = '';
1.1000    raeburn  9528:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9529:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9530:     }
                   9531:     $cmd =~ s/%%$//;
                   9532:     $cmd = &escape($cmd);
                   9533:     my $query = 'fetchenrollment';
1.620     albertel 9534:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9535:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9536:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9537:         return 'error: '.$queryid;
                   9538:     }
1.1172.2.93  raeburn  9539:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9540:     my $tries = 1;
                   9541:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  9542:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9543:         $tries ++;
                   9544:     }
1.526     raeburn  9545:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9546:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9547:     } else {
1.901     albertel 9548:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  9549:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9550:             foreach my $line (@responses) {
                   9551:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9552:                 $$replyref{$key} = $value;
                   9553:             }
                   9554:         } else {
1.1117    foxr     9555:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9556:             foreach my $line (@responses) {
                   9557:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9558:                 $$replyref{$key} = $value;
                   9559:                 if ($value > 0) {
1.800     albertel 9560:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9561:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9562:                         my $destname = $pathname.'/'.$filename;
                   9563:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9564:                         if ($xml_classlist =~ /^error/) {
                   9565:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9566:                         } else {
1.1172.2.96  raeburn  9567:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9568:                                 print FILE &unescape($xml_classlist);
                   9569:                                 close(FILE);
1.526     raeburn  9570:                             } else {
                   9571:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9572:                             }
                   9573:                         }
                   9574:                     }
                   9575:                 }
                   9576:             }
                   9577:         }
                   9578:         return 'ok';
                   9579:     }
                   9580:     return 'error';
                   9581: }
                   9582: 
1.242     www      9583: sub get_query_reply {
1.1172.2.79  raeburn  9584:     my ($queryid,$sleep,$loopmax) = @_;
                   9585:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9586:         $sleep = 0.2;
                   9587:     }
                   9588:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9589:         $loopmax = 100;
                   9590:     }
1.1117    foxr     9591:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9592:     my $reply='';
1.1172.2.79  raeburn  9593:     for (1..$loopmax) {
                   9594: 	sleep($sleep);
1.240     www      9595:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  9596: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9597: 		$reply = join('',<$fh>);
                   9598: 		close($fh);
1.240     www      9599: 	   } else { return 'error: reply_file_error'; }
1.242     www      9600:            return &unescape($reply);
                   9601: 	}
1.240     www      9602:     }
1.242     www      9603:     return 'timeout:'.$queryid;
1.240     www      9604: }
                   9605: 
                   9606: sub courselog_query {
1.241     www      9607: #
                   9608: # possible filters:
                   9609: # url: url or symb
                   9610: # username
                   9611: # domain
                   9612: # action: view, submit, grade
                   9613: # start: timestamp
                   9614: # end: timestamp
                   9615: #
1.240     www      9616:     my (%filters)=@_;
1.620     albertel 9617:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9618:     if ($filters{'url'}) {
                   9619: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9620:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9621:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9622:     }
1.620     albertel 9623:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9624:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9625:     return &log_query($cname,$cdom,'courselog',%filters);
                   9626: }
                   9627: 
                   9628: sub userlog_query {
1.858     raeburn  9629: #
                   9630: # possible filters:
                   9631: # action: log check role
                   9632: # start: timestamp
                   9633: # end: timestamp
                   9634: #
1.240     www      9635:     my ($uname,$udom,%filters)=@_;
                   9636:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9637: }
                   9638: 
1.506     raeburn  9639: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9640: 
                   9641: sub auto_run {
1.508     raeburn  9642:     my ($cnum,$cdom) = @_;
1.876     raeburn  9643:     my $response = 0;
                   9644:     my $settings;
                   9645:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9646:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9647:         $settings = $domconfig{'autoenroll'};
                   9648:         if ($settings->{'run'} eq '1') {
                   9649:             $response = 1;
                   9650:         }
                   9651:     } else {
1.934     raeburn  9652:         my $homeserver;
                   9653:         if (&is_course($cdom,$cnum)) {
                   9654:             $homeserver = &homeserver($cnum,$cdom);
                   9655:         } else {
                   9656:             $homeserver = &domain($cdom,'primary');
                   9657:         }
                   9658:         if ($homeserver ne 'no_host') {
                   9659:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9660:         }
1.876     raeburn  9661:     }
1.506     raeburn  9662:     return $response;
                   9663: }
1.776     albertel 9664: 
1.506     raeburn  9665: sub auto_get_sections {
1.508     raeburn  9666:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9667:     my $homeserver;
                   9668:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9669:         $homeserver = &homeserver($cnum,$cdom);
                   9670:     }
                   9671:     if (!defined($homeserver)) { 
                   9672:         if ($cdom =~ /^$match_domain$/) {
                   9673:             $homeserver = &domain($cdom,'primary');
                   9674:         }
                   9675:     }
                   9676:     my @secs;
                   9677:     if (defined($homeserver)) {
                   9678:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9679:         unless ($response eq 'refused') {
                   9680:             @secs = split(/:/,$response);
                   9681:         }
1.506     raeburn  9682:     }
                   9683:     return @secs;
                   9684: }
1.776     albertel 9685: 
1.506     raeburn  9686: sub auto_new_course {
1.1099    raeburn  9687:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9688:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9689:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9690:     return $response;
                   9691: }
1.776     albertel 9692: 
1.506     raeburn  9693: sub auto_validate_courseID {
1.508     raeburn  9694:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9695:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9696:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9697:     return $response;
                   9698: }
1.776     albertel 9699: 
1.1007    raeburn  9700: sub auto_validate_instcode {
1.1020    raeburn  9701:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9702:     my ($homeserver,$response);
                   9703:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9704:         $homeserver = &homeserver($cnum,$cdom);
                   9705:     }
                   9706:     if (!defined($homeserver)) {
                   9707:         if ($cdom =~ /^$match_domain$/) {
                   9708:             $homeserver = &domain($cdom,'primary');
                   9709:         }
                   9710:     }
1.1065    raeburn  9711:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9712:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9713:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9714:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9715: }
                   9716: 
1.1172.2.141  raeburn  9717: sub auto_validate_inst_crosslist {
                   9718:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   9719:     my ($homeserver,$response);
                   9720:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9721:         $homeserver = &homeserver($cnum,$cdom);
                   9722:     }
                   9723:     if (!defined($homeserver)) {
                   9724:         if ($cdom =~ /^$match_domain$/) {
                   9725:             $homeserver = &domain($cdom,'primary');
                   9726:         }
                   9727:     }
                   9728:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   9729:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   9730:                          &escape($instcode).':'.&escape($inst_xlist).':'.
                   9731:                          &escape($coowner),$homeserver);
                   9732:     }
                   9733:     return $response;
                   9734: }
                   9735: 
1.506     raeburn  9736: sub auto_create_password {
1.873     raeburn  9737:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9738:     my ($homeserver,$response);
1.506     raeburn  9739:     my $create_passwd = 0;
                   9740:     my $authchk = '';
1.873     raeburn  9741:     if ($udom =~ /^$match_domain$/) {
                   9742:         $homeserver = &domain($udom,'primary');
                   9743:     }
                   9744:     if ($homeserver eq '') {
                   9745:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9746:             $homeserver = &homeserver($cnum,$cdom);
                   9747:         }
                   9748:     }
                   9749:     if ($homeserver eq '') {
                   9750:         $authchk = 'nodomain';
1.506     raeburn  9751:     } else {
1.873     raeburn  9752:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9753:         if ($response eq 'refused') {
                   9754:             $authchk = 'refused';
                   9755:         } else {
1.901     albertel 9756:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9757:         }
1.506     raeburn  9758:     }
                   9759:     return ($authparam,$create_passwd,$authchk);
                   9760: }
                   9761: 
1.706     raeburn  9762: sub auto_photo_permission {
                   9763:     my ($cnum,$cdom,$students) = @_;
                   9764:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9765:     my ($outcome,$perm_reqd,$conditions) = 
                   9766: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9767:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9768: 	return (undef,undef);
                   9769:     }
1.706     raeburn  9770:     return ($outcome,$perm_reqd,$conditions);
                   9771: }
                   9772: 
                   9773: sub auto_checkphotos {
                   9774:     my ($uname,$udom,$pid) = @_;
                   9775:     my $homeserver = &homeserver($uname,$udom);
                   9776:     my ($result,$resulttype);
                   9777:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9778: 				   &escape($uname).':'.&escape($pid),
                   9779: 				   $homeserver));
1.709     albertel 9780:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9781: 	return (undef,undef);
                   9782:     }
1.706     raeburn  9783:     if ($outcome) {
                   9784:         ($result,$resulttype) = split(/:/,$outcome);
                   9785:     } 
                   9786:     return ($result,$resulttype);
                   9787: }
                   9788: 
                   9789: sub auto_photochoice {
                   9790:     my ($cnum,$cdom) = @_;
                   9791:     my $homeserver = &homeserver($cnum,$cdom);
                   9792:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9793: 						       &escape($cdom),
                   9794: 						       $homeserver)));
1.709     albertel 9795:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9796: 	return (undef,undef);
                   9797:     }
1.706     raeburn  9798:     return ($update,$comment);
                   9799: }
                   9800: 
                   9801: sub auto_photoupdate {
                   9802:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9803:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9804:     my $host=&hostname($homeserver);
1.706     raeburn  9805:     my $cmd = '';
                   9806:     my $maxtries = 1;
1.800     albertel 9807:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9808:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9809:     }
                   9810:     $cmd =~ s/%%$//;
                   9811:     $cmd = &escape($cmd);
                   9812:     my $query = 'institutionalphotos';
                   9813:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9814:     unless ($queryid=~/^\Q$host\E\_/) {
                   9815:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9816:         return 'error: '.$queryid;
                   9817:     }
                   9818:     my $reply = &get_query_reply($queryid);
                   9819:     my $tries = 1;
                   9820:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9821:         $reply = &get_query_reply($queryid);
                   9822:         $tries ++;
                   9823:     }
                   9824:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9825:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9826:     } else {
                   9827:         my @responses = split(/:/,$reply);
                   9828:         my $outcome = shift(@responses); 
                   9829:         foreach my $item (@responses) {
                   9830:             my ($key,$value) = split(/=/,$item);
                   9831:             $$photo{$key} = $value;
                   9832:         }
                   9833:         return $outcome;
                   9834:     }
                   9835:     return 'error';
                   9836: }
                   9837: 
1.521     raeburn  9838: sub auto_instcode_format {
1.793     albertel 9839:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9840: 	$cat_order) = @_;
1.521     raeburn  9841:     my $courses = '';
1.772     raeburn  9842:     my @homeservers;
1.521     raeburn  9843:     if ($caller eq 'global') {
1.841     albertel 9844: 	my %servers = &get_servers($codedom,'library');
                   9845: 	foreach my $tryserver (keys(%servers)) {
                   9846: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9847: 		push(@homeservers,$tryserver);
                   9848: 	    }
1.584     raeburn  9849:         }
1.1022    raeburn  9850:     } elsif ($caller eq 'requests') {
                   9851:         if ($codedom =~ /^$match_domain$/) {
                   9852:             my $chome = &domain($codedom,'primary');
                   9853:             unless ($chome eq 'no_host') {
                   9854:                 push(@homeservers,$chome);
                   9855:             }
                   9856:         }
1.521     raeburn  9857:     } else {
1.772     raeburn  9858:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9859:     }
1.793     albertel 9860:     foreach my $code (keys(%{$instcodes})) {
                   9861:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9862:     }
                   9863:     chop($courses);
1.772     raeburn  9864:     my $ok_response = 0;
                   9865:     my $response;
                   9866:     while (@homeservers > 0 && $ok_response == 0) {
                   9867:         my $server = shift(@homeservers); 
                   9868:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9869:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9870:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9871: 		split(/:/,$response);
1.772     raeburn  9872:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9873:             push(@{$codetitles},&str2array($codetitles_str));
                   9874:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9875:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9876:             $ok_response = 1;
                   9877:         }
                   9878:     }
                   9879:     if ($ok_response) {
1.521     raeburn  9880:         return 'ok';
1.772     raeburn  9881:     } else {
                   9882:         return $response;
1.521     raeburn  9883:     }
                   9884: }
                   9885: 
1.792     raeburn  9886: sub auto_instcode_defaults {
                   9887:     my ($domain,$returnhash,$code_order) = @_;
                   9888:     my @homeservers;
1.841     albertel 9889: 
                   9890:     my %servers = &get_servers($domain,'library');
                   9891:     foreach my $tryserver (keys(%servers)) {
                   9892: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9893: 	    push(@homeservers,$tryserver);
                   9894: 	}
1.792     raeburn  9895:     }
1.841     albertel 9896: 
1.792     raeburn  9897:     my $response;
1.841     albertel 9898:     foreach my $server (@homeservers) {
1.792     raeburn  9899:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9900:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9901: 	
                   9902: 	foreach my $pair (split(/\&/,$response)) {
                   9903: 	    my ($name,$value)=split(/\=/,$pair);
                   9904: 	    if ($name eq 'code_order') {
                   9905: 		@{$code_order} = split(/\&/,&unescape($value));
                   9906: 	    } else {
                   9907: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9908: 	    }
                   9909: 	}
                   9910: 	return 'ok';
1.792     raeburn  9911:     }
1.841     albertel 9912: 
                   9913:     return $response;
1.1003    raeburn  9914: }
                   9915: 
                   9916: sub auto_possible_instcodes {
1.1007    raeburn  9917:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9918:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9919:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9920:         return;
                   9921:     }
1.1003    raeburn  9922:     my (@homeservers,$uhome);
                   9923:     if (defined(&domain($domain,'primary'))) {
                   9924:         $uhome=&domain($domain,'primary');
                   9925:         push(@homeservers,&domain($domain,'primary'));
                   9926:     } else {
                   9927:         my %servers = &get_servers($domain,'library');
                   9928:         foreach my $tryserver (keys(%servers)) {
                   9929:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9930:                 push(@homeservers,$tryserver);
                   9931:             }
                   9932:         }
                   9933:     }
                   9934:     my $response;
                   9935:     foreach my $server (@homeservers) {
                   9936:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9937:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9938:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9939:             split(':',$response);
                   9940:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9941:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9942:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9943:             my ($name,$value)=split('=',$item);
                   9944:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9945:         }
                   9946:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9947:             my ($name,$value)=split('=',$item);
                   9948:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9949:         }
                   9950:         return 'ok';
                   9951:     }
                   9952:     return $response;
                   9953: }
1.792     raeburn  9954: 
1.1010    raeburn  9955: sub auto_courserequest_checks {
                   9956:     my ($dom) = @_;
1.1020    raeburn  9957:     my ($homeserver,%validations);
                   9958:     if ($dom =~ /^$match_domain$/) {
                   9959:         $homeserver = &domain($dom,'primary');
                   9960:     }
                   9961:     unless ($homeserver eq 'no_host') {
                   9962:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9963:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9964:             my @items = split(/&/,$response);
                   9965:             foreach my $item (@items) {
                   9966:                 my ($key,$value) = split('=',$item);
                   9967:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9968:             }
                   9969:         }
                   9970:     }
1.1010    raeburn  9971:     return %validations; 
                   9972: }
                   9973: 
1.1020    raeburn  9974: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9975:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9976:     my ($homeserver,$response);
                   9977:     if ($dom =~ /^$match_domain$/) {
                   9978:         $homeserver = &domain($dom,'primary');
                   9979:     }
1.1172.2.43  raeburn  9980:     unless ($homeserver eq 'no_host') {
                   9981:         my $customdata;
                   9982:         if (ref($custominfo) eq 'HASH') {
                   9983:             $customdata = &freeze_escape($custominfo);
                   9984:         }
1.1020    raeburn  9985:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9986:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9987:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9988:                                     $customdata,$homeserver));
1.1020    raeburn  9989:     }
                   9990:     return $response;
                   9991: }
                   9992: 
1.777     albertel 9993: sub auto_validate_class_sec {
1.918     raeburn  9994:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9995:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9996:     my $ownerlist;
                   9997:     if (ref($owners) eq 'ARRAY') {
                   9998:         $ownerlist = join(',',@{$owners});
                   9999:     } else {
                   10000:         $ownerlist = $owners;
                   10001:     }
1.773     raeburn  10002:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  10003:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  10004:     return $response;
                   10005: }
                   10006: 
1.1172.2.141  raeburn  10007: sub auto_instsec_reformat {
                   10008:     my ($cdom,$action,$instsecref) = @_;
                   10009:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   10010:     my @homeservers;
                   10011:     if (defined(&domain($cdom,'primary'))) {
                   10012:         push(@homeservers,&domain($cdom,'primary'));
                   10013:     } else {
                   10014:         my %servers = &get_servers($cdom,'library');
                   10015:         foreach my $tryserver (keys(%servers)) {
                   10016:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   10017:                 push(@homeservers,$tryserver);
                   10018:             }
                   10019:         }
                   10020:     }
                   10021:     my $response;
                   10022:     my %reformatted = %{$instsecref};
                   10023:     foreach my $server (@homeservers) {
                   10024:         if (ref($instsecref) eq 'HASH') {
                   10025:             my $info = &freeze_escape($instsecref);
                   10026:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   10027:                                 $action.':'.$info,$server);
                   10028:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   10029:             my @items = split(/&/,$response);
                   10030:             foreach my $item (@items) {
                   10031:                 my ($key,$value) = split(/=/,$item);
                   10032:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   10033:             }
                   10034:         }
                   10035:     }
                   10036:     return %reformatted;
                   10037: }
                   10038: 
1.1172.2.94  raeburn  10039: sub auto_validate_instclasses {
                   10040:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   10041:     my ($homeserver,%validations);
                   10042:     $homeserver = &homeserver($cnum,$cdom);
                   10043:     unless ($homeserver eq 'no_host') {
                   10044:         my $ownerlist;
                   10045:         if (ref($owners) eq 'ARRAY') {
                   10046:             $ownerlist = join(',',@{$owners});
                   10047:         } else {
                   10048:             $ownerlist = $owners;
                   10049:         }
                   10050:         if (ref($classesref) eq 'HASH') {
                   10051:             my $classes = &freeze_escape($classesref);
                   10052:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   10053:                                 ':'.$cdom.':'.$classes,$homeserver);
                   10054:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   10055:                 my @items = split(/&/,$response);
                   10056:                 foreach my $item (@items) {
                   10057:                     my ($key,$value) = split('=',$item);
                   10058:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   10059:                 }
                   10060:             }
                   10061:         }
                   10062:     }
                   10063:     return %validations;
                   10064: }
                   10065: 
1.1172.2.38  raeburn  10066: sub auto_crsreq_update {
                   10067:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  10068:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  10069:     my ($homeserver,%crsreqresponse);
                   10070:     if ($cdom =~ /^$match_domain$/) {
                   10071:         $homeserver = &domain($cdom,'primary');
                   10072:     }
                   10073:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   10074:         my $info;
                   10075:         if (ref($inbound) eq 'HASH') {
                   10076:             $info = &freeze_escape($inbound);
                   10077:         }
                   10078:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   10079:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   10080:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  10081:                             &escape($title).':'.&escape($code).':'.
                   10082:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  10083:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   10084:             my @items = split(/&/,$response);
                   10085:             foreach my $item (@items) {
                   10086:                 my ($key,$value) = split('=',$item);
                   10087:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   10088:             }
                   10089:         }
                   10090:     }
                   10091:     return \%crsreqresponse;
                   10092: }
                   10093: 
1.1172.2.78  raeburn  10094: sub auto_export_grades {
                   10095:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   10096:     my ($homeserver,%exportresponse);
                   10097:     if ($cdom =~ /^$match_domain$/) {
                   10098:         $homeserver = &domain($cdom,'primary');
                   10099:     }
                   10100:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   10101:         my $info;
                   10102:         if (ref($inforef) eq 'HASH') {
                   10103:             $info = &freeze_escape($inforef);
                   10104:         }
                   10105:         if (ref($gradesref) eq 'HASH') {
                   10106:             my $grades = &freeze_escape($gradesref);
                   10107:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   10108:                                 $info.':'.$grades,$homeserver);
                   10109:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   10110:                 my @items = split(/&/,$response);
                   10111:                 foreach my $item (@items) {
                   10112:                     my ($key,$value) = split('=',$item);
                   10113:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   10114:                 }
                   10115:             }
                   10116:         }
                   10117:     }
                   10118:     return \%exportresponse;
                   10119: }
                   10120: 
1.1172.2.68  raeburn  10121: sub check_instcode_cloning {
                   10122:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   10123:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   10124:         return;
                   10125:     }
                   10126:     my $canclone;
                   10127:     if (@{$code_order} > 0) {
                   10128:         my $instcoderegexp ='^';
                   10129:         my @clonecodes = split(/\&/,$cloner);
                   10130:         foreach my $item (@{$code_order}) {
                   10131:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   10132:                 foreach my $pair (@clonecodes) {
                   10133:                     my ($key,$val) = split(/\=/,$pair,2);
                   10134:                     $val = &unescape($val);
                   10135:                     if ($key eq $item) {
                   10136:                         $instcoderegexp .= '('.$val.')';
                   10137:                         last;
                   10138:                     }
                   10139:                 }
                   10140:             } else {
                   10141:                 $instcoderegexp .= $codedefaults->{$item};
                   10142:             }
                   10143:         }
                   10144:         $instcoderegexp .= '$';
                   10145:         my (@from,@to);
                   10146:         eval {
                   10147:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10148:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10149:         };
                   10150:         if ((@from > 0) && (@to > 0)) {
                   10151:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10152:             if (!@diffs) {
                   10153:                 $canclone = 1;
                   10154:             }
                   10155:         }
                   10156:     }
                   10157:     return $canclone;
                   10158: }
                   10159: 
                   10160: sub default_instcode_cloning {
                   10161:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   10162:     my (%codedefaults,@code_order,$canclone);
                   10163:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   10164:         %codedefaults = %{$codedefaultsref};
                   10165:         @code_order = @{$codeorderref};
                   10166:     } elsif ($clonedom) {
                   10167:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   10168:     }
                   10169:     if (($domdefclone) && (@code_order)) {
                   10170:         my @clonecodes = split(/\+/,$domdefclone);
                   10171:         my $instcoderegexp ='^';
                   10172:         foreach my $item (@code_order) {
                   10173:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   10174:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   10175:             } else {
                   10176:                 $instcoderegexp .= $codedefaults{$item};
                   10177:             }
                   10178:         }
                   10179:         $instcoderegexp .= '$';
                   10180:         my (@from,@to);
                   10181:         eval {
                   10182:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10183:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10184:         };
                   10185:         if ((@from > 0) && (@to > 0)) {
                   10186:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10187:             if (!@diffs) {
                   10188:                 $canclone = 1;
                   10189:             }
                   10190:         }
                   10191:     }
                   10192:     return $canclone;
                   10193: }
                   10194: 
1.679     raeburn  10195: # ------------------------------------------------------- Course Group routines
                   10196: 
                   10197: sub get_coursegroups {
1.809     raeburn  10198:     my ($cdom,$cnum,$group,$namespace) = @_;
                   10199:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  10200: }
                   10201: 
1.679     raeburn  10202: sub modify_coursegroup {
                   10203:     my ($cdom,$cnum,$groupsettings) = @_;
                   10204:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   10205: }
                   10206: 
1.809     raeburn  10207: sub toggle_coursegroup_status {
                   10208:     my ($cdom,$cnum,$group,$action) = @_;
                   10209:     my ($from_namespace,$to_namespace);
                   10210:     if ($action eq 'delete') {
                   10211:         $from_namespace = 'coursegroups';
                   10212:         $to_namespace = 'deleted_groups';
                   10213:     } else {
                   10214:         $from_namespace = 'deleted_groups';
                   10215:         $to_namespace = 'coursegroups';
                   10216:     }
                   10217:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  10218:     if (my $tmp = &error(%curr_group)) {
                   10219:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   10220:         return ('read error',$tmp);
                   10221:     } else {
                   10222:         my %savedsettings = %curr_group; 
1.809     raeburn  10223:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  10224:         my $deloutcome;
                   10225:         if ($result eq 'ok') {
1.809     raeburn  10226:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  10227:         } else {
                   10228:             return ('write error',$result);
                   10229:         }
                   10230:         if ($deloutcome eq 'ok') {
                   10231:             return 'ok';
                   10232:         } else {
                   10233:             return ('delete error',$deloutcome);
                   10234:         }
                   10235:     }
                   10236: }
                   10237: 
1.679     raeburn  10238: sub modify_group_roles {
1.957     raeburn  10239:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  10240:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   10241:     my $role = 'gr/'.&escape($userprivs);
                   10242:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  10243:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  10244:     if ($result eq 'ok') {
                   10245:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   10246:     }
1.679     raeburn  10247:     return $result;
                   10248: }
                   10249: 
                   10250: sub modify_coursegroup_membership {
                   10251:     my ($cdom,$cnum,$membership) = @_;
                   10252:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   10253:     return $result;
                   10254: }
                   10255: 
1.682     raeburn  10256: sub get_active_groups {
                   10257:     my ($udom,$uname,$cdom,$cnum) = @_;
                   10258:     my $now = time;
                   10259:     my %groups = ();
                   10260:     foreach my $key (keys(%env)) {
1.811     albertel 10261:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  10262:             my ($start,$end) = split(/\./,$env{$key});
                   10263:             if (($end!=0) && ($end<$now)) { next; }
                   10264:             if (($start!=0) && ($start>$now)) { next; }
                   10265:             if ($1 eq $cdom && $2 eq $cnum) {
                   10266:                 $groups{$3} = $env{$key} ;
                   10267:             }
                   10268:         }
                   10269:     }
                   10270:     return %groups;
                   10271: }
                   10272: 
1.683     raeburn  10273: sub get_group_membership {
                   10274:     my ($cdom,$cnum,$group) = @_;
                   10275:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   10276: }
                   10277: 
                   10278: sub get_users_groups {
                   10279:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  10280:     my @usersgroups;
1.683     raeburn  10281:     my $cachetime=1800;
                   10282: 
                   10283:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  10284:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   10285:     if (defined($cached)) {
1.734     albertel 10286:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  10287:     } else {  
                   10288:         $grouplist = '';
1.816     raeburn  10289:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  10290:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  10291:         my $access_end = $env{'course.'.$courseid.
                   10292:                               '.default_enrollment_end_date'};
                   10293:         my $now = time;
                   10294:         foreach my $key (keys(%roleshash)) {
                   10295:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   10296:                 my $group = $1;
                   10297:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   10298:                     my $start = $2;
                   10299:                     my $end = $1;
                   10300:                     if ($start == -1) { next; } # deleted from group
                   10301:                     if (($start!=0) && ($start>$now)) { next; }
                   10302:                     if (($end!=0) && ($end<$now)) {
                   10303:                         if ($access_end && $access_end < $now) {
                   10304:                             if ($access_end - $end < 86400) {
                   10305:                                 push(@usersgroups,$group);
1.733     raeburn  10306:                             }
                   10307:                         }
1.817     raeburn  10308:                         next;
1.733     raeburn  10309:                     }
1.817     raeburn  10310:                     push(@usersgroups,$group);
1.683     raeburn  10311:                 }
                   10312:             }
                   10313:         }
1.817     raeburn  10314:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   10315:         $grouplist = join(':',@usersgroups);
                   10316:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  10317:     }
1.733     raeburn  10318:     return @usersgroups;
1.683     raeburn  10319: }
                   10320: 
                   10321: sub devalidate_getgroups_cache {
                   10322:     my ($udom,$uname,$cdom,$cnum)=@_;
                   10323:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 10324: 
1.683     raeburn  10325:     my $hashid="$udom:$uname:$courseid";
                   10326:     &devalidate_cache_new('getgroups',$hashid);
                   10327: }
                   10328: 
1.12      www      10329: # ------------------------------------------------------------------ Plain Text
                   10330: 
                   10331: sub plaintext {
1.988     raeburn  10332:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  10333:     if ($short =~ m{^cr/}) {
1.758     albertel 10334: 	return (split('/',$short))[-1];
                   10335:     }
1.742     raeburn  10336:     if (!defined($cid)) {
                   10337:         $cid = $env{'request.course.id'};
                   10338:     }
                   10339:     my %rolenames = (
1.1008    raeburn  10340:                       Course    => 'std',
                   10341:                       Community => 'alt1',
1.742     raeburn  10342:                     );
1.1037    raeburn  10343:     if ($cid ne '') {
                   10344:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   10345:             unless ($forcedefault) {
                   10346:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   10347:                 &Apache::lonlocal::mt_escape(\$roletext);
                   10348:                 return &Apache::lonlocal::mt($roletext);
                   10349:             }
                   10350:         }
                   10351:     }
                   10352:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   10353:         (defined($rolenames{$type})) && 
                   10354:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  10355:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  10356:     } elsif ($cid ne '') {
                   10357:         my $crstype = $env{'course.'.$cid.'.type'};
                   10358:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   10359:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   10360:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   10361:         }
1.742     raeburn  10362:     }
1.1037    raeburn  10363:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      10364: }
                   10365: 
                   10366: # ----------------------------------------------------------------- Assign Role
                   10367: 
                   10368: sub assignrole {
1.957     raeburn  10369:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   10370:         $context)=@_;
1.21      www      10371:     my $mrole;
                   10372:     if ($role =~ /^cr\//) {
1.393     www      10373:         my $cwosec=$url;
1.811     albertel 10374:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      10375: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  10376:            my $refused = 1;
                   10377:            if ($context eq 'requestcourses') {
                   10378:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   10379:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   10380:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   10381:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10382:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10383:                            if ($crsenv{'internal.courseowner'} eq
                   10384:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   10385:                                $refused = '';
                   10386:                            }
                   10387:                        }
                   10388:                    }
                   10389:                }
                   10390:            }
                   10391:            if ($refused) {
                   10392:                &logthis('Refused custom assignrole: '.
                   10393:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   10394:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   10395:                return 'refused';
                   10396:            }
1.104     www      10397:         }
1.21      www      10398:         $mrole='cr';
1.678     raeburn  10399:     } elsif ($role =~ /^gr\//) {
                   10400:         my $cwogrp=$url;
1.811     albertel 10401:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  10402:         unless (&allowed('mdg',$cwogrp)) {
                   10403:             &logthis('Refused group assignrole: '.
                   10404:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   10405:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   10406:             return 'refused';
                   10407:         }
                   10408:         $mrole='gr';
1.21      www      10409:     } else {
1.82      www      10410:         my $cwosec=$url;
1.811     albertel 10411:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  10412:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   10413:             my $refused;
                   10414:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   10415:                 if (!(&allowed('c'.$role,$url))) {
                   10416:                     $refused = 1;
                   10417:                 }
                   10418:             } else {
                   10419:                 $refused = 1;
                   10420:             }
1.947     raeburn  10421:             if ($refused) {
1.1045    raeburn  10422:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10423:                 if (!$selfenroll && $context eq 'course') {
                   10424:                     my %crsenv;
                   10425:                     if ($role eq 'cc' || $role eq 'co') {
                   10426:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10427:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   10428:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   10429:                                 if ($crsenv{'internal.courseowner'} eq 
                   10430:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10431:                                     $refused = '';
                   10432:                                 }
                   10433:                             }
                   10434:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   10435:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   10436:                                 if ($crsenv{'internal.courseowner'} eq 
                   10437:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10438:                                     $refused = '';
                   10439:                                 }
                   10440:                             }
                   10441:                         }
                   10442:                     }
1.1172.2.146.  .13(raeb 10443:-23):                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   10444:-23):                     if ($role eq 'st') {
                   10445:-23):                         $refused = '';
                   10446:-23):                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
                   10447:-23):                         $refused = '';
                   10448:-23):                     }
1.1017    raeburn  10449:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10450:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10451:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10452:                         my $wrongcc;
                   10453:                         if ($cnum =~ /^$match_community$/) {
                   10454:                             $wrongcc = 1 if ($role eq 'cc');
                   10455:                         } else {
                   10456:                             $wrongcc = 1 if ($role eq 'co');
                   10457:                         }
                   10458:                         unless ($wrongcc) {
                   10459:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10460:                             if ($crsenv{'internal.courseowner'} eq 
                   10461:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10462:                                 $refused = '';
                   10463:                             }
1.1017    raeburn  10464:                         }
                   10465:                     }
1.1172.2.9  raeburn  10466:                 } elsif ($context eq 'requestauthor') {
                   10467:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   10468:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10469:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10470:                             $refused = '';
                   10471:                         } else {
                   10472:                             my %domdefaults = &get_domain_defaults($udom);
                   10473:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10474:                                 my $checkbystatus;
                   10475:                                 if ($env{'user.adv'}) {
                   10476:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10477:                                     if ($disposition eq 'automatic') {
                   10478:                                         $refused = '';
                   10479:                                     } elsif ($disposition eq '') {
                   10480:                                         $checkbystatus = 1;
                   10481:                                     }
                   10482:                                 } else {
                   10483:                                     $checkbystatus = 1;
                   10484:                                 }
                   10485:                                 if ($checkbystatus) {
                   10486:                                     if ($env{'environment.inststatus'}) {
                   10487:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10488:                                         foreach my $type (@inststatuses) {
                   10489:                                             if (($type ne '') &&
                   10490:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10491:                                                 $refused = '';
                   10492:                                             }
                   10493:                                         }
                   10494:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10495:                                         $refused = '';
                   10496:                                     }
                   10497:                                 }
                   10498:                             }
                   10499:                         }
                   10500:                     }
1.1017    raeburn  10501:                 }
                   10502:                 if ($refused) {
1.947     raeburn  10503:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10504:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10505: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10506:                     return 'refused';
                   10507:                 }
1.932     raeburn  10508:             }
1.1131    raeburn  10509:         } elsif ($role eq 'au') {
                   10510:             if ($url ne '/'.$udom.'/') {
                   10511:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10512:                          ' to assign author role for '.$uname.':'.$udom.
                   10513:                          ' in domain: '.$url.' refused (wrong domain).');
                   10514:                 return 'refused';
                   10515:             }
1.104     www      10516:         }
1.21      www      10517:         $mrole=$role;
                   10518:     }
1.620     albertel 10519:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10520:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10521:     if ($end) { $command.='_'.$end; }
1.21      www      10522:     if ($start) {
                   10523: 	if ($end) { 
1.81      www      10524:            $command.='_'.$start; 
1.21      www      10525:         } else {
1.81      www      10526:            $command.='_0_'.$start;
1.21      www      10527:         }
                   10528:     }
1.739     raeburn  10529:     my $origstart = $start;
                   10530:     my $origend = $end;
1.957     raeburn  10531:     my $delflag;
1.357     www      10532: # actually delete
                   10533:     if ($deleteflag) {
1.373     www      10534: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10535: # modify command to delete the role
1.620     albertel 10536:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10537:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10538: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10539: # set start and finish to negative values for userrolelog
                   10540:            $start=-1;
                   10541:            $end=-1;
1.957     raeburn  10542:            $delflag = 1;
1.357     www      10543:         }
                   10544:     }
                   10545: # send command
1.349     www      10546:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      10547: # log new user role if status is ok
1.349     www      10548:     if ($answer eq 'ok') {
1.663     raeburn  10549: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  10550:         if (($role eq 'cc') || ($role eq 'in') ||
                   10551:             ($role eq 'ep') || ($role eq 'ad') ||
                   10552:             ($role eq 'ta') || ($role eq 'st') ||
                   10553:             ($role=~/^cr/) || ($role eq 'gr') ||
                   10554:             ($role eq 'co')) {
1.1172.2.13  raeburn  10555: # for course roles, perform group memberships changes triggered by role change.
                   10556:             unless ($role =~ /^gr/) {
                   10557:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10558:                                                  $origstart,$selfenroll,$context);
                   10559:             }
1.1172.2.9  raeburn  10560:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10561:                            $selfenroll,$context);
                   10562:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  10563:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10564:                  ($role eq 'da')) {
1.1172.2.9  raeburn  10565:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10566:                            $context);
                   10567:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10568:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10569:                              $context);
                   10570:         }
1.1053    raeburn  10571:         if ($role eq 'cc') {
                   10572:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10573:         }
1.349     www      10574:     }
                   10575:     return $answer;
1.169     harris41 10576: }
                   10577: 
1.1053    raeburn  10578: sub autoupdate_coowners {
                   10579:     my ($url,$end,$start,$uname,$udom) = @_;
                   10580:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10581:     if (($cdom ne '') && ($cnum ne '')) {
                   10582:         my $now = time;
                   10583:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10584:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10585:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10586:             my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141  raeburn  10587:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  10588:             if ($instcode ne '') {
1.1056    raeburn  10589:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10590:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10591:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10592:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141  raeburn  10593:                         unless ($result eq 'valid') {
                   10594:                             if ($xlists ne '') {
                   10595:                                 foreach my $xlist (split(',',$xlists)) {
                   10596:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   10597:                                     $result =
                   10598:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   10599:                                                                       $inst_crosslist,$uname.':'.$udom);
                   10600:                                     last if ($result eq 'valid');
                   10601:                                 }
                   10602:                             }
                   10603:                         }
1.1056    raeburn  10604:                         if ($result eq 'valid') {
                   10605:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10606:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10607:                                     push(@newcoowners,$coowner);
                   10608:                                 }
                   10609:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10610:                                     push(@newcoowners,$uname.':'.$udom);
                   10611:                                 }
                   10612:                                 @newcoowners = sort(@newcoowners);
                   10613:                             } else {
                   10614:                                 push(@newcoowners,$uname.':'.$udom);
                   10615:                             }
1.1172.2.141  raeburn  10616:                         } elsif ($coursehash{'internal.co-owners'}) {
                   10617:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10618:                                 unless ($coowner eq $uname.':'.$udom) {
                   10619:                                     push(@newcoowners,$coowner);
1.1053    raeburn  10620:                                 }
                   10621:                             }
1.1172.2.141  raeburn  10622:                             unless (@newcoowners > 0) {
                   10623:                                 $delcoowners = 1;
                   10624:                                 $coowners = '';
                   10625:                             }
1.1053    raeburn  10626:                         }
                   10627:                         if (@newcoowners || $delcoowners) {
                   10628:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10629:                                             $delcoowners,@newcoowners);
                   10630:                         }
                   10631:                     }
                   10632:                 }
                   10633:             }
                   10634:         }
                   10635:     }
                   10636: }
                   10637: 
                   10638: sub store_coowners {
                   10639:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10640:     my $cid = $cdom.'_'.$cnum;
                   10641:     my ($coowners,$delresult,$putresult);
                   10642:     if (@newcoowners) {
                   10643:         $coowners = join(',',@newcoowners);
                   10644:         my %coownershash = (
                   10645:                             'internal.co-owners' => $coowners,
                   10646:                            );
                   10647:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10648:         if ($putresult eq 'ok') {
                   10649:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10650:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10651:             }
                   10652:         }
                   10653:     }
                   10654:     if ($delcoowners) {
                   10655:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10656:         if ($delresult eq 'ok') {
                   10657:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10658:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10659:             }
                   10660:         }
                   10661:     }
                   10662:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10663:         my %crsinfo =
                   10664:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10665:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10666:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10667:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10668:         }
                   10669:     }
                   10670: }
                   10671: 
1.169     harris41 10672: # -------------------------------------------------- Modify user authentication
1.197     www      10673: # Overrides without validation
                   10674: 
1.169     harris41 10675: sub modifyuserauth {
                   10676:     my ($udom,$uname,$umode,$upass)=@_;
                   10677:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  10678:     my $allowed;
                   10679:     if (&allowed('mau',$udom)) {
                   10680:         $allowed = 1;
                   10681:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10682:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10683:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10684:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10685:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10686:         if (($cdom ne '') && ($cnum ne '')) {
                   10687:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10688:             if ($is_owner) {
                   10689:                 $allowed = 1;
                   10690:             }
                   10691:         }
                   10692:     }
                   10693:     unless ($allowed) { return 'refused'; }
1.197     www      10694:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10695:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10696:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10697:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10698: 		     &escape($upass),$uhome);
1.1172.2.134  raeburn  10699:     my $ip = &get_requestor_ip();
1.620     albertel 10700:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10701:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134  raeburn  10702:          '(Remote '.$ip.'): '.$reply);
1.197     www      10703:     &log($udom,,$uname,$uhome,
1.620     albertel 10704:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10705:                                      $env{'user.name'}.', '.$umode.
1.1172.2.134  raeburn  10706:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10707:     unless ($reply eq 'ok') {
1.197     www      10708:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10709: 	return 'error: '.$reply;
                   10710:     }   
1.170     harris41 10711:     return 'ok';
1.80      www      10712: }
                   10713: 
1.81      www      10714: # --------------------------------------------------------------- Modify a user
1.80      www      10715: 
1.81      www      10716: sub modifyuser {
1.206     matthew  10717:     my ($udom,    $uname, $uid,
                   10718:         $umode,   $upass, $first,
                   10719:         $middle,  $last,  $gene,
1.1058    raeburn  10720:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10721:     $udom= &LONCAPA::clean_domain($udom);
                   10722:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10723:     my $showcandelete = 'none';
                   10724:     if (ref($candelete) eq 'ARRAY') {
                   10725:         if (@{$candelete} > 0) {
                   10726:             $showcandelete = join(', ',@{$candelete});
                   10727:         }
                   10728:     }
1.81      www      10729:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10730:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10731: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10732:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10733:                                      ' desiredhome not specified'). 
1.620     albertel 10734:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10735:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10736:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10737:     my $newuser;
                   10738:     if ($uhome eq 'no_host') {
                   10739:         $newuser = 1;
1.1172.2.146.  .13(raeb 10740:-23):         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   10741:-23):                 ($umode eq 'lti')) {
                   10742:-23):             return 'error: more information needed to create new user';
                   10743:-23):         }
1.1075    raeburn  10744:     }
1.80      www      10745: # ----------------------------------------------------------------- Create User
1.406     albertel 10746:     if (($uhome eq 'no_host') && 
1.1172.2.146.  .13(raeb 10747:-23): 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      10748:         my $unhome='';
1.844     albertel 10749:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10750:             $unhome = $desiredhome;
1.620     albertel 10751: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10752: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10753:         } else { # load balancing routine for determining $unhome
1.81      www      10754:             my $loadm=10000000;
1.841     albertel 10755: 	    my %servers = &get_servers($udom,'library');
                   10756: 	    foreach my $tryserver (keys(%servers)) {
                   10757: 		my $answer=reply('load',$tryserver);
                   10758: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10759: 		    $loadm=$answer;
                   10760: 		    $unhome=$tryserver;
                   10761: 		}
1.80      www      10762: 	    }
                   10763:         }
                   10764:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10765: 	    return 'error: unable to find a home server for '.$uname.
                   10766:                    ' in domain '.$udom;
1.80      www      10767:         }
                   10768:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10769:                          &escape($upass),$unhome);
                   10770: 	unless ($reply eq 'ok') {
                   10771:             return 'error: '.$reply;
                   10772:         }   
1.230     stredwic 10773:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10774:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10775: 	    return 'error: unable verify users home machine.';
1.80      www      10776:         }
1.209     matthew  10777:     }   # End of creation of new user
1.80      www      10778: # ---------------------------------------------------------------------- Add ID
                   10779:     if ($uid) {
                   10780:        $uid=~tr/A-Z/a-z/;
                   10781:        my %uidhash=&idrget($udom,$uname);
1.196     www      10782:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10783:          && (!$forceid)) {
1.80      www      10784: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10785: 	      return 'error: user id "'.$uid.'" does not match '.
                   10786:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10787:           }
                   10788:        } else {
                   10789: 	  &idput($udom,($uname => $uid));
                   10790:        }
                   10791:     }
                   10792: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10793:     my @tmp=&get('environment',
1.899     raeburn  10794: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10795:                     'permanentemail','inststatus'],
1.134     albertel 10796: 		   $udom,$uname);
1.1075    raeburn  10797:     my (%names,%oldnames);
1.313     matthew  10798:     if ($tmp[0] =~ m/^error:.*/) { 
                   10799:         %names=(); 
                   10800:     } else {
                   10801:         %names = @tmp;
1.1075    raeburn  10802:         %oldnames = %names;
1.313     matthew  10803:     }
1.388     www      10804: #
1.1058    raeburn  10805: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10806: # of users did not contain them), do not overwrite existing values
                   10807: # unless field is in $candelete array ref.  
                   10808: #
                   10809: 
                   10810:     my @fields = ('firstname','middlename','lastname','generation',
                   10811:                   'permanentemail','id');
                   10812:     my %newvalues;
                   10813:     if (ref($candelete) eq 'ARRAY') {
                   10814:         foreach my $field (@fields) {
                   10815:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10816:                 if ($field eq 'firstname') {
                   10817:                     $names{$field} = $first;
                   10818:                 } elsif ($field eq 'middlename') {
                   10819:                     $names{$field} = $middle;
                   10820:                 } elsif ($field eq 'lastname') {
                   10821:                     $names{$field} = $last;
                   10822:                 } elsif ($field eq 'generation') { 
                   10823:                     $names{$field} = $gene;
                   10824:                 } elsif ($field eq 'permanentemail') {
                   10825:                     $names{$field} = $email;
                   10826:                 } elsif ($field eq 'id') {
                   10827:                     $names{$field}  = $uid;
                   10828:                 }
                   10829:             }
                   10830:         }
                   10831:     }
1.388     www      10832:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10833:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10834:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10835:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10836:     if ($email) {
                   10837:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10838:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10839:     }
1.899     raeburn  10840:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10841:     if (defined($inststatus)) {
                   10842:         $names{'inststatus'} = '';
                   10843:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10844:         if (ref($usertypes) eq 'HASH') {
                   10845:             my @okstatuses; 
                   10846:             foreach my $item (split(/:/,$inststatus)) {
                   10847:                 if (defined($usertypes->{$item})) {
                   10848:                     push(@okstatuses,$item);  
                   10849:                 }
                   10850:             }
                   10851:             if (@okstatuses) {
                   10852:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10853:             }
                   10854:         }
                   10855:     }
1.1075    raeburn  10856:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10857:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10858:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10859:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10860:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10861:     } else {
                   10862:         $logmsg .= ' during self creation';
                   10863:     }
1.1075    raeburn  10864:     my $changed;
                   10865:     if ($newuser) {
                   10866:         $changed = 1;
                   10867:     } else {
                   10868:         foreach my $field (@fields) {
                   10869:             if ($names{$field} ne $oldnames{$field}) {
                   10870:                 $changed = 1;
                   10871:                 last;
                   10872:             }
                   10873:         }
                   10874:     }
                   10875:     unless ($changed) {
                   10876:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10877:         &logthis($logmsg);
                   10878:         return 'ok';
                   10879:     }
                   10880:     my $reply = &put('environment', \%names, $udom,$uname);
                   10881:     if ($reply ne 'ok') { 
                   10882:         return 'error: '.$reply;
                   10883:     }
1.1087    raeburn  10884:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10885:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10886:     }
1.1075    raeburn  10887:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10888:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10889:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10890:     &logthis($logmsg);
1.134     albertel 10891:     return 'ok';
1.80      www      10892: }
                   10893: 
1.81      www      10894: # -------------------------------------------------------------- Modify student
1.80      www      10895: 
1.81      www      10896: sub modifystudent {
                   10897:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10898:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10899:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10900:     if (!$cid) {
1.620     albertel 10901: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10902: 	    return 'not_in_class';
                   10903: 	}
1.80      www      10904:     }
                   10905: # --------------------------------------------------------------- Make the user
1.81      www      10906:     my $reply=&modifyuser
1.209     matthew  10907: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10908:          $desiredhome,$email,$inststatus);
1.80      www      10909:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10910:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10911:     # student's environment
1.297     matthew  10912:     $uid = undef if (!$forceid);
1.455     albertel 10913:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10914: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10915:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10916:     return $reply;
                   10917: }
                   10918: 
                   10919: sub modify_student_enrollment {
1.1172.2.23  raeburn  10920:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10921:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10922:     my ($cdom,$cnum,$chome);
                   10923:     if (!$cid) {
1.620     albertel 10924: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10925: 	    return 'not_in_class';
                   10926: 	}
1.620     albertel 10927: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10928: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10929:     } else {
                   10930: 	($cdom,$cnum)=split(/_/,$cid);
                   10931:     }
1.620     albertel 10932:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10933:     if (!$chome) {
1.457     raeburn  10934: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10935:     }
1.455     albertel 10936:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10937:     # Make sure the user exists
1.81      www      10938:     my $uhome=&homeserver($uname,$udom);
                   10939:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10940: 	return 'error: no such user';
                   10941:     }
1.297     matthew  10942:     # Get student data if we were not given enough information
                   10943:     if (!defined($first)  || $first  eq '' || 
                   10944:         !defined($last)   || $last   eq '' || 
                   10945:         !defined($uid)    || $uid    eq '' || 
                   10946:         !defined($middle) || $middle eq '' || 
                   10947:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10948:         # They did not supply us with enough data to enroll the student, so
                   10949:         # we need to pick up more information.
1.297     matthew  10950:         my %tmp = &get('environment',
1.294     matthew  10951:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10952:                        ,$udom,$uname);
                   10953: 
1.800     albertel 10954:         #foreach my $key (keys(%tmp)) {
                   10955:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10956:         #}
1.294     matthew  10957:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10958:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10959:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10960:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10961:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10962:     }
1.556     albertel 10963:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10964:     my $user = "$uname:$udom";
                   10965:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10966:     my $reply=cput('classlist',
1.1148    raeburn  10967: 		   {$user => 
1.1172.2.76  raeburn  10968: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10969: 		   $cdom,$cnum);
1.1148    raeburn  10970:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10971:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10972:     } else { 
1.81      www      10973: 	return 'error: '.$reply;
                   10974:     }
1.297     matthew  10975:     # Add student role to user
1.83      www      10976:     my $uurl='/'.$cid;
1.81      www      10977:     $uurl=~s/\_/\//g;
                   10978:     if ($usec) {
                   10979: 	$uurl.='/'.$usec;
                   10980:     }
1.1148    raeburn  10981:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10982:                              $selfenroll,$context);
                   10983:     if ($result ne 'ok') {
                   10984:         if ($old_entry{$user} ne '') {
                   10985:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10986:         } else {
                   10987:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10988:         }
                   10989:     }
                   10990:     return $result; 
1.21      www      10991: }
                   10992: 
1.556     albertel 10993: sub format_name {
                   10994:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10995:     my $name;
                   10996:     if ($first ne 'lastname') {
                   10997: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10998:     } else {
                   10999: 	if ($lastname=~/\S/) {
                   11000: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   11001: 	    $name=~s/\s+,/,/;
                   11002: 	} else {
                   11003: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   11004: 	}
                   11005:     }
                   11006:     $name=~s/^\s+//;
                   11007:     $name=~s/\s+$//;
                   11008:     $name=~s/\s+/ /g;
                   11009:     return $name;
                   11010: }
                   11011: 
1.84      www      11012: # ------------------------------------------------- Write to course preferences
                   11013: 
                   11014: sub writecoursepref {
                   11015:     my ($courseid,%prefs)=@_;
                   11016:     $courseid=~s/^\///;
                   11017:     $courseid=~s/\_/\//g;
                   11018:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   11019:     my $chome=homeserver($cnum,$cdomain);
                   11020:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   11021: 	return 'error: no such course';
                   11022:     }
                   11023:     my $cstring='';
1.800     albertel 11024:     foreach my $pref (keys(%prefs)) {
                   11025: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 11026:     }
1.84      www      11027:     $cstring=~s/\&$//;
                   11028:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   11029: }
                   11030: 
                   11031: # ---------------------------------------------------------- Make/modify course
                   11032: 
                   11033: sub createcourse {
1.741     raeburn  11034:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.146.  .1(raebu 11035:22):         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      11036:     $url=&declutter($url);
                   11037:     my $cid='';
1.1028    raeburn  11038:     if ($context eq 'requestcourses') {
                   11039:         my $can_create = 0;
                   11040:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   11041:         if ($udom eq $ownerdom) {
1.1172.2.146.  .1(raebu 11042:22):             my $reload;
                   11043:22):             if (($callercontext eq 'auto') &&
                   11044:22):                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   11045:22):                 $reload = 'reload';
                   11046:22):             }
                   11047:22):             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  11048:                                   $context)) {
                   11049:                 $can_create = 1;
                   11050:             }
                   11051:         } else {
                   11052:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   11053:                                            $category);
                   11054:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   11055:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   11056:                 if (@curr > 0) {
                   11057:                     my @options = qw(approval validate autolimit);
                   11058:                     my $optregex = join('|',@options);
                   11059:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   11060:                         $can_create = 1;
                   11061:                     }
                   11062:                 }
                   11063:             }
                   11064:         }
                   11065:         if ($can_create) {
                   11066:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   11067:                 unless (&allowed('ccc',$udom)) {
                   11068:                     return 'refused'; 
                   11069:                 }
1.1017    raeburn  11070:             }
                   11071:         } else {
                   11072:             return 'refused';
                   11073:         }
1.1028    raeburn  11074:     } elsif (!&allowed('ccc',$udom)) {
                   11075:         return 'refused';
1.84      www      11076:     }
1.1011    raeburn  11077: # --------------------------------------------------------------- Get Unique ID
                   11078:     my $uname;
                   11079:     if ($cnum =~ /^$match_courseid$/) {
                   11080:         my $chome=&homeserver($cnum,$udom,'true');
                   11081:         if (($chome eq '') || ($chome eq 'no_host')) {
                   11082:             $uname = $cnum;
                   11083:         } else {
1.1038    raeburn  11084:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  11085:         }
                   11086:     } else {
1.1038    raeburn  11087:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  11088:     }
                   11089:     return $uname if ($uname =~ /^error/);
                   11090: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  11091:     if (!defined($course_server)) {
                   11092:         if (defined(&domain($udom,'primary'))) {
                   11093:             $course_server = &domain($udom,'primary');
                   11094:         } else {
                   11095:             $course_server = $env{'user.home'}; 
                   11096:         }
                   11097:     }
                   11098:     my %host_servers =
                   11099:         &Apache::lonnet::get_servers($udom,'library');
                   11100:     unless ($host_servers{$course_server}) {
                   11101:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  11102:     }
1.84      www      11103: # ------------------------------------------------------------- Make the course
                   11104:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  11105:                       $course_server);
1.84      www      11106:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  11107:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      11108:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   11109: 	return 'error: no such course';
                   11110:     }
1.271     www      11111: # ----------------------------------------------------------------- Course made
1.516     raeburn  11112: # log existence
1.1029    raeburn  11113:     my $now = time;
1.918     raeburn  11114:     my $newcourse = {
                   11115:                     $udom.'_'.$uname => {
1.921     raeburn  11116:                                      description => $description,
                   11117:                                      inst_code   => $inst_code,
                   11118:                                      owner       => $course_owner,
                   11119:                                      type        => $crstype,
1.1029    raeburn  11120:                                      creator     => $env{'user.name'}.':'.
                   11121:                                                     $env{'user.domain'},
                   11122:                                      created     => $now,
                   11123:                                      context     => $context,
1.918     raeburn  11124:                                                 },
                   11125:                     };
1.921     raeburn  11126:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      11127: # set toplevel url
1.271     www      11128:     my $topurl=$url;
                   11129:     unless ($nonstandard) {
                   11130: # ------------------------------------------ For standard courses, make top url
                   11131:         my $mapurl=&clutter($url);
1.278     www      11132:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 11133:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      11134: <map>
                   11135: <resource id="1" type="start"></resource>
                   11136: <resource id="2" src="$mapurl"></resource>
                   11137: <resource id="3" type="finish"></resource>
                   11138: <link index="1" from="1" to="2"></link>
                   11139: <link index="2" from="2" to="3"></link>
                   11140: </map>
                   11141: ENDINITMAP
                   11142:         $topurl=&declutter(
1.638     albertel 11143:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      11144:                           );
                   11145:     }
                   11146: # ----------------------------------------------------------- Write preferences
1.84      www      11147:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  11148:                      ('description'              => $description,
                   11149:                       'url'                      => $topurl,
                   11150:                       'internal.creator'         => $env{'user.name'}.':'.
                   11151:                                                     $env{'user.domain'},
                   11152:                       'internal.created'         => $now,
                   11153:                       'internal.creationcontext' => $context)
                   11154:                     );
1.84      www      11155:     return '/'.$udom.'/'.$uname;
                   11156: }
                   11157: 
1.1011    raeburn  11158: # ------------------------------------------------------------------- Create ID
                   11159: sub generate_coursenum {
1.1038    raeburn  11160:     my ($udom,$crstype) = @_;
1.1011    raeburn  11161:     my $domdesc = &domain($udom);
                   11162:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  11163:     my $first;
                   11164:     if ($crstype eq 'Community') {
                   11165:         $first = '0';
                   11166:     } else {
                   11167:         $first = int(1+rand(9)); 
                   11168:     } 
                   11169:     my $uname=$first.
1.1011    raeburn  11170:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11171:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11172:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11173: # ----------------------------------------------- Make sure that does not exist
                   11174:     my $uhome=&homeserver($uname,$udom,'true');
                   11175:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  11176:         if ($crstype eq 'Community') {
                   11177:             $first = '0';
                   11178:         } else {
                   11179:             $first = int(1+rand(9));
                   11180:         }
                   11181:         $uname=$first.
1.1011    raeburn  11182:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11183:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11184:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11185:         $uhome=&homeserver($uname,$udom,'true');
                   11186:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   11187:             return 'error: unable to generate unique course-ID';
                   11188:         }
                   11189:     }
                   11190:     return $uname;
                   11191: }
                   11192: 
1.813     albertel 11193: sub is_course {
1.1167    droeschl 11194:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   11195:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  11196:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   11197:     my $uhome=&homeserver($cnum,$cdom);
                   11198:     my $iscourse;
                   11199:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   11200:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   11201:     } else {
                   11202:         my $hashid = $cdom.':'.$cnum;
                   11203:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   11204:         unless (defined($cached)) {
                   11205:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   11206:                                         $cnum,undef,undef,'.');
                   11207:             $iscourse = 0;
                   11208:             if (exists($courses{$cdom.'_'.$cnum})) {
                   11209:                 $iscourse = 1;
                   11210:             }
                   11211:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   11212:         }
                   11213:     }
                   11214:     return unless($iscourse);
1.1167    droeschl 11215:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 11216: }
                   11217: 
1.1015    raeburn  11218: sub store_userdata {
                   11219:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  11220:     my $result;
1.1016    raeburn  11221:     if ($datakey ne '') {
1.1013    raeburn  11222:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  11223:             if ($udom eq '' || $uname eq '') {
                   11224:                 $udom = $env{'user.domain'};
                   11225:                 $uname = $env{'user.name'};
                   11226:             }
                   11227:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  11228:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   11229:                 $result = 'error: no_host';
                   11230:             } else {
1.1172.2.138  raeburn  11231:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  11232:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   11233: 
                   11234:                 my $namevalue='';
                   11235:                 foreach my $key (keys(%{$storehash})) {
                   11236:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   11237:                 }
                   11238:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  11239:                 unless ($namespace eq 'courserequests') {
                   11240:                     $datakey = &escape($datakey);
                   11241:                 }
1.1105    raeburn  11242:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   11243:                                   $namevalue,$uhome);
1.1013    raeburn  11244:             }
                   11245:         } else {
                   11246:             $result = 'error: data to store was not a hash reference'; 
                   11247:         }
                   11248:     } else {
                   11249:         $result= 'error: invalid requestkey'; 
                   11250:     }
                   11251:     return $result;
                   11252: }
                   11253: 
1.21      www      11254: # ---------------------------------------------------------- Assign Custom Role
                   11255: 
                   11256: sub assigncustomrole {
1.957     raeburn  11257:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11258:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  11259:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      11260: }
                   11261: 
                   11262: # ----------------------------------------------------------------- Revoke Role
                   11263: 
                   11264: sub revokerole {
1.957     raeburn  11265:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11266:     my $now=time;
1.965     raeburn  11267:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      11268: }
                   11269: 
                   11270: # ---------------------------------------------------------- Revoke Custom Role
                   11271: 
                   11272: sub revokecustomrole {
1.957     raeburn  11273:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11274:     my $now=time;
1.357     www      11275:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  11276:            $deleteflag,$selfenroll,$context);
1.17      www      11277: }
                   11278: 
1.533     banghart 11279: # ------------------------------------------------------------ Disk usage
1.535     albertel 11280: sub diskusage {
1.955     raeburn  11281:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   11282:     $directorypath =~ s/\/$//;
                   11283:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   11284:                        .&escape($getpropath).':'.&escape($uname).':'
                   11285:                        .&escape($udom),homeserver($uname,$udom));
                   11286:     if ($listing eq 'unknown_cmd') {
                   11287:         if ($getpropath) {
                   11288:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   11289:         }
                   11290:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   11291:     }
1.514     albertel 11292:     return $listing;
1.512     banghart 11293: }
                   11294: 
1.566     banghart 11295: sub is_locked {
1.1096    raeburn  11296:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 11297:     my @check;
                   11298:     my $is_locked;
1.1093    raeburn  11299:     push (@check,$file_name);
1.613     albertel 11300:     my %locked = &get('file_permissions',\@check,
1.620     albertel 11301: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 11302:     my ($tmp)=keys(%locked);
                   11303:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  11304:     
1.566     banghart 11305:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  11306:         $is_locked = 'false';
                   11307:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  11308:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  11309:                $is_locked = 'true';
1.1096    raeburn  11310:                if (ref($which) eq 'ARRAY') {
                   11311:                    push(@{$which},$entry);
                   11312:                } else {
                   11313:                    last;
                   11314:                }
1.745     raeburn  11315:            }
                   11316:        }
1.566     banghart 11317:     } else {
                   11318:         $is_locked = 'false';
                   11319:     }
1.1093    raeburn  11320:     return $is_locked;
1.566     banghart 11321: }
                   11322: 
1.759     albertel 11323: sub declutter_portfile {
                   11324:     my ($file) = @_;
1.833     albertel 11325:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 11326:     return $file;
                   11327: }
                   11328: 
1.559     banghart 11329: # ------------------------------------------------------------- Mark as Read Only
                   11330: 
                   11331: sub mark_as_readonly {
                   11332:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 11333:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11334:     my ($tmp)=keys(%current_permissions);
                   11335:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 11336:     foreach my $file (@{$files}) {
1.759     albertel 11337: 	$file = &declutter_portfile($file);
1.561     banghart 11338:         push(@{$current_permissions{$file}},$what);
1.559     banghart 11339:     }
1.613     albertel 11340:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11341:     return;
                   11342: }
                   11343: 
1.572     banghart 11344: # ------------------------------------------------------------Save Selected Files
                   11345: 
                   11346: sub save_selected_files {
                   11347:     my ($user, $path, @files) = @_;
                   11348:     my $filename = $user."savedfiles";
1.573     banghart 11349:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  11350:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 11351:     foreach my $file (@files) {
1.620     albertel 11352:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 11353:     }
                   11354:     foreach my $file (@other_files) {
1.574     banghart 11355:         print (OUT $file."\n");
1.572     banghart 11356:     }
1.574     banghart 11357:     close (OUT);
1.572     banghart 11358:     return 'ok';
                   11359: }
                   11360: 
1.574     banghart 11361: sub clear_selected_files {
                   11362:     my ($user) = @_;
                   11363:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  11364:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 11365:     print (OUT undef);
                   11366:     close (OUT);
                   11367:     return ("ok");    
                   11368: }
                   11369: 
1.572     banghart 11370: sub files_in_path {
                   11371:     my ($user, $path) = @_;
                   11372:     my $filename = $user."savedfiles";
                   11373:     my %return_files;
1.1172.2.96  raeburn  11374:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 11375:     while (my $line_in = <IN>) {
1.574     banghart 11376:         chomp ($line_in);
                   11377:         my @paths_and_file = split (m!/!, $line_in);
                   11378:         my $file_part = pop (@paths_and_file);
                   11379:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 11380:         $path_part.='/';
                   11381:         my $path_and_file = $path_part.$file_part;
                   11382:         if ($path_part eq $path) {
                   11383:             $return_files{$file_part}= 'selected';
                   11384:         }
                   11385:     }
1.574     banghart 11386:     close (IN);
                   11387:     return (\%return_files);
1.572     banghart 11388: }
                   11389: 
                   11390: # called in portfolio select mode, to show files selected NOT in current directory
                   11391: sub files_not_in_path {
                   11392:     my ($user, $path) = @_;
                   11393:     my $filename = $user."savedfiles";
                   11394:     my @return_files;
                   11395:     my $path_part;
1.1172.2.96  raeburn  11396:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 11397:     while (my $line = <IN>) {
1.572     banghart 11398:         #ok, I know it's clunky, but I want it to work
1.800     albertel 11399:         my @paths_and_file = split(m|/|, $line);
                   11400:         my $file_part = pop(@paths_and_file);
                   11401:         chomp($file_part);
                   11402:         my $path_part = join('/', @paths_and_file);
1.572     banghart 11403:         $path_part .= '/';
                   11404:         my $path_and_file = $path_part.$file_part;
                   11405:         if ($path_part ne $path) {
1.800     albertel 11406:             push(@return_files, ($path_and_file));
1.572     banghart 11407:         }
                   11408:     }
1.800     albertel 11409:     close(OUT);
1.574     banghart 11410:     return (@return_files);
1.572     banghart 11411: }
                   11412: 
1.745     raeburn  11413: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11414: 
1.745     raeburn  11415: sub get_portfile_permissions {
                   11416:     my ($domain,$user) = @_;
1.613     albertel 11417:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11418:     my ($tmp)=keys(%current_permissions);
                   11419:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11420:     return \%current_permissions;
                   11421: }
                   11422: 
                   11423: #---------------------------------------------Get portfolio file access controls
                   11424: 
1.749     raeburn  11425: sub get_access_controls {
1.745     raeburn  11426:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11427:     my %access;
                   11428:     my $real_file = $file;
                   11429:     $file =~ s/\.meta$//;
1.745     raeburn  11430:     if (defined($file)) {
1.749     raeburn  11431:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11432:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11433:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11434:             }
                   11435:         }
1.745     raeburn  11436:     } else {
1.749     raeburn  11437:         foreach my $key (keys(%{$current_permissions})) {
                   11438:             if ($key =~ /\0accesscontrol$/) {
                   11439:                 if (defined($group)) {
                   11440:                     if ($key !~ m-^\Q$group\E/-) {
                   11441:                         next;
                   11442:                     }
                   11443:                 }
                   11444:                 my ($fullpath) = split(/\0/,$key);
                   11445:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11446:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11447:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11448:                     }
                   11449:                 }
                   11450:             }
                   11451:         }
                   11452:     }
                   11453:     return %access;
                   11454: }
                   11455: 
                   11456: sub modify_access_controls {
                   11457:     my ($file_name,$changes,$domain,$user)=@_;
                   11458:     my ($outcome,$deloutcome);
                   11459:     my %store_permissions;
                   11460:     my %new_values;
                   11461:     my %new_control;
                   11462:     my %translation;
                   11463:     my @deletions = ();
                   11464:     my $now = time;
                   11465:     if (exists($$changes{'activate'})) {
                   11466:         if (ref($$changes{'activate'}) eq 'HASH') {
                   11467:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   11468:             my $numnew = scalar(@newitems);
                   11469:             for (my $i=0; $i<$numnew; $i++) {
                   11470:                 my $newkey = $newitems[$i];
                   11471:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  11472:                 if ($newkey =~ /^\d+:/) { 
                   11473:                     $newkey =~ s/^(\d+)/$newid/;
                   11474:                     $translation{$1} = $newid;
                   11475:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   11476:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   11477:                     $translation{$1} = $newid;
                   11478:                 }
1.749     raeburn  11479:                 $new_values{$file_name."\0".$newkey} = 
                   11480:                                           $$changes{'activate'}{$newitems[$i]};
                   11481:                 $new_control{$newkey} = $now;
                   11482:             }
                   11483:         }
                   11484:     }
                   11485:     my %todelete;
                   11486:     my %changed_items;
                   11487:     foreach my $action ('delete','update') {
                   11488:         if (exists($$changes{$action})) {
                   11489:             if (ref($$changes{$action}) eq 'HASH') {
                   11490:                 foreach my $key (keys(%{$$changes{$action}})) {
                   11491:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   11492:                     if ($action eq 'delete') { 
                   11493:                         $todelete{$itemnum} = 1;
                   11494:                     } else {
                   11495:                         $changed_items{$itemnum} = $key;
                   11496:                     }
                   11497:                 }
1.745     raeburn  11498:             }
                   11499:         }
1.749     raeburn  11500:     }
                   11501:     # get lock on access controls for file.
                   11502:     my $lockhash = {
                   11503:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   11504:                                                        ':'.$env{'user.domain'},
                   11505:                    }; 
                   11506:     my $tries = 0;
                   11507:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11508:    
1.1172.2.79  raeburn  11509:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  11510:         $tries ++;
1.1172.2.79  raeburn  11511:         sleep(0.1);
1.749     raeburn  11512:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11513:     }
                   11514:     if ($gotlock eq 'ok') {
                   11515:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   11516:         my ($tmp)=keys(%curr_permissions);
                   11517:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   11518:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   11519:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   11520:             if (ref($curr_controls) eq 'HASH') {
                   11521:                 foreach my $control_item (keys(%{$curr_controls})) {
                   11522:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   11523:                     if (defined($todelete{$itemnum})) {
                   11524:                         push(@deletions,$file_name."\0".$control_item);
                   11525:                     } else {
                   11526:                         if (defined($changed_items{$itemnum})) {
                   11527:                             $new_control{$changed_items{$itemnum}} = $now;
                   11528:                             push(@deletions,$file_name."\0".$control_item);
                   11529:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   11530:                         } else {
                   11531:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   11532:                         }
                   11533:                     }
1.745     raeburn  11534:                 }
                   11535:             }
                   11536:         }
1.970     raeburn  11537:         my ($group);
                   11538:         if (&is_course($domain,$user)) {
                   11539:             ($group,my $file) = split(/\//,$file_name,2);
                   11540:         }
1.749     raeburn  11541:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   11542:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   11543:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   11544:         #  remove lock
                   11545:         my @del_lock = ($file_name."\0".'locked_access_records');
                   11546:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  11547:         my $sqlresult =
1.970     raeburn  11548:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  11549:                                     $group);
1.749     raeburn  11550:     } else {
                   11551:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  11552:     }
1.749     raeburn  11553:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  11554: }
                   11555: 
1.827     raeburn  11556: sub make_public_indefinitely {
                   11557:     my ($requrl) = @_;
                   11558:     my $now = time;
                   11559:     my $action = 'activate';
                   11560:     my $aclnum = 0;
                   11561:     if (&is_portfolio_url($requrl)) {
                   11562:         my (undef,$udom,$unum,$file_name,$group) =
                   11563:             &parse_portfolio_url($requrl);
                   11564:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   11565:         my %access_controls = &get_access_controls($current_perms,
                   11566:                                                    $group,$file_name);
                   11567:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11568:             my ($num,$scope,$end,$start) = 
                   11569:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   11570:             if ($scope eq 'public') {
                   11571:                 if ($start <= $now && $end == 0) {
                   11572:                     $action = 'none';
                   11573:                 } else {
                   11574:                     $action = 'update';
                   11575:                     $aclnum = $num;
                   11576:                 }
                   11577:                 last;
                   11578:             }
                   11579:         }
                   11580:         if ($action eq 'none') {
                   11581:              return 'ok';
                   11582:         } else {
                   11583:             my %changes;
                   11584:             my $newend = 0;
                   11585:             my $newstart = $now;
                   11586:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   11587:             $changes{$action}{$newkey} = {
                   11588:                 type => 'public',
                   11589:                 time => {
                   11590:                     start => $newstart,
                   11591:                     end   => $newend,
                   11592:                 },
                   11593:             };
                   11594:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11595:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   11596:             return $outcome;
                   11597:         }
                   11598:     } else {
                   11599:         return 'invalid';
                   11600:     }
                   11601: }
                   11602: 
1.745     raeburn  11603: #------------------------------------------------------Get Marked as Read Only
                   11604: 
                   11605: sub get_marked_as_readonly {
                   11606:     my ($domain,$user,$what,$group) = @_;
                   11607:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11608:     my @readonly_files;
1.629     banghart 11609:     my $cmp1=$what;
                   11610:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11611:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11612:         if (defined($group)) {
                   11613:             if ($file_name !~ m-^\Q$group\E/-) {
                   11614:                 next;
                   11615:             }
                   11616:         }
1.561     banghart 11617:         if (ref($value) eq "ARRAY"){
                   11618:             foreach my $stored_what (@{$value}) {
1.629     banghart 11619:                 my $cmp2=$stored_what;
1.759     albertel 11620:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11621:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11622:                 }
1.629     banghart 11623:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11624:                     push(@readonly_files, $file_name);
1.745     raeburn  11625:                     last;
1.563     banghart 11626:                 } elsif (!defined($what)) {
                   11627:                     push(@readonly_files, $file_name);
1.745     raeburn  11628:                     last;
1.561     banghart 11629:                 }
                   11630:             }
1.745     raeburn  11631:         }
1.561     banghart 11632:     }
                   11633:     return @readonly_files;
                   11634: }
1.577     banghart 11635: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11636: 
1.577     banghart 11637: sub get_marked_as_readonly_hash {
1.745     raeburn  11638:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11639:     my %readonly_files;
1.745     raeburn  11640:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11641:         if (defined($group)) {
                   11642:             if ($file_name !~ m-^\Q$group\E/-) {
                   11643:                 next;
                   11644:             }
                   11645:         }
1.577     banghart 11646:         if (ref($value) eq "ARRAY"){
                   11647:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11648:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11649:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11650:                         if ($lock_descriptor eq 'graded') {
                   11651:                             $readonly_files{$file_name} = 'graded';
                   11652:                         } elsif ($lock_descriptor eq 'handback') {
                   11653:                             $readonly_files{$file_name} = 'handback';
                   11654:                         } else {
                   11655:                             if (!exists($readonly_files{$file_name})) {
                   11656:                                 $readonly_files{$file_name} = 'locked';
                   11657:                             }
                   11658:                         }
1.745     raeburn  11659:                     }
1.750     banghart 11660:                 } 
1.577     banghart 11661:             }
                   11662:         } 
                   11663:     }
                   11664:     return %readonly_files;
                   11665: }
1.559     banghart 11666: # ------------------------------------------------------------ Unmark as Read Only
                   11667: 
                   11668: sub unmark_as_readonly {
1.629     banghart 11669:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11670:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11671:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11672:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11673:     my $symb_crs = $what;
                   11674:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11675:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11676:     my ($tmp)=keys(%current_permissions);
                   11677:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11678:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11679:     foreach my $file (@readonly_files) {
1.759     albertel 11680: 	my $clean_file = &declutter_portfile($file);
                   11681: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11682: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11683:         my @new_locks;
                   11684:         my @del_keys;
                   11685:         if (ref($current_locks) eq "ARRAY"){
                   11686:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11687:                 my $compare=$locker;
1.749     raeburn  11688:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11689:                     $compare=join('',@{$locker});
1.746     raeburn  11690:                     if ($compare ne $symb_crs) {
                   11691:                         push(@new_locks, $locker);
                   11692:                     }
1.563     banghart 11693:                 }
                   11694:             }
1.650     albertel 11695:             if (scalar(@new_locks) > 0) {
1.563     banghart 11696:                 $current_permissions{$file} = \@new_locks;
                   11697:             } else {
                   11698:                 push(@del_keys, $file);
1.613     albertel 11699:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11700:                 delete($current_permissions{$file});
1.563     banghart 11701:             }
                   11702:         }
1.561     banghart 11703:     }
1.613     albertel 11704:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11705:     return;
                   11706: }
1.512     banghart 11707: 
1.17      www      11708: # ------------------------------------------------------------ Directory lister
                   11709: 
                   11710: sub dirlist {
1.955     raeburn  11711:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11712:     $uri=~s/^\///;
                   11713:     $uri=~s/\/$//;
1.253     stredwic 11714:     my ($udom, $uname);
1.955     raeburn  11715:     if ($getuserdir) {
1.253     stredwic 11716:         $udom = $userdomain;
                   11717:         $uname = $username;
1.955     raeburn  11718:     } else {
                   11719:         (undef,$udom,$uname)=split(/\//,$uri);
                   11720:         if(defined($userdomain)) {
                   11721:             $udom = $userdomain;
                   11722:         }
                   11723:         if(defined($username)) {
                   11724:             $uname = $username;
                   11725:         }
1.253     stredwic 11726:     }
1.955     raeburn  11727:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11728: 
1.955     raeburn  11729:     $dirRoot = $perlvar{'lonDocRoot'};
                   11730:     if (defined($getpropath)) {
                   11731:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11732:         $dirRoot =~ s/\/$//;
1.955     raeburn  11733:     } elsif (defined($getuserdir)) {
                   11734:         my $subdir=$uname.'__';
                   11735:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11736:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11737:                    ."/$udom/$subdir/$uname";
                   11738:     } elsif (defined($alternateRoot)) {
                   11739:         $dirRoot = $alternateRoot;
1.751     banghart 11740:     }
1.253     stredwic 11741: 
                   11742:     if($udom) {
                   11743:         if($uname) {
1.1135    raeburn  11744:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11745:             if ($uhome eq 'no_host') {
                   11746:                 return ([],'no_host');
                   11747:             }
1.955     raeburn  11748:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11749:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11750:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11751:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11752:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11753:             } else {
                   11754:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11755:             }
1.605     matthew  11756:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11757:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11758:                 @listing_results = split(/:/,$listing);
                   11759:             } else {
                   11760:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11761:             }
1.1135    raeburn  11762:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11763:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11764:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11765:                 return ([],$listing);
                   11766:             } else {
                   11767:                 return (\@listing_results);
1.1135    raeburn  11768:             }
1.955     raeburn  11769:         } elsif(!$alternateRoot) {
1.1136    raeburn  11770:             my (%allusers,%listerror);
1.841     albertel 11771: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11772:  	    foreach my $tryserver (keys(%servers)) {
                   11773:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11774:                                   &escape($udom),$tryserver);
                   11775:                 if ($listing eq 'unknown_cmd') {
                   11776: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11777: 				      $udom, $tryserver);
                   11778:                 } else {
                   11779:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11780:                 }
1.841     albertel 11781: 		if ($listing eq 'unknown_cmd') {
                   11782: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11783: 				      $udom, $tryserver);
                   11784: 		    @listing_results = split(/:/,$listing);
                   11785: 		} else {
                   11786: 		    @listing_results =
                   11787: 			map { &unescape($_); } split(/:/,$listing);
                   11788: 		}
1.1136    raeburn  11789:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11790:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11791:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11792:                     $listerror{$tryserver} = $listing;
                   11793:                 } else {
1.841     albertel 11794: 		    foreach my $line (@listing_results) {
                   11795: 			my ($entry) = split(/&/,$line,2);
                   11796: 			$allusers{$entry} = 1;
                   11797: 		    }
                   11798: 		}
1.253     stredwic 11799:             }
1.1136    raeburn  11800:             my @alluserslist=();
1.800     albertel 11801:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11802:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11803:             }
1.1172.2.80  raeburn  11804:             if (!%listerror) {
                   11805:                 # no errors
                   11806:                 return (\@alluserslist);
                   11807:             } elsif (scalar(keys(%servers)) == 1) {
                   11808:                 # one library server, one error
                   11809:                 my ($key) = keys(%listerror);
                   11810:                 return (\@alluserslist, $listerror{$key});
                   11811:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11812:                 # con_lost indicates that we might miss data from at least one
                   11813:                 # library server
                   11814:                 return (\@alluserslist, 'con_lost');
                   11815:             } else {
                   11816:                 # multiple library servers and no con_lost -> data should be
                   11817:                 # complete.
                   11818:                 return (\@alluserslist);
                   11819:             }
                   11820: 
1.253     stredwic 11821:         } else {
1.1136    raeburn  11822:             return ([],'missing username');
1.253     stredwic 11823:         }
1.955     raeburn  11824:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11825:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11826:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11827:         return (\@all_domains);
1.955     raeburn  11828:     } else {
1.1136    raeburn  11829:         return ([],'missing domain');
1.275     stredwic 11830:     }
                   11831: }
                   11832: 
                   11833: # --------------------------------------------- GetFileTimestamp
                   11834: # This function utilizes dirlist and returns the date stamp for
                   11835: # when it was last modified.  It will also return an error of -1
                   11836: # if an error occurs
                   11837: 
                   11838: sub GetFileTimestamp {
1.955     raeburn  11839:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11840:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11841:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11842:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11843:                                     undef,$getuserdir);
                   11844:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11845:         return -1;
                   11846:     }
                   11847:     if (ref($fileref) eq 'ARRAY') {
                   11848:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11849:         # @stats contains first the filename, then the stat output
                   11850:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11851:     } else {
                   11852:         return -1;
1.253     stredwic 11853:     }
1.26      www      11854: }
                   11855: 
1.712     albertel 11856: sub stat_file {
                   11857:     my ($uri) = @_;
1.787     albertel 11858:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11859: 
1.955     raeburn  11860:     my ($udom,$uname,$file);
1.712     albertel 11861:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11862: 	($udom,$uname,$file) =
1.811     albertel 11863: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11864: 	$file = 'userfiles/'.$file;
                   11865:     }
                   11866:     if ($uri =~ m-^/res/-) {
                   11867: 	($udom,$uname) = 
1.807     albertel 11868: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11869: 	$file = $uri;
                   11870:     }
                   11871: 
                   11872:     if (!$udom || !$uname || !$file) {
                   11873: 	# unable to handle the uri
                   11874: 	return ();
                   11875:     }
1.956     raeburn  11876:     my $getpropath;
                   11877:     if ($file =~ /^userfiles\//) {
                   11878:         $getpropath = 1;
                   11879:     }
1.1136    raeburn  11880:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11881:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11882:         return ();
                   11883:     } else {
                   11884:         if (ref($listref) eq 'ARRAY') {
                   11885:             my @stats = split('&',$listref->[0]);
                   11886: 	    shift(@stats); #filename is first
                   11887: 	    return @stats;
                   11888:         }
1.712     albertel 11889:     }
                   11890:     return ();
                   11891: }
                   11892: 
1.26      www      11893: # -------------------------------------------------------- Value of a Condition
                   11894: 
1.713     albertel 11895: # gets the value of a specific preevaluated condition
                   11896: #    stored in the string  $env{user.state.<cid>}
                   11897: # or looks up a condition reference in the bighash and if if hasn't
                   11898: # already been evaluated recurses into docondval to get the value of
                   11899: # the condition, then memoizing it to 
                   11900: #   $env{user.state.<cid>.<condition>}
1.40      www      11901: sub directcondval {
                   11902:     my $number=shift;
1.620     albertel 11903:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11904: 	&Apache::lonuserstate::evalstate();
                   11905:     }
1.713     albertel 11906:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11907: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11908:     } elsif ($number =~ /^_/) {
                   11909: 	my $sub_condition;
                   11910: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11911: 		&GDBM_READER(),0640)) {
                   11912: 	    $sub_condition=$bighash{'conditions'.$number};
                   11913: 	    untie(%bighash);
                   11914: 	}
                   11915: 	my $value = &docondval($sub_condition);
1.949     raeburn  11916: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11917: 	return $value;
                   11918:     }
1.620     albertel 11919:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11920:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11921:     } else {
                   11922:        return 2;
                   11923:     }
                   11924: }
                   11925: 
1.713     albertel 11926: # get the collection of conditions for this resource
1.26      www      11927: sub condval {
                   11928:     my $condidx=shift;
1.54      www      11929:     my $allpathcond='';
1.713     albertel 11930:     foreach my $cond (split(/\|/,$condidx)) {
                   11931: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11932: 	    $allpathcond.=
                   11933: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11934: 	}
1.191     harris41 11935:     }
1.54      www      11936:     $allpathcond=~s/\|$//;
1.713     albertel 11937:     return &docondval($allpathcond);
                   11938: }
                   11939: 
                   11940: #evaluates an expression of conditions
                   11941: sub docondval {
                   11942:     my ($allpathcond) = @_;
                   11943:     my $result=0;
                   11944:     if ($env{'request.course.id'}
                   11945: 	&& defined($allpathcond)) {
                   11946: 	my $operand='|';
                   11947: 	my @stack;
                   11948: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11949: 	    if ($chunk eq '(') {
                   11950: 		push @stack,($operand,$result);
                   11951: 	    } elsif ($chunk eq ')') {
                   11952: 		my $before=pop @stack;
                   11953: 		if (pop @stack eq '&') {
                   11954: 		    $result=$result>$before?$before:$result;
                   11955: 		} else {
                   11956: 		    $result=$result>$before?$result:$before;
                   11957: 		}
                   11958: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11959: 		$operand=$chunk;
                   11960: 	    } else {
                   11961: 		my $new=directcondval($chunk);
                   11962: 		if ($operand eq '&') {
                   11963: 		    $result=$result>$new?$new:$result;
                   11964: 		} else {
                   11965: 		    $result=$result>$new?$result:$new;
                   11966: 		}
                   11967: 	    }
                   11968: 	}
1.26      www      11969:     }
                   11970:     return $result;
1.421     albertel 11971: }
                   11972: 
                   11973: # ---------------------------------------------------- Devalidate courseresdata
                   11974: 
                   11975: sub devalidatecourseresdata {
                   11976:     my ($coursenum,$coursedomain)=@_;
                   11977:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11978:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11979: }
                   11980: 
1.763     www      11981: 
1.200     www      11982: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11983: #
                   11984: #  Parameters:
                   11985: #      $coursenum    - Number of the course.
                   11986: #      $coursedomain - Domain at which the course was created.
                   11987: #  Returns:
                   11988: #     A hash of the course parameters along (I think) with timestamps
                   11989: #     and version info.
1.877     foxr     11990: 
1.624     albertel 11991: sub get_courseresdata {
                   11992:     my ($coursenum,$coursedomain)=@_;
1.200     www      11993:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11994:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11995:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11996:     my %dumpreply;
1.417     albertel 11997:     unless (defined($cached)) {
1.624     albertel 11998: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11999: 	$result=\%dumpreply;
1.251     albertel 12000: 	my ($tmp) = keys(%dumpreply);
                   12001: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 12002: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 12003: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   12004: 	    return $tmp;
1.416     albertel 12005: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 12006: 	    $result=undef;
1.599     albertel 12007: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 12008: 	}
                   12009:     }
1.624     albertel 12010:     return $result;
                   12011: }
                   12012: 
1.633     albertel 12013: sub devalidateuserresdata {
                   12014:     my ($uname,$udom)=@_;
                   12015:     my $hashid="$udom:$uname";
                   12016:     &devalidate_cache_new('userres',$hashid);
                   12017: }
                   12018: 
1.624     albertel 12019: sub get_userresdata {
                   12020:     my ($uname,$udom)=@_;
                   12021:     #most student don\'t have any data set, check if there is some data
                   12022:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   12023: 
                   12024:     my $hashid="$udom:$uname";
                   12025:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   12026:     if (!defined($cached)) {
                   12027: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   12028: 	$result=\%resourcedata;
                   12029: 	&do_cache_new('userres',$hashid,$result,600);
                   12030:     }
                   12031:     my ($tmp)=keys(%$result);
                   12032:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   12033: 	return $result;
                   12034:     }
                   12035:     #error 2 occurs when the .db doesn't exist
                   12036:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  12037:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   12038: 	    &logthis("<font color=\"blue\">WARNING:".
                   12039: 		     " Trying to get resource data for ".
                   12040: 		     $uname." at ".$udom.": ".
                   12041: 		     $tmp."</font>");
                   12042:         }
1.624     albertel 12043:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 12044: 	#&EXT_cache_set($udom,$uname);
                   12045: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 12046: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 12047:     }
                   12048:     return $tmp;
                   12049: }
1.879     foxr     12050: #----------------------------------------------- resdata - return resource data
                   12051: #  Purpose:
                   12052: #    Return resource data for either users or for a course.
                   12053: #  Parameters:
                   12054: #     $name      - Course/user name.
                   12055: #     $domain    - Name of the domain the user/course is registered on.
                   12056: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   12057: #     @which     - Array of names of resources desired.
                   12058: #  Returns:
                   12059: #     The value of the first reasource in @which that is found in the
                   12060: #     resource hash.
                   12061: #  Exceptional Conditions:
                   12062: #     If the $type passed in is not valid (not the string 'course' or 
                   12063: #     'user', an undefined  reference is returned.
                   12064: #     If none of the resources are found, an undef is returned
1.624     albertel 12065: sub resdata {
                   12066:     my ($name,$domain,$type,@which)=@_;
                   12067:     my $result;
                   12068:     if ($type eq 'course') {
                   12069: 	$result=&get_courseresdata($name,$domain);
                   12070:     } elsif ($type eq 'user') {
                   12071: 	$result=&get_userresdata($name,$domain);
                   12072:     }
                   12073:     if (!ref($result)) { return $result; }    
1.251     albertel 12074:     foreach my $item (@which) {
1.927     albertel 12075: 	if (defined($result->{$item->[0]})) {
                   12076: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 12077: 	}
1.250     albertel 12078:     }
1.291     albertel 12079:     return undef;
1.200     www      12080: }
                   12081: 
1.1172.2.146.  .1(raebu 12082:22): sub get_domain_lti {
                   12083:22):     my ($cdom,$context) = @_;
          .4(raebu 12084:22):     my ($name,$cachename,%lti);
          .1(raebu 12085:22):     if ($context eq 'consumer') {
                   12086:22):         $name = 'ltitools';
                   12087:22):     } elsif ($context eq 'provider') {
                   12088:22):         $name = 'lti';
          .4(raebu 12089:22):     } elsif ($context eq 'linkprot') {
                   12090:22):         $name = 'ltisec';
          .1(raebu 12091:22):     } else {
                   12092:22):         return %lti;
                   12093:22):     }
          .4(raebu 12094:22):     if ($context eq 'linkprot') {
                   12095:22):         $cachename = $context;
                   12096:22):     } else {
                   12097:22):         $cachename = $name;
                   12098:22):     }
                   12099:22):     my ($result,$cached)=&is_cached_new($cachename,$cdom);
          .1(raebu 12100:22):     if (defined($cached)) {
                   12101:22):         if (ref($result) eq 'HASH') {
                   12102:22):             %lti = %{$result};
                   12103:22):         }
                   12104:22):     } else {
                   12105:22):         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   12106:22):         if (ref($domconfig{$name}) eq 'HASH') {
          .4(raebu 12107:22):             if ($context eq 'linkprot') {
                   12108:22):                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
                   12109:22):                     %lti = %{$domconfig{$name}{'linkprot'}};
                   12110:22):                 }
                   12111:22):             } else {
                   12112:22):                 %lti = %{$domconfig{$name}};
                   12113:22):             }
          .1(raebu 12114:22):         }
                   12115:22):         my $cachetime = 24*60*60;
          .4(raebu 12116:22):         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
          .1(raebu 12117:22):     }
                   12118:22):     return %lti;
                   12119:22): }
                   12120:22): 
                   12121:22): sub get_course_lti {
          .13(raeb 12122:-23):     my ($cnum,$cdom,$context) = @_;
                   12123:-23):     my ($name,$cachename,%lti);
                   12124:-23):     if ($context eq 'consumer') {
                   12125:-23):         $name = 'ltitools';
                   12126:-23):         $cachename = 'courseltitools';
                   12127:-23):     } elsif ($context eq 'provider') {
                   12128:-23):         $name = 'lti';
                   12129:-23):         $cachename = 'courselti';
                   12130:-23):     } else {
                   12131:-23):         return %lti;
                   12132:-23):     }
          .1(raebu 12133:22):     my $hashid=$cdom.'_'.$cnum;
          .13(raeb 12134:-23):     my ($result,$cached)=&is_cached_new($cachename,$hashid);
          .1(raebu 12135:22):     if (defined($cached)) {
                   12136:22):         if (ref($result) eq 'HASH') {
          .13(raeb 12137:-23):             %lti = %{$result};
          .1(raebu 12138:22):         }
                   12139:22):     } else {
          .13(raeb 12140:-23):         %lti = &dump($name,$cdom,$cnum,undef,undef,undef,1);
          .1(raebu 12141:22):         my $cachetime = 24*60*60;
          .13(raeb 12142:-23):         &do_cache_new($cachename,$hashid,\%lti,$cachetime);
          .1(raebu 12143:22):     }
          .13(raeb 12144:-23):     return %lti;
          .1(raebu 12145:22): }
                   12146:22): 
          .3(raebu 12147:22): sub courselti_itemid {
                   12148:22):     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
                   12149:22):     my ($chome,$itemid);
                   12150:22):     $chome = &homeserver($cnum,$cdom);
                   12151:22):     return if ($chome eq 'no_host');
                   12152:22):     if (ref($params) eq 'HASH') {
                   12153:22):         my $rep;
                   12154:22):         if (grep { $_ eq $chome } current_machine_ids()) {
                   12155:22):             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
                   12156:22):         } else {
                   12157:22):             my $escurl = &escape($url);
                   12158:22):             my $escmethod = &escape($method);
                   12159:22):             my $items = &freeze_escape($params);
                   12160:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
                   12161:22):         }
                   12162:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   12163:22):                 ($rep eq 'unknown_cmd')) {
                   12164:22):             $itemid = $rep;
                   12165:22):         }
                   12166:22):     }
                   12167:22):     return $itemid;
                   12168:22): }
                   12169:22): 
                   12170:22): sub domainlti_itemid {
                   12171:22):     my ($cdom,$url,$method,$params,$context) = @_;
                   12172:22):     my ($primary_id,$itemid);
                   12173:22):     $primary_id = &domain($cdom,'primary');
                   12174:22):     return if ($primary_id eq '');
                   12175:22):     if (ref($params) eq 'HASH') {
                   12176:22):         my $rep;
                   12177:22):         if (grep { $_ eq $primary_id } current_machine_ids()) {
                   12178:22):             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
                   12179:22):         } else {
                   12180:22):             my $cnum = '';
                   12181:22):             my $escurl = &escape($url);
                   12182:22):             my $escmethod = &escape($method);
                   12183:22):             my $items = &freeze_escape($params);
                   12184:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
                   12185:22):         }
                   12186:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   12187:22):                 ($rep eq 'unknown_cmd')) {
                   12188:22):             $itemid = $rep;
                   12189:22):         }
                   12190:22):     }
                   12191:22):     return $itemid;
                   12192:22): }
                   12193:22): 
          .15(raeb 12194:-23): sub get_ltitools_id {
                   12195:-23):     my ($context,$cdom,$cnum,$title) = @_;
                   12196:-23):     my ($lockhash,$tries,$gotlock,$id,$error);
                   12197:-23): 
                   12198:-23):     # get lock on ltitools db
                   12199:-23):     $lockhash = {
                   12200:-23):                    lock => $env{'user.name'}.
                   12201:-23):                            ':'.$env{'user.domain'},
                   12202:-23):                 };
                   12203:-23):     $tries = 0;
                   12204:-23):     if ($context eq 'domain') {
                   12205:-23):         $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
                   12206:-23):     } else {
                   12207:-23):         $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
                   12208:-23):     }
                   12209:-23):     while (($gotlock ne 'ok') && ($tries<10)) {
                   12210:-23):         $tries ++;
                   12211:-23):         sleep (0.1);
                   12212:-23):         if ($context eq 'domain') {
                   12213:-23):             $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
                   12214:-23):         } else {
                   12215:-23):             $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
                   12216:-23):         }
                   12217:-23):     }
                   12218:-23):     if ($gotlock eq 'ok') {
                   12219:-23):         my %currids;
                   12220:-23):         if ($context eq 'domain') {
                   12221:-23):             %currids = &dump_dom('ltitools',$cdom);
                   12222:-23):         } else {
                   12223:-23):             %currids = &dump('ltitools',$cdom,$cnum);
                   12224:-23):         }
                   12225:-23):         if ($currids{'lock'}) {
                   12226:-23):             delete($currids{'lock'});
                   12227:-23):             if (keys(%currids)) {
                   12228:-23):                 my @curr = sort { $a <=> $b } keys(%currids);
                   12229:-23):                 if ($curr[-1] =~ /^\d+$/) {
                   12230:-23):                     $id = 1 + $curr[-1];
                   12231:-23):                 }
                   12232:-23):             } else {
                   12233:-23):                 $id = 1;
                   12234:-23):             }
                   12235:-23):             if ($id) {
                   12236:-23):                 if ($context eq 'domain') {
                   12237:-23):                     unless (&newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
                   12238:-23):                         $error = 'nostore';
                   12239:-23):                     }
                   12240:-23):                 } else {
                   12241:-23):                     unless (&newput('ltitools',{ $id => $title },$cdom,$cnum) eq 'ok') {
                   12242:-23):                         $error = 'nostore';
                   12243:-23):                     }
                   12244:-23):                 }
                   12245:-23):             } else {
                   12246:-23):                 $error = 'nonumber';
                   12247:-23):             }
                   12248:-23):         }
                   12249:-23):         my $dellockoutcome;
                   12250:-23):         if ($context eq 'domain') {
                   12251:-23):             $dellockoutcome = &del_dom('ltitools',['lock'],$cdom);
                   12252:-23):         } else {
                   12253:-23):             $dellockoutcome = &del('ltitools',['lock'],$cdom,$cnum);
                   12254:-23):         }
                   12255:-23):     } else {
                   12256:-23):         $error = 'nolock';
                   12257:-23):     }
                   12258:-23):     return ($id,$error);
                   12259:-23): }
                   12260:-23): 
          .9(raebu 12261:23): sub count_supptools {
                   12262:23):     my ($cnum,$cdom,$ignorecache,$reload)=@_;
1.1172.2.31  raeburn  12263:     my $hashid=$cnum.':'.$cdom;
1.1172.2.146.  .9(raebu 12264:23):     my ($numexttools,$cached);
1.1172.2.31  raeburn  12265:     unless ($ignorecache) {
1.1172.2.146.  .9(raebu 12266:23):         ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
1.1172.2.31  raeburn  12267:     }
                   12268:     unless (defined($cached)) {
                   12269:         my $chome=&homeserver($cnum,$cdom);
1.1172.2.146.  .9(raebu 12270:23):         $numexttools = 0;
1.1172.2.31  raeburn  12271:         unless ($chome eq 'no_host') {
1.1172.2.146.  .9(raebu 12272:23):             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
                   12273:23):             if (ref($supplemental) eq 'HASH') {
                   12274:23):                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   12275:23):                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
                   12276:23):                         if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   12277:23):                             $numexttools ++;
                   12278:23):                         }
                   12279:23):                     }
                   12280:23):                 }
                   12281:23):             }
1.1172.2.31  raeburn  12282:         }
1.1172.2.146.  .9(raebu 12283:23):         &do_cache_new('supptools',$hashid,$numexttools,600);
1.1172.2.31  raeburn  12284:     }
1.1172.2.146.  .9(raebu 12285:23):     return $numexttools;
                   12286:23): }
                   12287:23): 
                   12288:23): sub has_unhidden_suppfiles {
                   12289:23):     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   12290:23):     my $hashid=$cnum.':'.$cdom;
                   12291:23):     my ($showsupp,$cached);
                   12292:23):     unless ($ignorecache) {
                   12293:23):         ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
                   12294:23):     }
                   12295:23):     unless (defined($cached)) {
                   12296:23):         my $chome=&homeserver($cnum,$cdom);
                   12297:23):         unless ($chome eq 'no_host') {
                   12298:23):             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
                   12299:23):             if (ref($supplemental) eq 'HASH') {
                   12300:23):                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   12301:23):                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
                   12302:23):                         next if ($key =~ /\.sequence$/);
                   12303:23):                         if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
                   12304:23):                             foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
                   12305:23):                                 unless ($supplemental->{'hidden'}->{$id}) {
                   12306:23):                                     $showsupp = 1;
                   12307:23):                                     last;
                   12308:23):                                 }
                   12309:23):                             }
                   12310:23):                         }
                   12311:23):                         last if ($showsupp);
                   12312:23):                     }
                   12313:23):                 }
                   12314:23):             }
                   12315:23):         }
                   12316:23):         &do_cache_new('showsupp',$hashid,$showsupp,600);
                   12317:23):     }
                   12318:23):     return $showsupp;
1.1172.2.31  raeburn  12319: }
                   12320: 
1.379     matthew  12321: #
                   12322: # EXT resource caching routines
                   12323: #
                   12324: 
1.1172.2.146.  .1(raebu 12325:22): {
                   12326:22): # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   12327:22): #
                   12328:22): # The course for which we cache
                   12329:22): my $cachedmapkey='';
                   12330:22): # The cached recursive maps for this course
                   12331:22): my %cachedmaps=();
                   12332:22): # When this was last done
                   12333:22): my $cachedmaptime='';
                   12334:22): 
1.379     matthew  12335: sub clear_EXT_cache_status {
1.383     albertel 12336:     &delenv('cache.EXT.');
1.379     matthew  12337: }
                   12338: 
                   12339: sub EXT_cache_status {
                   12340:     my ($target_domain,$target_user) = @_;
1.383     albertel 12341:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 12342:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  12343:         # We know already the user has no data
                   12344:         return 1;
                   12345:     } else {
                   12346:         return 0;
                   12347:     }
                   12348: }
                   12349: 
                   12350: sub EXT_cache_set {
                   12351:     my ($target_domain,$target_user) = @_;
1.383     albertel 12352:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  12353:     #&appenv({$cachename => time});
1.379     matthew  12354: }
                   12355: 
1.28      www      12356: # --------------------------------------------------------- Value of a Variable
1.58      www      12357: sub EXT {
1.715     albertel 12358: 
1.1172.2.28  raeburn  12359:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      12360:     unless ($varname) { return ''; }
1.218     albertel 12361:     #get real user name/domain, courseid and symb
                   12362:     my $courseid;
1.359     albertel 12363:     my $publicuser;
1.427     www      12364:     if ($symbparm) {
                   12365: 	$symbparm=&get_symb_from_alias($symbparm);
                   12366:     }
1.218     albertel 12367:     if (!($uname && $udom)) {
1.790     albertel 12368:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 12369:       if (!$symbparm) {	$symbparm=$cursymb; }
                   12370:     } else {
1.620     albertel 12371: 	$courseid=$env{'request.course.id'};
1.218     albertel 12372:     }
1.48      www      12373:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   12374:     my $rest;
1.320     albertel 12375:     if (defined($therest[0])) {
1.48      www      12376:        $rest=join('.',@therest);
                   12377:     } else {
                   12378:        $rest='';
                   12379:     }
1.320     albertel 12380: 
1.57      www      12381:     my $qualifierrest=$qualifier;
                   12382:     if ($rest) { $qualifierrest.='.'.$rest; }
                   12383:     my $spacequalifierrest=$space;
                   12384:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      12385:     if ($realm eq 'user') {
1.48      www      12386: # --------------------------------------------------------------- user.resource
                   12387: 	if ($space eq 'resource') {
1.651     albertel 12388: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   12389: 		  || defined($Apache::lonhomework::parsing_a_task))
                   12390: 		 &&
1.1172.2.142  raeburn  12391: 		 ($symbparm eq &symbread()) ) {
1.744     albertel 12392: 		# if we are in the middle of processing the resource the
                   12393: 		# get the value we are planning on committing
                   12394:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   12395:                     return $Apache::lonhomework::results{$qualifierrest};
                   12396:                 } else {
                   12397:                     return $Apache::lonhomework::history{$qualifierrest};
                   12398:                 }
1.335     albertel 12399: 	    } else {
1.359     albertel 12400: 		my %restored;
1.620     albertel 12401: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 12402: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   12403: 		} else {
                   12404: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   12405: 		}
1.335     albertel 12406: 		return $restored{$qualifierrest};
                   12407: 	    }
1.48      www      12408: # ----------------------------------------------------------------- user.access
                   12409:         } elsif ($space eq 'access') {
1.218     albertel 12410: 	    # FIXME - not supporting calls for a specific user
1.48      www      12411:             return &allowed($qualifier,$rest);
                   12412: # ------------------------------------------ user.preferences, user.environment
                   12413:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 12414: 	    if (($uname eq $env{'user.name'}) &&
                   12415: 		($udom eq $env{'user.domain'})) {
                   12416: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 12417: 	    } else {
1.359     albertel 12418: 		my %returnhash;
                   12419: 		if (!$publicuser) {
                   12420: 		    %returnhash=&userenvironment($udom,$uname,
                   12421: 						 $qualifierrest);
                   12422: 		}
1.218     albertel 12423: 		return $returnhash{$qualifierrest};
                   12424: 	    }
1.48      www      12425: # ----------------------------------------------------------------- user.course
                   12426:         } elsif ($space eq 'course') {
1.218     albertel 12427: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12428:             return $env{join('.',('request.course',$qualifier))};
1.48      www      12429: # ------------------------------------------------------------------- user.role
                   12430:         } elsif ($space eq 'role') {
1.218     albertel 12431: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12432:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      12433:             if ($qualifier eq 'value') {
                   12434: 		return $role;
                   12435:             } elsif ($qualifier eq 'extent') {
                   12436:                 return $where;
                   12437:             }
                   12438: # ----------------------------------------------------------------- user.domain
                   12439:         } elsif ($space eq 'domain') {
1.218     albertel 12440:             return $udom;
1.48      www      12441: # ------------------------------------------------------------------- user.name
                   12442:         } elsif ($space eq 'name') {
1.218     albertel 12443:             return $uname;
1.48      www      12444: # ---------------------------------------------------- Any other user namespace
1.29      www      12445:         } else {
1.359     albertel 12446: 	    my %reply;
                   12447: 	    if (!$publicuser) {
                   12448: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   12449: 	    }
                   12450: 	    return $reply{$qualifierrest};
1.48      www      12451:         }
1.236     www      12452:     } elsif ($realm eq 'query') {
                   12453: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 12454:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   12455: 						[$spacequalifierrest]);
1.620     albertel 12456: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      12457:    } elsif ($realm eq 'request') {
1.48      www      12458: # ------------------------------------------------------------- request.browser
                   12459:         if ($space eq 'browser') {
1.1145    bisitz   12460:             return $env{'browser.'.$qualifier};
1.57      www      12461: # ------------------------------------------------------------ request.filename
                   12462:         } else {
1.620     albertel 12463:             return $env{'request.'.$spacequalifierrest};
1.29      www      12464:         }
1.28      www      12465:     } elsif ($realm eq 'course') {
1.48      www      12466: # ---------------------------------------------------------- course.description
1.620     albertel 12467:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      12468:     } elsif ($realm eq 'resource') {
1.165     www      12469: 
1.620     albertel 12470: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 12471: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   12472: 	}
1.693     albertel 12473: 
1.1172.2.30  raeburn  12474:         if ($qualifier eq '') {
                   12475: 	    if ($space eq 'title') {
                   12476: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   12477: 	        return &gettitle($symbparm);
                   12478: 	    }
1.693     albertel 12479: 	
1.1172.2.30  raeburn  12480: 	    if ($space eq 'map') {
                   12481: 	        my ($map) = &decode_symb($symbparm);
                   12482: 	        return &symbread($map);
                   12483: 	    }
                   12484:             if ($space eq 'maptitle') {
                   12485:                 my ($map) = &decode_symb($symbparm);
                   12486:                 return &gettitle($map);
                   12487:             }
                   12488: 	    if ($space eq 'filename') {
                   12489: 	        if ($symbparm) {
                   12490: 		    return &clutter((&decode_symb($symbparm))[2]);
                   12491: 	        }
                   12492: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 12493: 	    }
1.1172.2.30  raeburn  12494: 
                   12495:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   12496:                 if ($space eq 'visibleparts') {
                   12497:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   12498:                     my $item;
                   12499:                     if (ref($navmap)) {
                   12500:                         my $res = $navmap->getBySymb($symbparm);
                   12501:                         my $parts = $res->parts();
                   12502:                         if (ref($parts) eq 'ARRAY') {
                   12503:                             $item = join(',',@{$parts});
                   12504:                         }
                   12505:                         undef($navmap);
                   12506:                     }
                   12507:                     return $item;
                   12508:                 }
                   12509:             }
                   12510:         }
1.693     albertel 12511: 
                   12512: 	my ($section, $group, @groups);
1.593     albertel 12513: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  12514:         if (($courseid eq '') && ($cid)) {
                   12515:             $courseid = $cid;
                   12516:         }
                   12517: 	if (($symbparm && $courseid) && 
                   12518: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      12519: 
1.218     albertel 12520: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      12521: 
1.60      www      12522: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 12523: 	    my $symbp=$symbparm;
1.735     albertel 12524: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 12525: 
                   12526: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   12527: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   12528: 
1.620     albertel 12529: 	    if (($env{'user.name'} eq $uname) &&
                   12530: 		($env{'user.domain'} eq $udom)) {
                   12531: 		$section=$env{'request.course.sec'};
1.733     raeburn  12532:                 @groups = split(/:/,$env{'request.course.groups'});  
                   12533:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 12534: 	    } else {
1.539     albertel 12535: 		if (! defined($usection)) {
1.551     albertel 12536: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 12537: 		} else {
                   12538: 		    $section = $usection;
                   12539: 		}
1.733     raeburn  12540:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12541: 	    }
                   12542: 
                   12543: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12544: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   12545: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12546: 
1.593     albertel 12547: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12548: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 12549: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12550: 
1.60      www      12551: # ----------------------------------------------------------- first, check user
1.624     albertel 12552: 
                   12553: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 12554: 				       ([$courselevelr,'resource'],
                   12555: 					[$courselevelm,'map'     ],
                   12556: 					[$courselevel, 'course'  ]));
1.931     albertel 12557: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12558: 
1.594     albertel 12559: # ------------------------------------------------ second, check some of course
1.684     raeburn  12560:             my $coursereply;
1.691     raeburn  12561:             if (@groups > 0) {
                   12562:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   12563:                                        $mapparm,$spacequalifierrest);
1.927     albertel 12564:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  12565:             }
1.96      www      12566: 
1.684     raeburn  12567: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12568: 				  $env{'course.'.$courseid.'.domain'},
                   12569: 				  'course',
                   12570: 				  ([$seclevelr,   'resource'],
                   12571: 				   [$seclevelm,   'map'     ],
                   12572: 				   [$seclevel,    'course'  ],
                   12573: 				   [$courselevelr,'resource']));
                   12574: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12575: 
1.60      www      12576: # ------------------------------------------------------ third, check map parms
1.218     albertel 12577: 	    my %parmhash=();
                   12578: 	    my $thisparm='';
                   12579: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12580: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12581: 		    &GDBM_READER(),0640)) {
1.218     albertel 12582: 		$thisparm=$parmhash{$symbparm};
                   12583: 		untie(%parmhash);
                   12584: 	    }
1.927     albertel 12585: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12586: 	}
1.594     albertel 12587: # ------------------------------------------ fourth, look in resource metadata
1.71      www      12588: 
1.1172.2.146.  .13(raeb 12589:-23):         my $what = $spacequalifierrest;
                   12590:-23):         $what=~s/\./\_/;
                   12591:-23):         my $filename;
1.282     albertel 12592: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12593: 	if ($symbparm) {
1.409     www      12594: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12595: 	} else {
1.620     albertel 12596: 	    $filename=$env{'request.filename'};
1.282     albertel 12597: 	}
1.1172.2.146.  .13(raeb 12598:-23):         my $toolsymb;
                   12599:-23):         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   12600:-23):             $toolsymb = $symbparm;
                   12601:-23):         }
                   12602:-23): 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 12603: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1172.2.146.  .13(raeb 12604:-23): 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 12605: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12606: 
1.1172.2.146.  .13(raeb 12607:-23): # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 12608: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12609: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12610: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12611: 				     $env{'course.'.$courseid.'.domain'},
                   12612: 				     'course',
1.927     albertel 12613: 				     ([$courselevelm,'map'   ],
                   12614: 				      [$courselevel, 'course']));
                   12615: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12616: 	}
1.145     www      12617: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12618: 	unless ($space eq '0') {
1.336     albertel 12619: 	    my @parts=split(/_/,$space);
                   12620: 	    my $id=pop(@parts);
                   12621: 	    my $part=join('_',@parts);
                   12622: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12623: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12624: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12625: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12626: 	}
1.395     albertel 12627: 	if ($recurse) { return undef; }
1.1172.2.146.  .13(raeb 12628:-23): 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 12629: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12630: # ---------------------------------------------------- Any other user namespace
                   12631:     } elsif ($realm eq 'environment') {
                   12632: # ----------------------------------------------------------------- environment
1.620     albertel 12633: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12634: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12635: 	} else {
1.770     albertel 12636: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12637: 		return '';
                   12638: 	    }
1.219     albertel 12639: 	    my %returnhash=&userenvironment($udom,$uname,
                   12640: 					    $spacequalifierrest);
                   12641: 	    return $returnhash{$spacequalifierrest};
                   12642: 	}
1.28      www      12643:     } elsif ($realm eq 'system') {
1.48      www      12644: # ----------------------------------------------------------------- system.time
                   12645: 	if ($space eq 'time') {
                   12646: 	    return time;
                   12647:         }
1.696     albertel 12648:     } elsif ($realm eq 'server') {
                   12649: # ----------------------------------------------------------------- system.time
                   12650: 	if ($space eq 'name') {
                   12651: 	    return $ENV{'SERVER_NAME'};
                   12652:         }
1.1172.2.146.  .1(raebu 12653:22):     } elsif ($realm eq 'client') {
                   12654:22):         if ($space eq 'remote_addr') {
                   12655:22):             return &get_requestor_ip();
                   12656:22):         }
1.28      www      12657:     }
1.48      www      12658:     return '';
1.61      www      12659: }
                   12660: 
1.927     albertel 12661: sub get_reply {
                   12662:     my ($reply_value) = @_;
1.940     raeburn  12663:     if (ref($reply_value) eq 'ARRAY') {
                   12664:         if (wantarray) {
                   12665: 	    return @$reply_value;
                   12666:         }
                   12667:         return $reply_value->[0];
                   12668:     } else {
                   12669:         return $reply_value;
1.927     albertel 12670:     }
                   12671: }
                   12672: 
1.691     raeburn  12673: sub check_group_parms {
                   12674:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   12675:     my @groupitems = ();
                   12676:     my $resultitem;
1.927     albertel 12677:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  12678:     foreach my $group (@{$groups}) {
                   12679:         foreach my $level (@levels) {
1.927     albertel 12680:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12681:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12682:         }
                   12683:     }
                   12684:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12685:                             $env{'course.'.$courseid.'.domain'},
                   12686:                                      'course',@groupitems);
                   12687:     return $coursereply;
                   12688: }
                   12689: 
1.1172.2.146.  .1(raebu 12690:22): sub get_map_hierarchy {
                   12691:22):     my ($mapname,$courseid) = @_;
                   12692:22):     my @recurseup = ();
                   12693:22):     if ($mapname) {
                   12694:22):         if (($cachedmapkey eq $courseid) &&
                   12695:22):             (abs($cachedmaptime-time)<5)) {
                   12696:22):             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12697:22):                 return @{$cachedmaps{$mapname}};
                   12698:22):             }
                   12699:22):         }
                   12700:22):         my $navmap = Apache::lonnavmaps::navmap->new();
                   12701:22):         if (ref($navmap)) {
                   12702:22):             @recurseup = $navmap->recurseup_maps($mapname);
                   12703:22):             undef($navmap);
                   12704:22):             $cachedmaps{$mapname} = \@recurseup;
                   12705:22):             $cachedmaptime=time;
                   12706:22):             $cachedmapkey=$courseid;
                   12707:22):         }
                   12708:22):     }
                   12709:22):     return @recurseup;
                   12710:22): }
                   12711:22): 
          .2(raebu 12712:22): }
          .1(raebu 12713:22): 
1.691     raeburn  12714: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12715:     my ($courseid,@groups) = @_;
                   12716:     @groups = sort(@groups);
1.691     raeburn  12717:     return @groups;
                   12718: }
                   12719: 
1.395     albertel 12720: sub packages_tab_default {
1.1172.2.146.  .13(raeb 12721:-23):     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 12722:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12723: 
                   12724:     my (@extension,@specifics,$do_default);
1.1172.2.146.  .13(raeb 12725:-23):     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 12726: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12727: 	if ($pack_type eq 'default') {
                   12728: 	    $do_default=1;
                   12729: 	} elsif ($pack_type eq 'extension') {
                   12730: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12731: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12732: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12733: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12734: 	}
                   12735:     }
                   12736:     # first look for a package that matches the requested part id
                   12737:     foreach my $package (@specifics) {
                   12738: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12739: 	next if ($pack_part ne $part);
                   12740: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12741: 	    return $packagetab{"$pack_type&$name&default"};
                   12742: 	}
                   12743:     }
                   12744:     # look for any possible matching non extension_ package
                   12745:     foreach my $package (@specifics) {
                   12746: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12747: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12748: 	    return $packagetab{"$pack_type&$name&default"};
                   12749: 	}
1.585     albertel 12750: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12751: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12752: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12753: 	}
                   12754:     }
1.738     albertel 12755:     # look for any posible extension_ match
                   12756:     foreach my $package (@extension) {
                   12757: 	my ($package,$pack_type)=@{$package};
                   12758: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12759: 	    return $packagetab{"$pack_type&$name&default"};
                   12760: 	}
                   12761: 	if (defined($packagetab{$package."&$name&default"})) {
                   12762: 	    return $packagetab{$package."&$name&default"};
                   12763: 	}
                   12764:     }
                   12765:     # look for a global default setting
                   12766:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12767: 	return $packagetab{"default&$name&default"};
                   12768:     }
1.395     albertel 12769:     return undef;
                   12770: }
                   12771: 
1.334     albertel 12772: sub add_prefix_and_part {
                   12773:     my ($prefix,$part)=@_;
                   12774:     my $keyroot;
                   12775:     if (defined($prefix) && $prefix !~ /^__/) {
                   12776: 	# prefix that has a part already
                   12777: 	$keyroot=$prefix;
                   12778:     } elsif (defined($prefix)) {
                   12779: 	# prefix that is missing a part
                   12780: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12781:     } else {
                   12782: 	# no prefix at all
                   12783: 	if (defined($part)) { $keyroot='_'.$part; }
                   12784:     }
                   12785:     return $keyroot;
                   12786: }
                   12787: 
1.71      www      12788: # ---------------------------------------------------------------- Get metadata
                   12789: 
1.599     albertel 12790: my %metaentry;
1.1070    www      12791: my %importedpartids;
1.1172.2.99  raeburn  12792: my %importedrespids;
1.71      www      12793: sub metadata {
1.1172.2.146.  .13(raeb 12794:-23):     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      12795:     $uri=&declutter($uri);
1.288     albertel 12796:     # if it is a non metadata possible uri return quickly
1.529     albertel 12797:     if (($uri eq '') || 
                   12798: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.146.  .1(raebu 12799:22): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12800:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12801: 	return undef;
                   12802:     }
1.1172.2.49  raeburn  12803:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12804: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12805: 	return undef;
1.288     albertel 12806:     }
1.73      www      12807:     my $filename=$uri;
                   12808:     $uri=~s/\.meta$//;
1.172     www      12809: #
                   12810: # Is the metadata already cached?
1.177     www      12811: # Look at timestamp of caching
1.172     www      12812: # Everything is cached by the main uri, libraries are never directly cached
                   12813: #
1.428     albertel 12814:     if (!defined($liburi)) {
1.599     albertel 12815: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12816: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12817:     }
1.1172.2.146.  .13(raeb 12818:-23): 
                   12819:-23): #
                   12820:-23): # If the uri is for an external tool the file from
                   12821:-23): # which metadata should be retrieved depends on whether
                   12822:-23): # the tool had been configured to be gradable (set in the Course
                   12823:-23): # Editor or Resource Editor).
                   12824:-23): #
                   12825:-23): # If a valid symb has been included as the third arg in the call
                   12826:-23): # to &metadata() that can be used to retrieve the value of
                   12827:-23): # parameter_0_gradable set for the resource, and included in the
                   12828:-23): # uploaded map containing the tool. The value is retrieved via
                   12829:-23): # &EXT(), if a valid symb is available.  Otherwise the value of
                   12830:-23): # gradable in the exttool_$marker.db file for the tool instance
                   12831:-23): # is retrieved via &get().
                   12832:-23): #
                   12833:-23): # When lonuserstate::traceroute() calls lonnet::EXT() for
                   12834:-23): # hiddenresource and encrypturl (during course initialization)
                   12835:-23): # the map-level parameter for resource.0.gradable included in the
                   12836:-23): # uploaded map containing the tool will not yet have been stored
                   12837:-23): # in the user_course_parms.db file for the user's session, so in
                   12838:-23): # this case fall back to retrieving gradable status from the
                   12839:-23): # exttool_$marker.db file.
                   12840:-23): #
                   12841:-23): # In order to avoid an infinite loop, &metadata() will return
                   12842:-23): # before a call to &EXT(), if the uri is for an external tool
                   12843:-23): # and the $what for which metadata is being requested is
                   12844:-23): # parameter_0_gradable or 0_gradable.
                   12845:-23): #
                   12846:-23): 
                   12847:-23):     if ($uri =~ /ext\.tool$/) {
                   12848:-23):         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   12849:-23):             return;
                   12850:-23):         } else {
                   12851:-23):             my ($checked,$use_passback);
                   12852:-23):             if ($toolsymb ne '') {
                   12853:-23):                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
                   12854:-23):                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
                   12855:-23):                     $checked = 1;
                   12856:-23):                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   12857:-23):                         $use_passback = 1;
                   12858:-23):                     }
                   12859:-23):                 }
                   12860:-23):             }
                   12861:-23):             unless ($checked) {
                   12862:-23):                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   12863:-23):                 $marker=~s/\D//g;
                   12864:-23):                 if ($marker) {
                   12865:-23):                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   12866:-23):                     $use_passback = $toolsettings{'gradable'};
                   12867:-23):                 }
                   12868:-23):             }
                   12869:-23):             if ($use_passback) {
                   12870:-23):                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   12871:-23):             } else {
                   12872:-23):                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   12873:-23):             }
                   12874:-23):         }
                   12875:-23):     }
                   12876:-23): 
1.428     albertel 12877:     {
1.1069    www      12878: # Imported parts would go here
1.1172.2.99  raeburn  12879:         my @origfiletagids=();
1.1069    www      12880:         my $importedparts=0;
1.1172.2.99  raeburn  12881: 
                   12882: # Imported responseids would go here
                   12883:         my $importedresponses=0;
1.172     www      12884: #
                   12885: # Is this a recursive call for a library?
                   12886: #
1.599     albertel 12887: #	if (! exists($metacache{$uri})) {
                   12888: #	    $metacache{$uri}={};
                   12889: #	}
1.924     albertel 12890: 	my $cachetime = 60*60;
1.171     www      12891:         if ($liburi) {
                   12892: 	    $liburi=&declutter($liburi);
                   12893:             $filename=$liburi;
1.401     bowersj2 12894:         } else {
1.599     albertel 12895: 	    &devalidate_cache_new('meta',$uri);
                   12896: 	    undef(%metaentry);
1.401     bowersj2 12897: 	}
1.140     www      12898:         my %metathesekeys=();
1.73      www      12899:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12900: 	my $metastring;
1.1140    www      12901: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12902: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12903: 	    $metastring = 
1.929     albertel 12904: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12905: 					  ('grade_target' => 'meta'));
                   12906: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12907: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12908:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12909: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12910: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12911: 	    $metastring=&getfile($file);
1.489     albertel 12912: 	}
1.208     albertel 12913:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12914:         my $token;
1.140     www      12915:         undef %metathesekeys;
1.71      www      12916:         while ($token=$parser->get_token) {
1.339     albertel 12917: 	    if ($token->[0] eq 'S') {
                   12918: 		if (defined($token->[2]->{'package'})) {
1.172     www      12919: #
                   12920: # This is a package - get package info
                   12921: #
1.339     albertel 12922: 		    my $package=$token->[2]->{'package'};
                   12923: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12924: 		    if (defined($token->[2]->{'id'})) { 
                   12925: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12926: 		    }
1.599     albertel 12927: 		    if ($metaentry{':packages'}) {
                   12928: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12929: 		    } else {
1.599     albertel 12930: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12931: 		    }
1.736     albertel 12932: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12933: 			my $part=$keyroot;
                   12934: 			$part=~s/^\_//;
1.736     albertel 12935: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12936: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12937: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12938: 			    # ignore package.tab specified default values
                   12939:                             # here &package_tab_default() will fetch those
                   12940: 			    if ($subp eq 'default') { next; }
1.736     albertel 12941: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12942: 			    my $unikey;
                   12943: 			    if ($pack =~ /_0$/) {
                   12944: 				$unikey='parameter_0_'.$name;
                   12945: 				$part=0;
                   12946: 			    } else {
                   12947: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12948: 			    }
1.339     albertel 12949: 			    if ($subp eq 'display') {
                   12950: 				$value.=' [Part: '.$part.']';
                   12951: 			    }
1.599     albertel 12952: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12953: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12954: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12955: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12956: 			    }
1.599     albertel 12957: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12958: 				$metaentry{':'.$unikey}=
                   12959: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12960: 			    }
1.339     albertel 12961: 			}
                   12962: 		    }
                   12963: 		} else {
1.172     www      12964: #
                   12965: # This is not a package - some other kind of start tag
1.339     albertel 12966: #
                   12967: 		    my $entry=$token->[1];
1.1068    www      12968: 		    my $unikey='';
1.175     www      12969: 
1.339     albertel 12970: 		    if ($entry eq 'import') {
1.175     www      12971: #
                   12972: # Importing a library here
1.339     albertel 12973: #
1.1067    www      12974:                         my $location=$parser->get_text('/import');
                   12975:                         my $dir=$filename;
                   12976:                         $dir=~s|[^/]*$||;
                   12977:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  12978: 
                   12979:                         my $importid=$token->[2]->{'id'};
1.1068    www      12980:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  12981: #
                   12982: # Check metadata for imported file to
                   12983: # see if it contained response items
                   12984: #
                   12985:                         my %currmetaentry = %metaentry;
                   12986:                         my $libresponseorder = &metadata($location,'responseorder');
                   12987:                         my $origfile;
                   12988:                         if ($libresponseorder ne '') {
                   12989:                             if ($#origfiletagids<0) {
                   12990:                                 undef(%importedrespids);
                   12991:                                 undef(%importedpartids);
                   12992:                             }
                   12993:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   12994:                             if (@{$importedrespids{$importid}} > 0) {
                   12995:                                 $importedresponses = 1;
                   12996: # We need to get the original file and the imported file to get the response order correct
                   12997: # Load and inspect original file
                   12998:                                 if ($#origfiletagids<0) {
                   12999:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   13000:                                     $origfile=&getfile($origfilelocation);
                   13001:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13002:                                 }
                   13003:                             }
                   13004:                         }
                   13005: # Do not overwrite contents of %metaentry hash for resource itself with 
                   13006: # hash populated for imported library file
                   13007:                         %metaentry = %currmetaentry;
                   13008:                         undef(%currmetaentry);
1.1068    www      13009:                         if ($importmode eq 'problem') {
1.1069    www      13010: # Import as problem/response
1.1068    www      13011:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13012:                         } elsif ($importmode eq 'part') {
                   13013: # Import as part(s)
1.1069    www      13014:                            $importedparts=1;
                   13015: # We need to get the original file and the imported file to get the part order correct
                   13016: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  13017: # Load and inspect original file if we didn't do that already
                   13018:                            if ($#origfiletagids<0) {
                   13019:                                undef(%importedrespids);
                   13020:                                undef(%importedpartids);
                   13021:                                if ($origfile eq '') {
                   13022:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   13023:                                    $origfile=&getfile($origfilelocation);
                   13024:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13025:                                }
1.1070    www      13026:                            }
                   13027: 
1.1069    www      13028: # Load and inspect imported file
                   13029:                            my $impfile=&getfile($location);
                   13030:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13031:                            if ($#impfilepartids>=0) {
                   13032: # This problem had parts
1.1070    www      13033:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      13034:                            } else {
                   13035: # Importing by turning a single problem into a problem part
                   13036: # It gets the import-tags ID as part-ID
                   13037:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      13038:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      13039:                            }
1.1068    www      13040:                         } else {
                   13041: # Normal import
                   13042:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13043:                            if (defined($token->[2]->{'id'})) {
                   13044:                               $unikey.='_'.$token->[2]->{'id'};
                   13045:                            }
1.1067    www      13046:                         }
                   13047: 
1.339     albertel 13048: 			if ($depthcount<20) {
1.736     albertel 13049: 			    my $metadata = 
1.1172.2.146.  .13(raeb 13050:-23): 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 13051: 					  $depthcount+1);
                   13052: 			    foreach my $meta (split(',',$metadata)) {
                   13053: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   13054: 				$metathesekeys{$meta}=1;
1.339     albertel 13055: 			    }
1.1068    www      13056: 			
                   13057:                         }
1.1067    www      13058: 		    } else {
                   13059: #
                   13060: # Not importing, some other kind of non-package, non-library start tag
                   13061: # 
                   13062:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13063:                         if (defined($token->[2]->{'id'})) {
                   13064:                             $unikey.='_'.$token->[2]->{'id'};
                   13065:                         }
1.339     albertel 13066: 			if (defined($token->[2]->{'name'})) { 
                   13067: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   13068: 			}
                   13069: 			$metathesekeys{$unikey}=1;
1.736     albertel 13070: 			foreach my $param (@{$token->[3]}) {
                   13071: 			    $metaentry{':'.$unikey.'.'.$param} =
                   13072: 				$token->[2]->{$param};
1.339     albertel 13073: 			}
                   13074: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 13075: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 13076: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   13077: 		 # only ws inside the tag, and not in default, so use default
                   13078: 		 # as value
1.599     albertel 13079: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 13080: 			} elsif ( $internaltext =~ /\S/ ) {
                   13081: 		  # something interesting inside the tag
                   13082: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 13083: 			} else {
1.908     albertel 13084: 		  # no interesting values, don't set a default
1.339     albertel 13085: 			}
1.172     www      13086: # end of not-a-package not-a-library import
1.339     albertel 13087: 		    }
1.172     www      13088: # end of not-a-package start tag
1.339     albertel 13089: 		}
1.172     www      13090: # the next is the end of "start tag"
1.339     albertel 13091: 	    }
                   13092: 	}
1.483     albertel 13093: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 13094: 	$extension = lc($extension);
                   13095: 	if ($extension eq 'htm') { $extension='html'; }
                   13096: 
1.737     albertel 13097: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 13098: 	    #no specific packages #how's our extension
                   13099: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 13100: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 13101: 					 \%metathesekeys);
                   13102: 	}
1.883     albertel 13103: 
                   13104: 	if (!exists($metaentry{':packages'})
                   13105: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 13106: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 13107: 		#no specific packages well let's get default then
                   13108: 		if ($key!~/^default&/) { next; }
1.488     albertel 13109: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 13110: 					     \%metathesekeys);
                   13111: 	    }
                   13112: 	}
1.338     www      13113: # are there custom rights to evaluate
1.599     albertel 13114: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 13115: 
1.338     www      13116:     #
                   13117:     # Importing a rights file here
1.339     albertel 13118:     #
                   13119: 	    unless ($depthcount) {
1.599     albertel 13120: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 13121: 		my $dir=$filename;
                   13122: 		$dir=~s|[^/]*$||;
                   13123: 		$location=&filelocation($dir,$location);
1.736     albertel 13124: 		my $rights_metadata =
1.1172.2.146.  .13(raeb 13125:-23): 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 13126: 			      $depthcount+1);
                   13127: 		foreach my $rights (split(',',$rights_metadata)) {
                   13128: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   13129: 		    $metathesekeys{$rights}=1;
1.339     albertel 13130: 		}
                   13131: 	    }
                   13132: 	}
1.737     albertel 13133: 	# uniqifiy package listing
                   13134: 	my %seen;
                   13135: 	my @uniq_packages =
                   13136: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   13137: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   13138: 
1.1172.2.99  raeburn  13139:         if (($importedresponses) || ($importedparts)) {
                   13140:             if ($importedparts) {
1.1070    www      13141: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  13142:                 $metaentry{':partorder'}='';
                   13143:                 $metathesekeys{'partorder'}=1;
                   13144:             }
                   13145:             if ($importedresponses) {
                   13146: # We had imported responses and need to rebuild responseorder
                   13147:                 $metaentry{':responseorder'}='';
                   13148:                 $metathesekeys{'responseorder'}=1;
                   13149:             }
                   13150:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   13151:                 my $origid = $origfiletagids[$index+1];
                   13152:                 if ($origfiletagids[$index] eq 'part') {
                   13153: # Original part, part of the problem
                   13154:                     if ($importedparts) {
                   13155:                         $metaentry{':partorder'}.=','.$origid;
                   13156:                     }
                   13157:                 } elsif ($origfiletagids[$index] eq 'import') {
                   13158:                     if ($importedparts) {
                   13159: # We have imported parts at this position
                   13160:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   13161:                     }
                   13162:                     if ($importedresponses) {
                   13163: # We have imported responses at this position
                   13164:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   13165:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   13166:                         }
                   13167:                     }
                   13168:                 } else {
                   13169: # Original response item, part of the problem
                   13170:                     if ($importedresponses) {
                   13171:                         $metaentry{':responseorder'}.=','.$origid;
                   13172:                     }
                   13173:                 }
                   13174:             }
                   13175:             if ($importedparts) {
                   13176:                 $metaentry{':partorder'}=~s/^\,//;
                   13177:             }
                   13178:             if ($importedresponses) {
                   13179:                 $metaentry{':responseorder'}=~s/^\,//;
                   13180:             }
1.1070    www      13181:         }
                   13182: 
1.737     albertel 13183: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 13184: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  13185: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 13186: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      13187: # this is the end of "was not already recently cached
1.71      www      13188:     }
1.599     albertel 13189:     return $metaentry{':'.$what};
1.261     albertel 13190: }
                   13191: 
1.488     albertel 13192: sub metadata_create_package_def {
1.483     albertel 13193:     my ($uri,$key,$package,$metathesekeys)=@_;
                   13194:     my ($pack,$name,$subp)=split(/\&/,$key);
                   13195:     if ($subp eq 'default') { next; }
                   13196:     
1.599     albertel 13197:     if (defined($metaentry{':packages'})) {
                   13198: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 13199:     } else {
1.599     albertel 13200: 	$metaentry{':packages'}=$package;
1.483     albertel 13201:     }
                   13202:     my $value=$packagetab{$key};
                   13203:     my $unikey;
                   13204:     $unikey='parameter_0_'.$name;
1.599     albertel 13205:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 13206:     $$metathesekeys{$unikey}=1;
1.599     albertel 13207:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   13208: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 13209:     }
1.599     albertel 13210:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   13211: 	$metaentry{':'.$unikey}=
                   13212: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 13213:     }
                   13214: }
                   13215: 
1.261     albertel 13216: sub metadata_generate_part0 {
                   13217:     my ($metadata,$metacache,$uri) = @_;
                   13218:     my %allnames;
1.737     albertel 13219:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 13220: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 13221: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   13222: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 13223: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 13224: 	    $allnames{$name}=$part;
                   13225: 	  }
                   13226: 	}
                   13227:     }
                   13228:     foreach my $name (keys(%allnames)) {
                   13229:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 13230:       my $key=":parameter_0_$name";
1.261     albertel 13231:       $$metacache{"$key.part"}='0';
                   13232:       $$metacache{"$key.name"}=$name;
1.428     albertel 13233:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 13234: 					   $allnames{$name}.'_'.$name.
                   13235: 					   '.type'};
1.428     albertel 13236:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 13237: 			     '.display'};
1.644     www      13238:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 13239:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 13240:       $$metacache{"$key.display"}=$olddis;
                   13241:     }
1.71      www      13242: }
                   13243: 
1.764     albertel 13244: # ------------------------------------------------------ Devalidate title cache
                   13245: 
                   13246: sub devalidate_title_cache {
                   13247:     my ($url)=@_;
                   13248:     if (!$env{'request.course.id'}) { return; }
                   13249:     my $symb=&symbread($url);
                   13250:     if (!$symb) { return; }
                   13251:     my $key=$env{'request.course.id'}."\0".$symb;
                   13252:     &devalidate_cache_new('title',$key);
                   13253: }
                   13254: 
1.1014    droeschl 13255: # ------------------------------------------------- Get the title of a course
                   13256: 
                   13257: sub current_course_title {
                   13258:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   13259: }
1.301     www      13260: # ------------------------------------------------- Get the title of a resource
                   13261: 
                   13262: sub gettitle {
                   13263:     my $urlsymb=shift;
                   13264:     my $symb=&symbread($urlsymb);
1.534     albertel 13265:     if ($symb) {
1.620     albertel 13266: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 13267: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 13268: 	if (defined($cached)) { 
                   13269: 	    return $result;
                   13270: 	}
1.534     albertel 13271: 	my ($map,$resid,$url)=&decode_symb($symb);
                   13272: 	my $title='';
1.907     albertel 13273: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   13274: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   13275: 	} else {
                   13276: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   13277: 		    &GDBM_READER(),0640)) {
                   13278: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   13279: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   13280: 		untie(%bighash);
                   13281: 	    }
1.534     albertel 13282: 	}
                   13283: 	$title=~s/\&colon\;/\:/gs;
                   13284: 	if ($title) {
1.1159    www      13285: # Remember both $symb and $title for dynamic metadata
                   13286:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      13287:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      13288: # Cache this title and then return it
1.599     albertel 13289: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 13290: 	}
                   13291: 	$urlsymb=$url;
                   13292:     }
                   13293:     my $title=&metadata($urlsymb,'title');
                   13294:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   13295:     return $title;
1.301     www      13296: }
1.613     albertel 13297: 
1.614     albertel 13298: sub get_slot {
                   13299:     my ($which,$cnum,$cdom)=@_;
                   13300:     if (!$cnum || !$cdom) {
1.790     albertel 13301: 	(undef,my $courseid)=&whichuser();
1.620     albertel 13302: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   13303: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 13304:     }
1.703     albertel 13305:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   13306:     my %slotinfo;
                   13307:     if (exists($remembered{$key})) {
                   13308: 	$slotinfo{$which} = $remembered{$key};
                   13309:     } else {
                   13310: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   13311: 	&Apache::lonhomework::showhash(%slotinfo);
                   13312: 	my ($tmp)=keys(%slotinfo);
                   13313: 	if ($tmp=~/^error:/) { return (); }
                   13314: 	$remembered{$key} = $slotinfo{$which};
                   13315:     }
1.616     albertel 13316:     if (ref($slotinfo{$which}) eq 'HASH') {
                   13317: 	return %{$slotinfo{$which}};
                   13318:     }
                   13319:     return $slotinfo{$which};
1.614     albertel 13320: }
1.1150    raeburn  13321: 
                   13322: sub get_reservable_slots {
                   13323:     my ($cnum,$cdom,$uname,$udom) = @_;
                   13324:     my $now = time;
                   13325:     my $reservable_info;
                   13326:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   13327:     if (exists($remembered{$key})) {
                   13328:         $reservable_info = $remembered{$key};
                   13329:     } else {
                   13330:         my %resv;
                   13331:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   13332:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   13333:         $reservable_info = \%resv;
                   13334:         $remembered{$key} = $reservable_info;
                   13335:     }
                   13336:     return $reservable_info;
                   13337: }
                   13338: 
                   13339: sub get_course_slots {
                   13340:     my ($cnum,$cdom) = @_;
                   13341:     my $hashid=$cnum.':'.$cdom;
                   13342:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   13343:     if (defined($cached)) {
                   13344:         if (ref($result) eq 'HASH') {
                   13345:             return %{$result};
                   13346:         }
                   13347:     } else {
                   13348:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   13349:         my ($tmp) = keys(%slots);
                   13350:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  13351:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  13352:             return %slots;
                   13353:         }
                   13354:     }
                   13355:     return;
                   13356: }
                   13357: 
                   13358: sub devalidate_slots_cache {
                   13359:     my ($cnum,$cdom)=@_;
                   13360:     my $hashid=$cnum.':'.$cdom;
                   13361:     &devalidate_cache_new('allslots',$hashid);
                   13362: }
                   13363: 
1.1172.2.8  raeburn  13364: sub get_coursechange {
                   13365:     my ($cdom,$cnum) = @_;
                   13366:     if ($cdom eq '' || $cnum eq '') {
                   13367:         return unless ($env{'request.course.id'});
                   13368:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   13369:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   13370:     }
                   13371:     my $hashid=$cdom.'_'.$cnum;
                   13372:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   13373:     if ((defined($cached)) && ($change ne '')) {
                   13374:         return $change;
                   13375:     } else {
                   13376:         my %crshash;
                   13377:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   13378:         if ($crshash{'internal.contentchange'} eq '') {
                   13379:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13380:             if ($change eq '') {
                   13381:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13382:                 $change = $crshash{'internal.created'};
                   13383:             }
                   13384:         } else {
                   13385:             $change = $crshash{'internal.contentchange'};
                   13386:         }
                   13387:         my $cachetime = 600;
                   13388:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   13389:     }
                   13390:     return $change;
                   13391: }
                   13392: 
                   13393: sub devalidate_coursechange_cache {
1.1172.2.146.  .9(raebu 13394:23):     my ($cdom,$cnum)=@_;
                   13395:23):     my $hashid=$cdom.'_'.$cnum;
1.1172.2.8  raeburn  13396:     &devalidate_cache_new('crschange',$hashid);
                   13397: }
                   13398: 
1.1172.2.146.  .9(raebu 13399:23): sub get_suppchange {
                   13400:23):     my ($cdom,$cnum) = @_;
                   13401:23):     if ($cdom eq '' || $cnum eq '') {
                   13402:23):         return unless ($env{'request.course.id'});
                   13403:23):         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   13404:23):         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   13405:23):     }
                   13406:23):     my $hashid=$cdom.'_'.$cnum;
                   13407:23):     my ($change,$cached)=&is_cached_new('suppchange',$hashid);
                   13408:23):     if ((defined($cached)) && ($change ne '')) {
                   13409:23):         return $change;
                   13410:23):     } else {
                   13411:23):         my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
                   13412:23):         if ($crshash{'internal.supplementalchange'} eq '') {
                   13413:23):             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13414:23):             if ($change eq '') {
                   13415:23):                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13416:23):                 $change = $crshash{'internal.created'};
                   13417:23):             }
                   13418:23):         } else {
                   13419:23):             $change = $crshash{'internal.supplementalchange'};
                   13420:23):         }
                   13421:23):         my $cachetime = 600;
                   13422:23):         &do_cache_new('suppchange',$hashid,$change,$cachetime);
                   13423:23):     }
                   13424:23):     return $change;
                   13425:23): }
                   13426:23): 
                   13427:23): sub devalidate_suppchange_cache {
                   13428:23):     my ($cdom,$cnum)=@_;
                   13429:23):     my $hashid=$cdom.'_'.$cnum;
                   13430:23):     &devalidate_cache_new('suppchange',$hashid);
                   13431:23): }
                   13432:23): 
                   13433:23): sub update_supp_caches {
                   13434:23):     my ($cdom,$cnum) = @_;
                   13435:23):     my %servers = &internet_dom_servers($cdom);
                   13436:23):     my @ids=&current_machine_ids();
                   13437:23):     foreach my $server (keys(%servers)) {
                   13438:23):         next if (grep(/^\Q$server\E$/,@ids));
                   13439:23):         my $hashid=$cnum.':'.$cdom;
                   13440:23):         my $cachekey = &escape('showsupp').':'.&escape($hashid);
                   13441:23):         &remote_devalidate_cache($server,[$cachekey]);
                   13442:23):     }
                   13443:23):     &has_unhidden_suppfiles($cnum,$cdom,1,1);
                   13444:23):     &count_supptools($cnum,$cdom,1);
                   13445:23):     my $now = time;
                   13446:23):     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   13447:23):         &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
                   13448:23):     }
                   13449:23):     &put('environment',{'internal.supplementalchange' => $now},
                   13450:23):          $cdom,$cnum);
                   13451:23):     &Apache::lonnet::appenv(
                   13452:23):         {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
                   13453:23):     &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
                   13454:23): }
                   13455:23): 
1.31      www      13456: # ------------------------------------------------- Update symbolic store links
                   13457: 
                   13458: sub symblist {
                   13459:     my ($mapname,%newhash)=@_;
1.438     www      13460:     $mapname=&deversion(&declutter($mapname));
1.31      www      13461:     my %hash;
1.620     albertel 13462:     if (($env{'request.course.fn'}) && (%newhash)) {
                   13463:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 13464:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  13465: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 13466: 		next if ($url eq 'last_known'
                   13467: 			 && $env{'form.no_update_last_known'});
                   13468: 		$hash{declutter($url)}=&encode_symb($mapname,
                   13469: 						    $newhash{$url}->[1],
                   13470: 						    $newhash{$url}->[0]);
1.191     harris41 13471:             }
1.31      www      13472:             if (untie(%hash)) {
                   13473: 		return 'ok';
                   13474:             }
                   13475:         }
                   13476:     }
                   13477:     return 'error';
1.212     www      13478: }
                   13479: 
                   13480: # --------------------------------------------------------------- Verify a symb
                   13481: 
                   13482: sub symbverify {
1.1172.2.11  raeburn  13483:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      13484:     my $thisfn=$thisurl;
1.439     www      13485:     $thisfn=&declutter($thisfn);
1.215     www      13486: # direct jump to resource in page or to a sequence - will construct own symbs
                   13487:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   13488: # check URL part
1.409     www      13489:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      13490: 
1.431     www      13491:     unless ($url eq $thisfn) { return 0; }
1.213     www      13492: 
1.216     www      13493:     $symb=&symbclean($symb);
1.510     www      13494:     $thisurl=&deversion($thisurl);
1.439     www      13495:     $thisfn=&deversion($thisfn);
1.213     www      13496: 
                   13497:     my %bighash;
                   13498:     my $okay=0;
1.431     www      13499: 
1.620     albertel 13500:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13501:                             &GDBM_READER(),0640)) {
1.1032    raeburn  13502:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   13503:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  13504:             if ($map =~ m{^uploaded/.+\.page$}) {
                   13505:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   13506:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   13507:             }
                   13508:         }
                   13509:         my $ids;
1.1172.2.122  raeburn  13510:         if ($map =~ m{^uploaded/.+\.page$}) {
                   13511:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  13512:         } else {
                   13513:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  13514:         }
1.1102    raeburn  13515:         unless ($ids) {
1.1172.2.13  raeburn  13516:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  13517:             $ids=$bighash{$idkey};
1.216     www      13518:         }
                   13519:         if ($ids) {
                   13520: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  13521:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   13522:                 $symb =~ s/\?.+$//;
                   13523:             }
1.800     albertel 13524: 	    foreach my $id (split(/\,/,$ids)) {
                   13525: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      13526:                if (
                   13527:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  13528:    eq $symb) {
1.1172.2.11  raeburn  13529:                    if (ref($encstate)) {
                   13530:                        $$encstate = $bighash{'encrypted_'.$id};
                   13531:                    }
1.1172.2.13  raeburn  13532:                    if (($env{'request.role.adv'}) ||
                   13533:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  13534:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  13535:                        $okay=1;
                   13536:                        last;
                   13537:                    }
                   13538:                }
                   13539:            }
1.216     www      13540:         }
1.213     www      13541: 	untie(%bighash);
                   13542:     }
                   13543:     return $okay;
1.31      www      13544: }
                   13545: 
1.210     www      13546: # --------------------------------------------------------------- Clean-up symb
                   13547: 
                   13548: sub symbclean {
                   13549:     my $symb=shift;
1.568     albertel 13550:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      13551: # remove version from map
                   13552:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      13553: 
1.210     www      13554: # remove version from URL
                   13555:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      13556: 
1.507     www      13557: # remove wrapper
                   13558: 
1.510     www      13559:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 13560:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      13561:     return $symb;
1.409     www      13562: }
                   13563: 
                   13564: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 13565: 
                   13566: sub encode_symb {
                   13567:     my ($map,$resid,$url)=@_;
                   13568:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   13569: }
1.409     www      13570: 
                   13571: sub decode_symb {
1.568     albertel 13572:     my $symb=shift;
                   13573:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   13574:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      13575:     return (&fixversion($map),$resid,&fixversion($url));
                   13576: }
                   13577: 
                   13578: sub fixversion {
                   13579:     my $fn=shift;
1.609     banghart 13580:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      13581:     my %bighash;
                   13582:     my $uri=&clutter($fn);
1.620     albertel 13583:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      13584: # is this cached?
1.599     albertel 13585:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      13586:     if (defined($cached)) { return $result; }
                   13587: # unfortunately not cached, or expired
1.620     albertel 13588:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      13589: 	    &GDBM_READER(),0640)) {
                   13590:  	if ($bighash{'version_'.$uri}) {
                   13591:  	    my $version=$bighash{'version_'.$uri};
1.444     www      13592:  	    unless (($version eq 'mostrecent') || 
                   13593: 		    ($version==&getversion($uri))) {
1.440     www      13594:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   13595:  	    }
                   13596:  	}
                   13597:  	untie %bighash;
1.413     www      13598:     }
1.599     albertel 13599:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      13600: }
                   13601: 
                   13602: sub deversion {
                   13603:     my $url=shift;
                   13604:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   13605:     return $url;
1.210     www      13606: }
                   13607: 
1.31      www      13608: # ------------------------------------------------------ Return symb list entry
                   13609: 
                   13610: sub symbread {
1.1172.2.126  raeburn  13611:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128  raeburn  13612:         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  13613:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128  raeburn  13614:     if (defined($env{$cache_str})) {
1.1172.2.126  raeburn  13615:         unless (ref($possibles) eq 'HASH') {
                   13616:             if ($ignorecachednull) {
                   13617:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   13618:             } else {
                   13619:                 return $env{$cache_str};
                   13620:             }
1.1172.2.66  raeburn  13621:         }
                   13622:     }
1.242     www      13623: # no filename provided? try from environment
1.1172.2.54  raeburn  13624:     unless ($thisfn) {
1.620     albertel 13625:         if ($env{'request.symb'}) {
1.1172.2.128  raeburn  13626:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  13627:         }
                   13628:         $thisfn=$env{'request.filename'};
1.44      www      13629:     }
1.569     albertel 13630:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13631: # is that filename actually a symb? Verify, clean, and return
                   13632:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13633: 	if (&symbverify($thisfn,$1)) {
1.1172.2.128  raeburn  13634: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13635: 	}
1.242     www      13636:     }
1.44      www      13637:     $thisfn=declutter($thisfn);
1.31      www      13638:     my %hash;
1.37      www      13639:     my %bighash;
                   13640:     my $syval='';
1.620     albertel 13641:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.1172.2.128  raeburn  13642:         unless ($ignoresymbdb) {
1.1172.2.126  raeburn  13643:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   13644:                           &GDBM_READER(),0640)) {
1.1172.2.146.  .7(raebu 13645:22): 	        $syval=$hash{$thisfn};
1.1172.2.126  raeburn  13646:                 untie(%hash);
                   13647:             }
1.1172.2.128  raeburn  13648:             if ($syval && $checkforblock) {
                   13649:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126  raeburn  13650:                 if (@blockers) {
                   13651:                     $syval='';
                   13652:                 }
                   13653:             }
1.37      www      13654:         }
                   13655: # ---------------------------------------------------------- There was an entry
                   13656:         if ($syval) {
1.601     albertel 13657: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13658: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13659: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13660: 		    #return $env{$cache_str}='';
1.601     albertel 13661: 		#}    
                   13662: 		#$syval.=$1;
                   13663: 	    #}
1.37      www      13664:         } else {
                   13665: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13666:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13667:                             &GDBM_READER(),0640)) {
1.37      www      13668: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13669:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13670:               unless ($ids) { 
                   13671:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13672:               }
                   13673:               unless ($ids) {
                   13674: # alias?
                   13675: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13676:               }
1.37      www      13677:               if ($ids) {
                   13678: # ------------------------------------------------------------------- Has ID(s)
                   13679:                  my @possibilities=split(/\,/,$ids);
1.39      www      13680:                  if ($#possibilities==0) {
                   13681: # ----------------------------------------------- There is only one possibility
1.37      www      13682: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13683: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13684: 						    $resid,$thisfn);
1.1172.2.66  raeburn  13685:                      if (ref($possibles) eq 'HASH') {
1.1172.2.126  raeburn  13686:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   13687:                              $possibles->{$syval} = 1;
                   13688:                          }
1.1172.2.66  raeburn  13689:                      }
                   13690:                      if ($checkforblock) {
1.1172.2.126  raeburn  13691:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127  raeburn  13692:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126  raeburn  13693:                              if (@blockers) {
                   13694:                                  $syval = '';
                   13695:                                  untie(%bighash);
                   13696:                                  return $env{$cache_str}='';
                   13697:                              }
1.1172.2.66  raeburn  13698:                          }
                   13699:                      }
                   13700:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      13701: # ------------------------------------------ There is more than one possibility
                   13702:                      my $realpossible=0;
1.800     albertel 13703:                      foreach my $id (@possibilities) {
                   13704: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  13705:                          my $canaccess;
                   13706:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13707:                              $canaccess = 1;
                   13708:                          } else {
                   13709:                              $canaccess = &allowed('bre',$file);
                   13710:                          }
                   13711:                          if ($canaccess) {
                   13712:          		     my ($mapid,$resid)=split(/\./,$id);
                   13713:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13714:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13715:                                                              $resid,$thisfn);
1.1172.2.126  raeburn  13716:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127  raeburn  13717:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  13718:                                  if ($checkforblock) {
1.1172.2.127  raeburn  13719:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126  raeburn  13720:                                      if (@blockers > 0) {
                   13721:                                          $syval = '';
                   13722:                                      } else {
1.1172.2.66  raeburn  13723:                                          $syval = $poss_syval;
                   13724:                                          $realpossible++;
                   13725:                                      }
                   13726:                                  } else {
                   13727:                                      $syval = $poss_syval;
                   13728:                                      $realpossible++;
                   13729:                                  }
1.1172.2.126  raeburn  13730:                                  if ($syval) {
                   13731:                                      if (ref($possibles) eq 'HASH') {
                   13732:                                          $possibles->{$syval} = 1;
                   13733:                                      }
                   13734:                                  }
1.1172.2.66  raeburn  13735:                              }
1.39      www      13736: 			 }
1.191     harris41 13737:                      }
1.39      www      13738: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13739:                  } else {
                   13740:                      $syval='';
1.37      www      13741:                  }
                   13742: 	      }
1.1172.2.66  raeburn  13743:               untie(%bighash);
1.481     raeburn  13744:            }
1.31      www      13745:         }
1.62      www      13746:         if ($syval) {
1.1172.2.128  raeburn  13747: 	    return $env{$cache_str}=$syval;
1.62      www      13748:         }
1.31      www      13749:     }
1.949     raeburn  13750:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13751:     return $env{$cache_str}='';
1.31      www      13752: }
                   13753: 
                   13754: # ---------------------------------------------------------- Return random seed
                   13755: 
1.32      www      13756: sub numval {
                   13757:     my $txt=shift;
                   13758:     $txt=~tr/A-J/0-9/;
                   13759:     $txt=~tr/a-j/0-9/;
                   13760:     $txt=~tr/K-T/0-9/;
                   13761:     $txt=~tr/k-t/0-9/;
                   13762:     $txt=~tr/U-Z/0-5/;
                   13763:     $txt=~tr/u-z/0-5/;
                   13764:     $txt=~s/\D//g;
1.564     albertel 13765:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13766:     return int($txt);
1.368     albertel 13767: }
                   13768: 
1.484     albertel 13769: sub numval2 {
                   13770:     my $txt=shift;
                   13771:     $txt=~tr/A-J/0-9/;
                   13772:     $txt=~tr/a-j/0-9/;
                   13773:     $txt=~tr/K-T/0-9/;
                   13774:     $txt=~tr/k-t/0-9/;
                   13775:     $txt=~tr/U-Z/0-5/;
                   13776:     $txt=~tr/u-z/0-5/;
                   13777:     $txt=~s/\D//g;
                   13778:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13779:     my $total;
                   13780:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13781:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13782:     return int($total);
                   13783: }
                   13784: 
1.575     albertel 13785: sub numval3 {
                   13786:     use integer;
                   13787:     my $txt=shift;
                   13788:     $txt=~tr/A-J/0-9/;
                   13789:     $txt=~tr/a-j/0-9/;
                   13790:     $txt=~tr/K-T/0-9/;
                   13791:     $txt=~tr/k-t/0-9/;
                   13792:     $txt=~tr/U-Z/0-5/;
                   13793:     $txt=~tr/u-z/0-5/;
                   13794:     $txt=~s/\D//g;
                   13795:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13796:     my $total;
                   13797:     foreach my $val (@txts) { $total+=$val; }
                   13798:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13799:     return $total;
                   13800: }
                   13801: 
1.675     albertel 13802: sub digest {
                   13803:     my ($data)=@_;
                   13804:     my $digest=&Digest::MD5::md5($data);
                   13805:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13806:     my ($e,$f);
                   13807:     {
                   13808:         use integer;
                   13809:         $e=($a+$b);
                   13810:         $f=($c+$d);
                   13811:         if ($_64bit) {
                   13812:             $e=(($e<<32)>>32);
                   13813:             $f=(($f<<32)>>32);
                   13814:         }
                   13815:     }
                   13816:     if (wantarray) {
                   13817: 	return ($e,$f);
                   13818:     } else {
                   13819: 	my $g;
                   13820: 	{
                   13821: 	    use integer;
                   13822: 	    $g=($e+$f);
                   13823: 	    if ($_64bit) {
                   13824: 		$g=(($g<<32)>>32);
                   13825: 	    }
                   13826: 	}
                   13827: 	return $g;
                   13828:     }
                   13829: }
                   13830: 
1.368     albertel 13831: sub latest_rnd_algorithm_id {
1.675     albertel 13832:     return '64bit5';
1.366     albertel 13833: }
1.32      www      13834: 
1.503     albertel 13835: sub get_rand_alg {
                   13836:     my ($courseid)=@_;
1.790     albertel 13837:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13838:     if ($courseid) {
1.620     albertel 13839: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13840:     }
                   13841:     return &latest_rnd_algorithm_id();
                   13842: }
                   13843: 
1.562     albertel 13844: sub validCODE {
                   13845:     my ($CODE)=@_;
                   13846:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13847:     return 0;
                   13848: }
                   13849: 
1.491     albertel 13850: sub getCODE {
1.620     albertel 13851:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13852:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13853: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13854: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13855: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13856:     }
                   13857:     return undef;
                   13858: }
1.1133    foxr     13859: #
                   13860: #  Determines the random seed for a specific context:
                   13861: #
                   13862: # parameters:
                   13863: #   symb      - in course context the symb for the seed.
                   13864: #   course_id - The course id of the form domain_coursenum.
                   13865: #   domain    - Domain for the user.
                   13866: #   course    - Course for the user.
                   13867: #   cenv      - environment of the course.
                   13868: #
                   13869: # NOTE:
                   13870: #   All parameters are picked out of the environment if missing
                   13871: #   or not defined.
                   13872: #   If a symb cannot be determined the current time is used instead.
                   13873: #
                   13874: #  For a given well defined symb, courside, domain, username,
                   13875: #  and course environment, the seed is reproducible.
                   13876: #
1.31      www      13877: sub rndseed {
1.1133    foxr     13878:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13879:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13880:     if (!defined($symb)) {
1.366     albertel 13881: 	unless ($symb=$wsymb) { return time; }
                   13882:     }
1.1146    foxr     13883:     if (!defined $courseid) { 
                   13884: 	$courseid=$wcourseid; 
                   13885:     }
                   13886:     if (!defined $domain) { $domain=$wdomain; }
                   13887:     if (!defined $username) { $username=$wusername }
1.1133    foxr     13888: 
                   13889:     my $which;
                   13890:     if (defined($cenv->{'rndseed'})) {
                   13891: 	$which = $cenv->{'rndseed'};
                   13892:     } else {
                   13893: 	$which =&get_rand_alg($courseid);
                   13894:     }
1.491     albertel 13895:     if (defined(&getCODE())) {
1.675     albertel 13896: 	if ($which eq '64bit5') {
                   13897: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   13898: 	} elsif ($which eq '64bit4') {
1.575     albertel 13899: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   13900: 	} else {
                   13901: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   13902: 	}
1.675     albertel 13903:     } elsif ($which eq '64bit5') {
                   13904: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 13905:     } elsif ($which eq '64bit4') {
                   13906: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 13907:     } elsif ($which eq '64bit3') {
                   13908: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 13909:     } elsif ($which eq '64bit2') {
                   13910: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13911:     } elsif ($which eq '64bit') {
                   13912: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13913:     }
                   13914:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13915: }
                   13916: 
                   13917: sub rndseed_32bit {
                   13918:     my ($symb,$courseid,$domain,$username)=@_;
                   13919:     {
                   13920: 	use integer;
                   13921: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13922: 	my $symbseed=numval($symb) << 22;
                   13923: 	my $namechck=unpack("%32C*",$username) << 17;
                   13924: 	my $nameseed=numval($username) << 12;
                   13925: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13926: 	my $courseseed=unpack("%32C*",$courseid);
                   13927: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13928: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13929: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13930: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13931: 	return $num;
                   13932:     }
                   13933: }
                   13934: 
                   13935: sub rndseed_64bit {
                   13936:     my ($symb,$courseid,$domain,$username)=@_;
                   13937:     {
                   13938: 	use integer;
                   13939: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13940: 	my $symbseed=numval($symb) << 10;
                   13941: 	my $namechck=unpack("%32S*",$username);
                   13942: 	
                   13943: 	my $nameseed=numval($username) << 21;
                   13944: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13945: 	my $courseseed=unpack("%32S*",$courseid);
                   13946: 	
                   13947: 	my $num1=$symbchck+$symbseed+$namechck;
                   13948: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13949: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13950: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13951: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13952: 	return "$num1,$num2";
1.155     albertel 13953:     }
1.366     albertel 13954: }
                   13955: 
1.443     albertel 13956: sub rndseed_64bit2 {
                   13957:     my ($symb,$courseid,$domain,$username)=@_;
                   13958:     {
                   13959: 	use integer;
                   13960: 	# strings need to be an even # of cahracters long, it it is odd the
                   13961:         # last characters gets thrown away
                   13962: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13963: 	my $symbseed=numval($symb) << 10;
                   13964: 	my $namechck=unpack("%32S*",$username.' ');
                   13965: 	
                   13966: 	my $nameseed=numval($username) << 21;
1.501     albertel 13967: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13968: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13969: 	
                   13970: 	my $num1=$symbchck+$symbseed+$namechck;
                   13971: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13972: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13973: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13974: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13975: 	return "$num1,$num2";
                   13976:     }
                   13977: }
                   13978: 
                   13979: sub rndseed_64bit3 {
                   13980:     my ($symb,$courseid,$domain,$username)=@_;
                   13981:     {
                   13982: 	use integer;
                   13983: 	# strings need to be an even # of cahracters long, it it is odd the
                   13984:         # last characters gets thrown away
                   13985: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13986: 	my $symbseed=numval2($symb) << 10;
                   13987: 	my $namechck=unpack("%32S*",$username.' ');
                   13988: 	
                   13989: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13990: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13991: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13992: 	
                   13993: 	my $num1=$symbchck+$symbseed+$namechck;
                   13994: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13995: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13996: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13997: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13998: 	
1.503     albertel 13999: 	return "$num1:$num2";
1.443     albertel 14000:     }
                   14001: }
                   14002: 
1.575     albertel 14003: sub rndseed_64bit4 {
                   14004:     my ($symb,$courseid,$domain,$username)=@_;
                   14005:     {
                   14006: 	use integer;
                   14007: 	# strings need to be an even # of cahracters long, it it is odd the
                   14008:         # last characters gets thrown away
                   14009: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   14010: 	my $symbseed=numval3($symb) << 10;
                   14011: 	my $namechck=unpack("%32S*",$username.' ');
                   14012: 	
                   14013: 	my $nameseed=numval3($username) << 21;
                   14014: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   14015: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14016: 	
                   14017: 	my $num1=$symbchck+$symbseed+$namechck;
                   14018: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 14019: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14020: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 14021: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      14022: 	
1.575     albertel 14023: 	return "$num1:$num2";
                   14024:     }
                   14025: }
                   14026: 
1.675     albertel 14027: sub rndseed_64bit5 {
                   14028:     my ($symb,$courseid,$domain,$username)=@_;
                   14029:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   14030:     return "$num1:$num2";
                   14031: }
                   14032: 
1.366     albertel 14033: sub rndseed_CODE_64bit {
                   14034:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 14035:     {
1.366     albertel 14036: 	use integer;
1.443     albertel 14037: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 14038: 	my $symbseed=numval2($symb);
1.491     albertel 14039: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   14040: 	my $CODEseed=numval(&getCODE());
1.443     albertel 14041: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 14042: 	my $num1=$symbseed+$CODEchck;
                   14043: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 14044: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   14045: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 14046: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   14047: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 14048: 	return "$num1:$num2";
1.366     albertel 14049:     }
                   14050: }
                   14051: 
1.575     albertel 14052: sub rndseed_CODE_64bit4 {
                   14053:     my ($symb,$courseid,$domain,$username)=@_;
                   14054:     {
                   14055: 	use integer;
                   14056: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   14057: 	my $symbseed=numval3($symb);
                   14058: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   14059: 	my $CODEseed=numval3(&getCODE());
                   14060: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14061: 	my $num1=$symbseed+$CODEchck;
                   14062: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 14063: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   14064: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 14065: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   14066: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   14067: 	return "$num1:$num2";
                   14068:     }
                   14069: }
                   14070: 
1.675     albertel 14071: sub rndseed_CODE_64bit5 {
                   14072:     my ($symb,$courseid,$domain,$username)=@_;
                   14073:     my $code = &getCODE();
                   14074:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   14075:     return "$num1:$num2";
                   14076: }
                   14077: 
1.366     albertel 14078: sub setup_random_from_rndseed {
                   14079:     my ($rndseed)=@_;
1.503     albertel 14080:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  14081: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   14082:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   14083:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   14084:         } else {
                   14085:             &Math::Random::random_set_seed($num1,$num2);
                   14086:         }
1.366     albertel 14087:     } else {
                   14088: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 14089:     }
1.36      albertel 14090: }
                   14091: 
1.474     albertel 14092: sub latest_receipt_algorithm_id {
1.835     albertel 14093:     return 'receipt3';
1.474     albertel 14094: }
                   14095: 
1.480     www      14096: sub recunique {
                   14097:     my $fucourseid=shift;
                   14098:     my $unique;
1.835     albertel 14099:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   14100: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 14101: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      14102:     } else {
                   14103: 	$unique=$perlvar{'lonReceipt'};
                   14104:     }
                   14105:     return unpack("%32C*",$unique);
                   14106: }
                   14107: 
                   14108: sub recprefix {
                   14109:     my $fucourseid=shift;
                   14110:     my $prefix;
1.835     albertel 14111:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   14112: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 14113: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      14114:     } else {
                   14115: 	$prefix=$perlvar{'lonHostID'};
                   14116:     }
                   14117:     return unpack("%32C*",$prefix);
                   14118: }
                   14119: 
1.76      www      14120: sub ireceipt {
1.474     albertel 14121:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 14122: 
                   14123:     my $return =&recprefix($fucourseid).'-';
                   14124: 
                   14125:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   14126: 	$env{'request.state'} eq 'construct') {
                   14127: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   14128: 	return $return;
                   14129:     }
                   14130: 
1.76      www      14131:     my $cuname=unpack("%32C*",$funame);
                   14132:     my $cudom=unpack("%32C*",$fudom);
                   14133:     my $cucourseid=unpack("%32C*",$fucourseid);
                   14134:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      14135:     my $cunique=&recunique($fucourseid);
1.474     albertel 14136:     my $cpart=unpack("%32S*",$part);
1.835     albertel 14137:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   14138: 
1.790     albertel 14139: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 14140: 			       
                   14141: 	$return.= ($cunique%$cuname+
                   14142: 		   $cunique%$cudom+
                   14143: 		   $cusymb%$cuname+
                   14144: 		   $cusymb%$cudom+
                   14145: 		   $cucourseid%$cuname+
                   14146: 		   $cucourseid%$cudom+
                   14147: 		   $cpart%$cuname+
                   14148: 		   $cpart%$cudom);
                   14149:     } else {
                   14150: 	$return.= ($cunique%$cuname+
                   14151: 		   $cunique%$cudom+
                   14152: 		   $cusymb%$cuname+
                   14153: 		   $cusymb%$cudom+
                   14154: 		   $cucourseid%$cuname+
                   14155: 		   $cucourseid%$cudom);
                   14156:     }
                   14157:     return $return;
1.76      www      14158: }
                   14159: 
                   14160: sub receipt {
1.474     albertel 14161:     my ($part)=@_;
1.790     albertel 14162:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 14163:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      14164: }
1.260     ng       14165: 
1.790     albertel 14166: sub whichuser {
                   14167:     my ($passedsymb)=@_;
                   14168:     my ($symb,$courseid,$domain,$name,$publicuser);
                   14169:     if (defined($env{'form.grade_symb'})) {
                   14170: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   14171: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   14172: 	if (!$allowed &&
                   14173: 	    exists($env{'request.course.sec'}) &&
                   14174: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   14175: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   14176: 			      '/'.$env{'request.course.sec'});
                   14177: 	}
                   14178: 	if ($allowed) {
                   14179: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   14180: 	    $courseid=$tmp_courseid;
                   14181: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   14182: 	    ($name)=&get_env_multiple('form.grade_username');
                   14183: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   14184: 	}
                   14185:     }
                   14186:     if (!$passedsymb) {
                   14187: 	$symb=&symbread();
                   14188:     } else {
                   14189: 	$symb=$passedsymb;
                   14190:     }
                   14191:     $courseid=$env{'request.course.id'};
                   14192:     $domain=$env{'user.domain'};
                   14193:     $name=$env{'user.name'};
                   14194:     if ($name eq 'public' && $domain eq 'public') {
                   14195: 	if (!defined($env{'form.username'})) {
                   14196: 	    $env{'form.username'}.=time.rand(10000000);
                   14197: 	}
                   14198: 	$name.=$env{'form.username'};
                   14199:     }
                   14200:     return ($symb,$courseid,$domain,$name,$publicuser);
                   14201: 
                   14202: }
                   14203: 
1.36      albertel 14204: # ------------------------------------------------------------ Serves up a file
1.472     albertel 14205: # returns either the contents of the file or 
                   14206: # -1 if the file doesn't exist
1.481     raeburn  14207: #
                   14208: # if the target is a file that was uploaded via DOCS, 
                   14209: # a check will be made to see if a current copy exists on the local server,
                   14210: # if it does this will be served, otherwise a copy will be retrieved from
                   14211: # the home server for the course and stored in /home/httpd/html/userfiles on
                   14212: # the local server.   
1.472     albertel 14213: 
1.36      albertel 14214: sub getfile {
1.538     albertel 14215:     my ($file) = @_;
1.609     banghart 14216:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 14217:     &repcopy($file);
                   14218:     return &readfile($file);
                   14219: }
                   14220: 
                   14221: sub repcopy_userfile {
                   14222:     my ($file)=@_;
1.1142    raeburn  14223:     my $londocroot = $perlvar{'lonDocRoot'};
                   14224:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  14225:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 14226:     my ($cdom,$cnum,$filename) = 
1.811     albertel 14227: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 14228:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   14229:     if (-e "$file") {
1.828     www      14230: # we already have a local copy, check it out
1.538     albertel 14231: 	my @fileinfo = stat($file);
1.828     www      14232: 	my $rtncode;
                   14233: 	my $info;
1.538     albertel 14234: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 14235: 	if ($lwpresp ne 'ok') {
1.828     www      14236: # there is no such file anymore, even though we had a local copy
1.482     albertel 14237: 	    if ($rtncode eq '404') {
1.538     albertel 14238: 		unlink($file);
1.482     albertel 14239: 	    }
                   14240: 	    return -1;
                   14241: 	}
                   14242: 	if ($info < $fileinfo[9]) {
1.828     www      14243: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  14244: 	    return 'ok';
1.828     www      14245: 	} else {
                   14246: # the file is outdated, get rid of it
                   14247: 	    unlink($file);
1.482     albertel 14248: 	}
1.828     www      14249:     }
                   14250: # one way or the other, at this point, we don't have the file
                   14251: # construct the correct path for the file
                   14252:     my @parts = ($cdom,$cnum); 
                   14253:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   14254: 	push @parts, split(/\//,$1);
                   14255:     }
                   14256:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   14257:     foreach my $part (@parts) {
                   14258: 	$path .= '/'.$part;
                   14259: 	if (!-e $path) {
                   14260: 	    mkdir($path,0770);
1.482     albertel 14261: 	}
                   14262:     }
1.828     www      14263: # now the path exists for sure
                   14264: # get a user agent
                   14265:     my $ua=new LWP::UserAgent;
                   14266:     my $transferfile=$file.'.in.transfer';
                   14267: # FIXME: this should flock
                   14268:     if (-e $transferfile) { return 'ok'; }
                   14269:     my $request;
                   14270:     $uri=~s/^\///;
1.980     raeburn  14271:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  14272:     my $hostname = &hostname($homeserver);
1.980     raeburn  14273:     my $protocol = $protocol{$homeserver};
                   14274:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  14275:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      14276:     my $response=$ua->request($request,$transferfile);
                   14277: # did it work?
                   14278:     if ($response->is_error()) {
                   14279: 	unlink($transferfile);
                   14280: 	&logthis("Userfile repcopy failed for $uri");
                   14281: 	return -1;
                   14282:     }
                   14283: # worked, rename the transfer file
                   14284:     rename($transferfile,$file);
1.607     raeburn  14285:     return 'ok';
1.481     raeburn  14286: }
                   14287: 
1.517     albertel 14288: sub tokenwrapper {
                   14289:     my $uri=shift;
1.980     raeburn  14290:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 14291:     $uri=~s|^/||;
1.620     albertel 14292:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 14293:     my $token=$1;
1.552     albertel 14294:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   14295:     if ($udom && $uname && $file) {
                   14296: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  14297:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  14298:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.120  raeburn  14299:         my $hostname = &hostname($homeserver);
1.980     raeburn  14300:         my $protocol = $protocol{$homeserver};
                   14301:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  14302:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 14303:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   14304:                                '&tokenissued='.$perlvar{'lonHostID'};
                   14305:     } else {
                   14306:         return '/adm/notfound.html';
                   14307:     }
                   14308: }
                   14309: 
1.828     www      14310: # call with reqtype HEAD: get last modification time
                   14311: # call with reqtype GET: get the file contents
                   14312: # Do not call this with reqtype GET for large files! It loads everything into memory
                   14313: #
1.481     raeburn  14314: sub getuploaded {
                   14315:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   14316:     $uri=~s/^\///;
1.980     raeburn  14317:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  14318:     my $hostname = &hostname($homeserver);
1.980     raeburn  14319:     my $protocol = $protocol{$homeserver};
                   14320:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  14321:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  14322:     my $ua=new LWP::UserAgent;
                   14323:     my $request=new HTTP::Request($reqtype,$uri);
                   14324:     my $response=$ua->request($request);
                   14325:     $$rtncode = $response->code;
1.482     albertel 14326:     if (! $response->is_success()) {
                   14327: 	return 'failed';
                   14328:     }      
                   14329:     if ($reqtype eq 'HEAD') {
1.486     www      14330: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 14331:     } elsif ($reqtype eq 'GET') {
                   14332: 	$$info = $response->content;
1.472     albertel 14333:     }
1.482     albertel 14334:     return 'ok';
1.36      albertel 14335: }
                   14336: 
1.481     raeburn  14337: sub readfile {
                   14338:     my $file = shift;
                   14339:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   14340:     my $fh;
1.1172.2.96  raeburn  14341:     open($fh,"<",$file);
1.481     raeburn  14342:     my $a='';
1.800     albertel 14343:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  14344:     return $a;
                   14345: }
                   14346: 
1.36      albertel 14347: sub filelocation {
1.590     banghart 14348:     my ($dir,$file) = @_;
                   14349:     my $location;
                   14350:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 14351: 
                   14352:     if ($file =~ m-^/adm/-) {
                   14353: 	$file=~s-^/adm/wrapper/-/-;
                   14354: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   14355:     }
1.882     albertel 14356: 
1.1139    www      14357:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  14358:         $location = $file;
1.609     banghart 14359:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 14360:         my ($udom,$uname,$filename)=
1.811     albertel 14361:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 14362:         my $home=&homeserver($uname,$udom);
                   14363:         my $is_me=0;
                   14364:         my @ids=&current_machine_ids();
                   14365:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   14366:         if ($is_me) {
1.1117    foxr     14367:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 14368:         } else {
                   14369:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   14370:   	      $udom.'/'.$uname.'/'.$filename;
                   14371:         }
1.882     albertel 14372:     } elsif ($file =~ m-^/adm/-) {
                   14373: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 14374:     } else {
                   14375:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      14376:         $file=~s:^/(res|priv)/:/:;
                   14377:         my $space=$1;
1.590     banghart 14378:         if ( !( $file =~ m:^/:) ) {
                   14379:             $location = $dir. '/'.$file;
                   14380:         } else {
1.1142    raeburn  14381:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 14382:         }
1.59      albertel 14383:     }
1.590     banghart 14384:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 14385:     while ($location=~m{/\.\./}) {
                   14386: 	if ($location =~ m{/[^/]+/\.\./}) {
                   14387: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   14388: 	} else {
                   14389: 	    $location=~ s{/\.\./}{/}g;
                   14390: 	}
                   14391:     } #remove dir/..
1.590     banghart 14392:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   14393:     return $location;
1.46      www      14394: }
1.36      albertel 14395: 
1.46      www      14396: sub hreflocation {
                   14397:     my ($dir,$file)=@_;
1.980     raeburn  14398:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 14399: 	$file=filelocation($dir,$file);
1.700     albertel 14400:     } elsif ($file=~m-^/adm/-) {
                   14401: 	$file=~s-^/adm/wrapper/-/-;
                   14402: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 14403:     }
                   14404:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   14405: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   14406:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  14407: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   14408: 	        {/uploaded/$1/$2/}x;
1.46      www      14409:     }
1.913     albertel 14410:     if ($file=~ m{^/userfiles/}) {
                   14411: 	$file =~ s{^/userfiles/}{/uploaded/};
                   14412:     }
1.462     albertel 14413:     return $file;
1.465     albertel 14414: }
                   14415: 
1.1139    www      14416: 
                   14417: 
                   14418: 
                   14419: 
1.465     albertel 14420: sub current_machine_domains {
1.853     albertel 14421:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   14422: }
                   14423: 
                   14424: sub machine_domains {
                   14425:     my ($hostname) = @_;
1.465     albertel 14426:     my @domains;
1.838     albertel 14427:     my %hostname = &all_hostnames();
1.465     albertel 14428:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  14429: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 14430: 	if ($hostname eq $name) {
1.844     albertel 14431: 	    push(@domains,&host_domain($id));
1.465     albertel 14432: 	}
                   14433:     }
                   14434:     return @domains;
                   14435: }
                   14436: 
                   14437: sub current_machine_ids {
1.853     albertel 14438:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   14439: }
                   14440: 
                   14441: sub machine_ids {
                   14442:     my ($hostname) = @_;
                   14443:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 14444:     my @ids;
1.888     albertel 14445:     my %name_to_host = &all_names();
1.889     albertel 14446:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   14447: 	return @{ $name_to_host{$hostname} };
                   14448:     }
                   14449:     return;
1.31      www      14450: }
                   14451: 
1.824     raeburn  14452: sub additional_machine_domains {
                   14453:     my @domains;
1.1172.2.142  raeburn  14454:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
                   14455:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
                   14456:             while( my $line = <$fh>) {
                   14457:                 chomp($line);
                   14458:                 $line =~ s/\s//g;
                   14459:                 push(@domains,$line);
                   14460:             }
                   14461:             close($fh);
                   14462:         }
1.824     raeburn  14463:     }
                   14464:     return @domains;
                   14465: }
                   14466: 
                   14467: sub default_login_domain {
                   14468:     my $domain = $perlvar{'lonDefDomain'};
                   14469:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   14470:     foreach my $posdom (&current_machine_domains(),
                   14471:                         &additional_machine_domains()) {
                   14472:         if (lc($posdom) eq lc($testdomain)) {
                   14473:             $domain=$posdom;
                   14474:             last;
                   14475:         }
                   14476:     }
                   14477:     return $domain;
                   14478: }
                   14479: 
1.1172.2.106  raeburn  14480: sub shared_institution {
1.1172.2.136  raeburn  14481:     my ($dom,$lonhost) = @_;
                   14482:     if ($lonhost eq '') {
                   14483:         $lonhost = $perlvar{'lonHostID'};
                   14484:     }
1.1172.2.106  raeburn  14485:     my $same_intdom;
1.1172.2.136  raeburn  14486:     my $hostintdom = &internet_dom($lonhost);
1.1172.2.106  raeburn  14487:     if ($hostintdom ne '') {
                   14488:         my %iphost = &get_iphost();
                   14489:         my $primary_id = &domain($dom,'primary');
                   14490:         my $primary_ip = &get_host_ip($primary_id);
                   14491:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   14492:             foreach my $id (@{$iphost{$primary_ip}}) {
                   14493:                 my $intdom = &internet_dom($id);
                   14494:                 if ($intdom eq $hostintdom) {
                   14495:                     $same_intdom = 1;
                   14496:                     last;
                   14497:                 }
                   14498:             }
                   14499:         }
                   14500:     }
                   14501:     return $same_intdom;
                   14502: }
                   14503: 
1.1172.2.120  raeburn  14504: sub uses_sts {
                   14505:     my ($ignore_cache) = @_;
                   14506:     my $lonhost = $perlvar{'lonHostID'};
                   14507:     my $hostname = &hostname($lonhost);
                   14508:     my $sts_on;
                   14509:     if ($protocol{$lonhost} eq 'https') {
                   14510:         my $cachetime = 12*3600;
                   14511:         if (!$ignore_cache) {
                   14512:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   14513:             if (defined($cached)) {
                   14514:                 return $sts_on;
                   14515:             }
                   14516:         }
1.1172.2.121  raeburn  14517:         my $ua=new LWP::UserAgent;
1.1172.2.120  raeburn  14518:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   14519:         my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121  raeburn  14520:         my $response=$ua->request($request);
1.1172.2.120  raeburn  14521:         if ($response->is_success) {
                   14522:             my $has_sts = $response->header('Strict-Transport-Security');
                   14523:             if ($has_sts eq '') {
                   14524:                 $sts_on = 0;
                   14525:             } else {
                   14526:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   14527:                     my $maxage = $1;
                   14528:                     if ($maxage) {
                   14529:                         $sts_on = 1;
                   14530:                     } else {
                   14531:                         $sts_on = 0;
                   14532:                     }
                   14533:                 } else {
                   14534:                     $sts_on = 0;
                   14535:                 }
                   14536:             }
                   14537:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   14538:         }
                   14539:     }
                   14540:     return;
                   14541: }
                   14542: 
1.1172.2.142  raeburn  14543: sub waf_allssl {
                   14544:     my ($host_name) = @_;
                   14545:     my $alias = &get_proxy_alias();
                   14546:     if ($host_name eq '') {
                   14547:         $host_name = $ENV{'SERVER_NAME'};
                   14548:     }
                   14549:     if (($host_name ne '') && ($alias eq $host_name)) {
                   14550:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   14551:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   14552:         if ($defdomdefaults{'waf_sslopt'}) {
                   14553:             return $defdomdefaults{'waf_sslopt'};
                   14554:         }
                   14555:     }
                   14556:     return;
                   14557: }
                   14558: 
1.1172.2.134  raeburn  14559: sub get_requestor_ip {
                   14560:     my ($r,$nolookup,$noproxy) = @_;
                   14561:     my $from_ip;
                   14562:     if (ref($r)) {
1.1172.2.142  raeburn  14563:         if ($r->can('useragent_ip')) {
                   14564:             if ($noproxy && $r->can('client_ip')) {
                   14565:                 $from_ip = $r->client_ip();
                   14566:             } else {
                   14567:                 $from_ip = $r->useragent_ip();
                   14568:             }
                   14569:         } elsif ($r->connection->can('remote_ip')) {
                   14570:             $from_ip = $r->connection->remote_ip();
                   14571:         } else {
                   14572:             $from_ip = $r->get_remote_host($nolookup);
                   14573:         }
1.1172.2.134  raeburn  14574:     } else {
                   14575:         $from_ip = $ENV{'REMOTE_ADDR'};
                   14576:     }
1.1172.2.142  raeburn  14577:     return $from_ip if ($noproxy);
                   14578:    # Who controls proxy settings for server
                   14579:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14580:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   14581:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
                   14582:         if ($proxyinfo->{'vpnint'}) {
                   14583:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
                   14584:                 return $from_ip;
                   14585:             }
                   14586:         }
                   14587:         if ($proxyinfo->{'trusted'}) {
                   14588:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   14589:                 my $ipheader = $proxyinfo->{'ipheader'};
                   14590:                 my ($ip,$xfor);
                   14591:                 if (ref($r)) {
                   14592:                     if ($ipheader) {
                   14593:                         $ip = $r->headers_in->{$ipheader};
                   14594:                     }
                   14595:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   14596:                 } else {
                   14597:                     if ($ipheader) {
                   14598:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   14599:                     }
                   14600:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   14601:                 }
                   14602:                 if (($ip eq '') && ($xfor ne '')) {
                   14603:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   14604:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   14605:                             $ip = $poss_ip;
                   14606:                             last;
                   14607:                         }
                   14608:                     }
                   14609:                 }
                   14610:                 if ($ip ne '') {
                   14611:                     return $ip;
                   14612:                 }
                   14613:             }
                   14614:         }
                   14615:     }
1.1172.2.134  raeburn  14616:     return $from_ip;
                   14617: }
                   14618: 
1.1172.2.142  raeburn  14619: sub get_proxy_settings {
                   14620:     my ($dom_in_use) = @_;
                   14621:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   14622:     my $proxyinfo = {
                   14623:                        ipheader => $domdefaults{'waf_ipheader'},
                   14624:                        trusted  => $domdefaults{'waf_trusted'},
                   14625:                        vpnint   => $domdefaults{'waf_vpnint'},
                   14626:                        vpnext   => $domdefaults{'waf_vpnext'},
                   14627:                        sslopt   => $domdefaults{'waf_sslopt'},
                   14628:                     };
                   14629:     return $proxyinfo;
                   14630: }
                   14631: 
                   14632: sub ip_match {
                   14633:     my ($ip,$pattern_str) = @_;
                   14634:     $ip=Net::CIDR::cidrvalidate($ip);
                   14635:     if ($ip) {
                   14636:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   14637:     }
                   14638:     return;
                   14639: }
                   14640: 
                   14641: sub get_proxy_alias {
                   14642:     my ($lonid) = @_;
                   14643:     if ($lonid eq '') {
                   14644:         $lonid = $perlvar{'lonHostID'};
                   14645:     }
                   14646:     if (!defined(&hostname($lonid))) {
                   14647:         return;
                   14648:     }
                   14649:     if ($lonid ne '') {
                   14650:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
                   14651:         if ($cached) {
                   14652:             return $alias;
                   14653:         }
                   14654:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14655:         if ($dom ne '') {
                   14656:             my $cachetime = 60*60*24;
                   14657:             my %domconfig =
                   14658:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14659:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14660:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
                   14661:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   14662:                 }
                   14663:             }
                   14664:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   14665:         }
                   14666:     }
                   14667:     return;
                   14668: }
                   14669: 
                   14670: sub use_proxy_alias {
                   14671:     my ($r,$lonid) = @_;
                   14672:     my $alias = &get_proxy_alias($lonid);
                   14673:     if ($alias) {
                   14674:         my $dom = &host_domain($lonid);
                   14675:         if ($dom ne '') {
                   14676:             my $proxyinfo = &get_proxy_settings($dom);
                   14677:             my ($vpnint,$remote_ip);
                   14678:             if (ref($proxyinfo) eq 'HASH') {
                   14679:                 $vpnint = $proxyinfo->{'vpnint'};
                   14680:                 if ($vpnint) {
                   14681:                     $remote_ip = &get_requestor_ip($r,1,1);
                   14682:                 }
                   14683:             }
                   14684:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   14685:                 return $alias;
                   14686:             }
                   14687:         }
                   14688:     }
                   14689:     return;
                   14690: }
                   14691: 
                   14692: sub alias_sso {
                   14693:     my ($lonid) = @_;
                   14694:     if ($lonid eq '') {
                   14695:         $lonid = $perlvar{'lonHostID'};
                   14696:     }
                   14697:     if (!defined(&hostname($lonid))) {
                   14698:         return;
                   14699:     }
                   14700:     if ($lonid ne '') {
                   14701:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
                   14702:         if ($cached) {
                   14703:             return $use_alias;
                   14704:         }
                   14705:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14706:         if ($dom ne '') {
                   14707:             my $cachetime = 60*60*24;
                   14708:             my %domconfig =
                   14709:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14710:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14711:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
                   14712:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
                   14713:                 }
                   14714:             }
                   14715:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
                   14716:         }
                   14717:     }
                   14718:     return;
                   14719: }
                   14720: 
                   14721: sub get_saml_landing {
                   14722:     my ($lonid) = @_;
                   14723:     if ($lonid eq '') {
                   14724:         my $defdom = &default_login_domain();
                   14725:         my @hosts = &current_machine_ids();
                   14726:         if (@hosts > 1) {
                   14727:             foreach my $hostid (@hosts) {
                   14728:                 if (&host_domain($hostid) eq $defdom) {
                   14729:                     $lonid = $hostid;
                   14730:                     last;
                   14731:                 }
                   14732:             }
                   14733:         } else {
                   14734:             $lonid = $perlvar{'lonHostID'};
                   14735:         }
                   14736:         if ($lonid) {
                   14737:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
                   14738:                 return;
                   14739:             }
                   14740:         } else {
                   14741:             return;
                   14742:         }
                   14743:     } elsif (!defined(&hostname($lonid))) {
                   14744:         return;
                   14745:     }
                   14746:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   14747:     if ($cached) {
                   14748:         return $landing;
                   14749:     }
                   14750:     my $dom = &Apache::lonnet::host_domain($lonid);
                   14751:     if ($dom ne '') {
                   14752:         my $cachetime = 60*60*24;
                   14753:         my %domconfig =
                   14754:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
                   14755:         if (ref($domconfig{'login'}) eq 'HASH') {
                   14756:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   14757:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   14758:                     $landing = 1;
                   14759:                 }
                   14760:             }
                   14761:         }
                   14762:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   14763:     }
                   14764:     return;
                   14765: }
                   14766: 
1.31      www      14767: # ------------------------------------------------------------- Declutters URLs
                   14768: 
                   14769: sub declutter {
                   14770:     my $thisfn=shift;
1.569     albertel 14771:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  14772:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   14773:         $thisfn=~s{^/home/httpd/html}{};
                   14774:     }
1.31      www      14775:     $thisfn=~s/^\///;
1.697     albertel 14776:     $thisfn=~s|^adm/wrapper/||;
                   14777:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      14778:     $thisfn=~s/^res\///;
1.1172    bisitz   14779:     $thisfn=~s/^priv\///;
1.1032    raeburn  14780:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   14781:         $thisfn=~s/\?.+$//;
                   14782:     }
1.268     www      14783:     return $thisfn;
                   14784: }
                   14785: 
                   14786: # ------------------------------------------------------------- Clutter up URLs
                   14787: 
                   14788: sub clutter {
                   14789:     my $thisfn='/'.&declutter(shift);
1.887     albertel 14790:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 14791: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      14792:        $thisfn='/res'.$thisfn; 
                   14793:     }
1.1031    raeburn  14794:     if ($thisfn !~m|^/adm|) {
                   14795: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 14796: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 14797: 	} else {
                   14798: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   14799: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 14800: 	    if ($embstyle eq 'ssi'
                   14801: 		|| ($embstyle eq 'hdn')
                   14802: 		|| ($embstyle eq 'rat')
                   14803: 		|| ($embstyle eq 'prv')
                   14804: 		|| ($embstyle eq 'ign')) {
                   14805: 		#do nothing with these
                   14806: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 14807: 		|| ($embstyle eq 'emb')
                   14808: 		|| ($embstyle eq 'wrp')) {
                   14809: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 14810: 	    } elsif ($embstyle eq 'unk'
                   14811: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 14812: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 14813: 	    } else {
1.718     www      14814: #		&logthis("Got a blank emb style");
1.695     albertel 14815: 	    }
1.694     albertel 14816: 	}
1.1172.2.146.  .1(raebu 14817:22):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   14818:22):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 14819:     }
1.31      www      14820:     return $thisfn;
1.12      www      14821: }
                   14822: 
1.787     albertel 14823: sub clutter_with_no_wrapper {
                   14824:     my $uri = &clutter(shift);
                   14825:     if ($uri =~ m-^/adm/-) {
                   14826: 	$uri =~ s-^/adm/wrapper/-/-;
                   14827: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14828:     }
                   14829:     return $uri;
                   14830: }
                   14831: 
1.557     albertel 14832: sub freeze_escape {
                   14833:     my ($value)=@_;
                   14834:     if (ref($value)) {
                   14835: 	$value=&nfreeze($value);
                   14836: 	return '__FROZEN__'.&escape($value);
                   14837:     }
                   14838:     return &escape($value);
                   14839: }
                   14840: 
1.11      www      14841: 
1.557     albertel 14842: sub thaw_unescape {
                   14843:     my ($value)=@_;
                   14844:     if ($value =~ /^__FROZEN__/) {
                   14845: 	substr($value,0,10,undef);
                   14846: 	$value=&unescape($value);
                   14847: 	return &thaw($value);
                   14848:     }
                   14849:     return &unescape($value);
                   14850: }
                   14851: 
1.436     albertel 14852: sub correct_line_ends {
                   14853:     my ($result)=@_;
                   14854:     $$result =~s/\r\n/\n/mg;
                   14855:     $$result =~s/\r/\n/mg;
1.415     albertel 14856: }
1.1       albertel 14857: # ================================================================ Main Program
                   14858: 
1.184     www      14859: sub goodbye {
1.204     albertel 14860:    &logthis("Starting Shut down");
1.443     albertel 14861: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14862:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14863: #converted
1.599     albertel 14864: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14865:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14866: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   14867: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 14868: #1.1 only
1.870     albertel 14869: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   14870: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   14871: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   14872: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   14873:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 14874:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   14875:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      14876:    &flushcourselogs();
                   14877:    &logthis("Shutting down");
                   14878: }
                   14879: 
1.852     albertel 14880: sub get_dns {
1.1172.2.17  raeburn  14881:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 14882:     if (!$ignore_cache) {
                   14883: 	my ($content,$cached)=
                   14884: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   14885: 	if ($cached) {
1.1172.2.17  raeburn  14886: 	    &$func($content,$hashref);
1.869     albertel 14887: 	    return;
                   14888: 	}
                   14889:     }
                   14890: 
                   14891:     my %alldns;
1.1172.2.96  raeburn  14892:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   14893:         foreach my $dns (<$config>) {
                   14894: 	    next if ($dns !~ /^\^(\S*)/x);
                   14895:             my $line = $1;
                   14896:             my ($host,$protocol) = split(/:/,$line);
                   14897:             if ($protocol ne 'https') {
                   14898:                 $protocol = 'http';
                   14899:             }
                   14900: 	    $alldns{$host} = $protocol;
1.979     raeburn  14901:         }
1.1172.2.96  raeburn  14902:         close($config);
1.869     albertel 14903:     }
                   14904:     while (%alldns) {
1.1172.2.52  raeburn  14905: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142  raeburn  14906:         my @content;
                   14907:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   14908:             my $command = (split('/',$url))[3];
                   14909:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   14910:             delete($alldns{$dns});
                   14911:             next if (($dir eq '') || ($file eq ''));
                   14912:             if (open(my $config,'<',"$dir/$file")) {
                   14913:                 @content = <$config>;
                   14914:                 close($config);
                   14915:             }
                   14916:         } else {
                   14917: 	    my $ua=new LWP::UserAgent;
                   14918:             $ua->timeout(30);
                   14919: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   14920: 	    my $response=$ua->request($request);
                   14921:             delete($alldns{$dns});
                   14922: 	    next if ($response->is_error());
                   14923: 	    @content = split("\n",$response->content);
                   14924:         }
1.1172.2.17  raeburn  14925:         unless ($nocache) {
1.1172.2.23  raeburn  14926: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  14927:         }
                   14928: 	&$func(\@content,$hashref);
1.869     albertel 14929: 	return;
1.852     albertel 14930:     }
1.871     albertel 14931:     my $which = (split('/',$url))[3];
                   14932:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  14933:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   14934:         my @content = <$config>;
                   14935:         &$func(\@content,$hashref);
                   14936:     }
1.1172.2.17  raeburn  14937:     return;
                   14938: }
                   14939: 
                   14940: # ------------------------------------------------------Get DNS checksums file
                   14941: sub parse_dns_checksums_tab {
                   14942:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  14943:     my $lonhost = $perlvar{'lonHostID'};
                   14944:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  14945:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  14946:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14947:     my $webconfdir = '/etc/httpd/conf';
                   14948:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14949:         $webconfdir = '/etc/apache2';
                   14950:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14951:         if ($1 >= 10) {
                   14952:             $webconfdir = '/etc/apache2';
                   14953:         }
                   14954:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14955:         if ($1 >= 10.0) {
                   14956:             $webconfdir = '/etc/apache2';
                   14957:         }
                   14958:     }
1.1172.2.17  raeburn  14959:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14960:     my (%chksum,%revnum);
                   14961:     if (ref($lines) eq 'ARRAY') {
                   14962:         chomp(@{$lines});
1.1172.2.34  raeburn  14963:         my $version = shift(@{$lines});
                   14964:         if ($version eq $release) {
1.1172.2.17  raeburn  14965:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  14966:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  14967:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14968:                     if ($webconfdir eq '/etc/apache2') {
                   14969:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14970:                     }
                   14971:                 }
1.1172.2.34  raeburn  14972:                 $chksum{$file} = $shasum;
                   14973:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  14974:             }
                   14975:             if (ref($hashref) eq 'HASH') {
                   14976:                 %{$hashref} = (
                   14977:                                 sums     => \%chksum,
                   14978:                                 versions => \%revnum,
                   14979:                               );
                   14980:             }
                   14981:         }
                   14982:     }
1.869     albertel 14983:     return;
1.852     albertel 14984: }
1.1172.2.17  raeburn  14985: 
                   14986: sub fetch_dns_checksums {
                   14987:     my %checksums;
1.1172.2.34  raeburn  14988:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  14989:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  14990:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14991:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  14992:              \%checksums);
                   14993:     return \%checksums;
                   14994: }
                   14995: 
1.1172.2.142  raeburn  14996: sub parse_getdns_url {
                   14997:     my ($command,$url) = @_;
                   14998:     my $dir = $perlvar{'lonTabDir'};
                   14999:     my $file;
                   15000:     if ($command eq 'hosts') {
                   15001:         $file = 'dns_hosts.tab';
                   15002:     } elsif ($command eq 'domain') {
                   15003:         $file = 'dns_domain.tab';
                   15004:     } elsif ($command eq 'checksums') {
                   15005:         my $version = (split('/',$url))[4];
                   15006:         $file = "dns_checksums/$version.tab",
                   15007:     }
                   15008:     return ($dir,$file);
                   15009: }
                   15010: 
1.327     albertel 15011: # ------------------------------------------------------------ Read domain file
                   15012: {
1.852     albertel 15013:     my $loaded;
1.846     albertel 15014:     my %domain;
                   15015: 
1.852     albertel 15016:     sub parse_domain_tab {
                   15017: 	my ($lines) = @_;
                   15018: 	foreach my $line (@$lines) {
                   15019: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      15020: 
1.846     albertel 15021: 	    chomp($line);
1.852     albertel 15022: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 15023: 	    my %this_domain;
                   15024: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   15025: 			       'lang_def', 'city', 'longi', 'lati',
                   15026: 			       'primary') {
                   15027: 		$this_domain{$field} = shift(@elements);
                   15028: 	    }
                   15029: 	    $domain{$name} = \%this_domain;
1.852     albertel 15030: 	}
                   15031:     }
1.864     albertel 15032: 
                   15033:     sub reset_domain_info {
                   15034: 	undef($loaded);
                   15035: 	undef(%domain);
                   15036:     }
                   15037: 
1.852     albertel 15038:     sub load_domain_tab {
1.1172.2.70  raeburn  15039: 	my ($ignore_cache,$nocache) = @_;
                   15040: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 15041: 	my $fh;
1.1172.2.96  raeburn  15042: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 15043: 	    my @lines = <$fh>;
                   15044: 	    &parse_domain_tab(\@lines);
1.448     albertel 15045: 	}
1.852     albertel 15046: 	close($fh);
                   15047: 	$loaded = 1;
1.327     albertel 15048:     }
1.846     albertel 15049: 
                   15050:     sub domain {
1.852     albertel 15051: 	&load_domain_tab() if (!$loaded);
                   15052: 
1.846     albertel 15053: 	my ($name,$what) = @_;
                   15054: 	return if ( !exists($domain{$name}) );
                   15055: 
                   15056: 	if (!$what) {
                   15057: 	    return $domain{$name}{'description'};
                   15058: 	}
                   15059: 	return $domain{$name}{$what};
                   15060:     }
1.974     raeburn  15061: 
                   15062:     sub domain_info {
                   15063:         &load_domain_tab() if (!$loaded);
                   15064:         return %domain;
                   15065:     }
                   15066: 
1.327     albertel 15067: }
                   15068: 
                   15069: 
1.1       albertel 15070: # ------------------------------------------------------------- Read hosts file
                   15071: {
1.838     albertel 15072:     my %hostname;
1.844     albertel 15073:     my %hostdom;
1.845     albertel 15074:     my %libserv;
1.852     albertel 15075:     my $loaded;
1.888     albertel 15076:     my %name_to_host;
1.1074    raeburn  15077:     my %internetdom;
1.1107    raeburn  15078:     my %LC_dns_serv;
1.852     albertel 15079: 
                   15080:     sub parse_hosts_tab {
                   15081: 	my ($file) = @_;
                   15082: 	foreach my $configline (@$file) {
                   15083: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  15084:             chomp($configline);
                   15085: 	    if ($configline =~ /^\^/) {
                   15086:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   15087:                     $LC_dns_serv{$1} = 1;
                   15088:                 }
                   15089:                 next;
                   15090:             }
1.1074    raeburn  15091: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 15092: 	    $name=~s/\s//g;
                   15093: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  15094:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   15095:                     my $curr = $hostname{$id};
                   15096:                     my $skip;
                   15097:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   15098:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   15099:                             $skip = 1;
                   15100:                         } else {
                   15101:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   15102:                         }
                   15103:                     }
                   15104:                     unless ($skip) {
                   15105:                         push(@{$name_to_host{$name}},$id);
                   15106:                     }
                   15107:                 } else {
                   15108:                     push(@{$name_to_host{$name}},$id);
                   15109:                 }
1.852     albertel 15110: 		$hostname{$id}=$name;
                   15111: 		$hostdom{$id}=$domain;
                   15112: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  15113:                 if (defined($protocol)) {
                   15114:                     if ($protocol eq 'https') {
                   15115:                         $protocol{$id} = $protocol;
                   15116:                     } else {
                   15117:                         $protocol{$id} = 'http'; 
                   15118:                     }
1.968     raeburn  15119:                 } else {
1.969     raeburn  15120:                     $protocol{$id} = 'http';
1.968     raeburn  15121:                 }
1.1074    raeburn  15122:                 if (defined($intdom)) {
                   15123:                     $internetdom{$id} = $intdom;
                   15124:                 }
1.852     albertel 15125: 	    }
                   15126: 	}
                   15127:     }
1.864     albertel 15128:     
                   15129:     sub reset_hosts_info {
1.897     albertel 15130: 	&purge_remembered();
1.864     albertel 15131: 	&reset_domain_info();
                   15132: 	&reset_hosts_ip_info();
1.892     albertel 15133: 	undef(%name_to_host);
1.864     albertel 15134: 	undef(%hostname);
                   15135: 	undef(%hostdom);
                   15136: 	undef(%libserv);
                   15137: 	undef($loaded);
                   15138:     }
1.1       albertel 15139: 
1.852     albertel 15140:     sub load_hosts_tab {
1.1172.2.70  raeburn  15141: 	my ($ignore_cache,$nocache) = @_;
                   15142: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  15143: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 15144: 	my @config = <$config>;
                   15145: 	&parse_hosts_tab(\@config);
                   15146: 	close($config);
                   15147: 	$loaded=1;
1.1       albertel 15148:     }
1.852     albertel 15149: 
1.838     albertel 15150:     sub hostname {
1.852     albertel 15151: 	&load_hosts_tab() if (!$loaded);
                   15152: 
1.838     albertel 15153: 	my ($lonid) = @_;
                   15154: 	return $hostname{$lonid};
                   15155:     }
1.845     albertel 15156: 
1.838     albertel 15157:     sub all_hostnames {
1.852     albertel 15158: 	&load_hosts_tab() if (!$loaded);
                   15159: 
1.838     albertel 15160: 	return %hostname;
                   15161:     }
1.845     albertel 15162: 
1.888     albertel 15163:     sub all_names {
1.1172.2.70  raeburn  15164:         my ($ignore_cache,$nocache) = @_;
                   15165: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 15166: 
                   15167: 	return %name_to_host;
                   15168:     }
                   15169: 
1.974     raeburn  15170:     sub all_host_domain {
                   15171:         &load_hosts_tab() if (!$loaded);
                   15172:         return %hostdom;
                   15173:     }
                   15174: 
1.845     albertel 15175:     sub is_library {
1.852     albertel 15176: 	&load_hosts_tab() if (!$loaded);
                   15177: 
1.845     albertel 15178: 	return exists($libserv{$_[0]});
                   15179:     }
                   15180: 
                   15181:     sub all_library {
1.852     albertel 15182: 	&load_hosts_tab() if (!$loaded);
                   15183: 
1.845     albertel 15184: 	return %libserv;
                   15185:     }
                   15186: 
1.1062    droeschl 15187:     sub unique_library {
                   15188: 	#2x reverse removes all hostnames that appear more than once
                   15189:         my %unique = reverse &all_library();
                   15190:         return reverse %unique;
                   15191:     }
                   15192: 
1.841     albertel 15193:     sub get_servers {
1.852     albertel 15194: 	&load_hosts_tab() if (!$loaded);
                   15195: 
1.841     albertel 15196: 	my ($domain,$type) = @_;
                   15197: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   15198: 	                                          : %hostname;
                   15199: 	my %result;
1.842     albertel 15200: 	if (ref($domain) eq 'ARRAY') {
                   15201: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 15202: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 15203: 		    $result{$host} = $hostname;
                   15204: 		}
                   15205: 	    }
                   15206: 	} else {
                   15207: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   15208: 		if ($hostdom{$host} eq $domain) {
                   15209: 		    $result{$host} = $hostname;
                   15210: 		}
1.841     albertel 15211: 	    }
                   15212: 	}
                   15213: 	return %result;
                   15214:     }
1.845     albertel 15215: 
1.1062    droeschl 15216:     sub get_unique_servers {
                   15217:         my %unique = reverse &get_servers(@_);
                   15218: 	return reverse %unique;
                   15219:     }
                   15220: 
1.844     albertel 15221:     sub host_domain {
1.852     albertel 15222: 	&load_hosts_tab() if (!$loaded);
                   15223: 
1.844     albertel 15224: 	my ($lonid) = @_;
                   15225: 	return $hostdom{$lonid};
                   15226:     }
                   15227: 
1.841     albertel 15228:     sub all_domains {
1.852     albertel 15229: 	&load_hosts_tab() if (!$loaded);
                   15230: 
1.841     albertel 15231: 	my %seen;
                   15232: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   15233: 	return @uniq;
                   15234:     }
1.1074    raeburn  15235: 
                   15236:     sub internet_dom {
                   15237:         &load_hosts_tab() if (!$loaded);
                   15238: 
                   15239:         my ($lonid) = @_;
                   15240:         return $internetdom{$lonid};
                   15241:     }
1.1107    raeburn  15242: 
                   15243:     sub is_LC_dns {
                   15244:         &load_hosts_tab() if (!$loaded);
                   15245: 
                   15246:         my ($hostname) = @_;
                   15247:         return exists($LC_dns_serv{$hostname});
                   15248:     }
                   15249: 
1.1       albertel 15250: }
                   15251: 
1.847     albertel 15252: { 
                   15253:     my %iphost;
1.856     albertel 15254:     my %name_to_ip;
                   15255:     my %lonid_to_ip;
1.869     albertel 15256: 
1.847     albertel 15257:     sub get_hosts_from_ip {
                   15258: 	my ($ip) = @_;
                   15259: 	my %iphosts = &get_iphost();
                   15260: 	if (ref($iphosts{$ip})) {
                   15261: 	    return @{$iphosts{$ip}};
                   15262: 	}
                   15263: 	return;
1.839     albertel 15264:     }
1.864     albertel 15265:     
                   15266:     sub reset_hosts_ip_info {
                   15267: 	undef(%iphost);
                   15268: 	undef(%name_to_ip);
                   15269: 	undef(%lonid_to_ip);
                   15270:     }
1.856     albertel 15271: 
                   15272:     sub get_host_ip {
                   15273: 	my ($lonid) = @_;
                   15274: 	if (exists($lonid_to_ip{$lonid})) {
                   15275: 	    return $lonid_to_ip{$lonid};
                   15276: 	}
                   15277: 	my $name=&hostname($lonid);
                   15278:    	my $ip = gethostbyname($name);
                   15279: 	return if (!$ip || length($ip) ne 4);
                   15280: 	$ip=inet_ntoa($ip);
                   15281: 	$name_to_ip{$name}   = $ip;
                   15282: 	$lonid_to_ip{$lonid} = $ip;
                   15283: 	return $ip;
                   15284:     }
1.847     albertel 15285:     
                   15286:     sub get_iphost {
1.1172.2.70  raeburn  15287: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 15288: 
1.869     albertel 15289: 	if (!$ignore_cache) {
                   15290: 	    if (%iphost) {
                   15291: 		return %iphost;
                   15292: 	    }
                   15293: 	    my ($ip_info,$cached)=
                   15294: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   15295: 	    if ($cached) {
                   15296: 		%iphost      = %{$ip_info->[0]};
                   15297: 		%name_to_ip  = %{$ip_info->[1]};
                   15298: 		%lonid_to_ip = %{$ip_info->[2]};
                   15299: 		return %iphost;
                   15300: 	    }
                   15301: 	}
1.894     albertel 15302: 
                   15303: 	# get yesterday's info for fallback
                   15304: 	my %old_name_to_ip;
                   15305: 	my ($ip_info,$cached)=
                   15306: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   15307: 	if ($cached) {
                   15308: 	    %old_name_to_ip = %{$ip_info->[1]};
                   15309: 	}
                   15310: 
1.1172.2.70  raeburn  15311: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 15312: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 15313: 	    my $ip;
                   15314: 	    if (!exists($name_to_ip{$name})) {
                   15315: 		$ip = gethostbyname($name);
                   15316: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 15317: 		    if (defined($old_name_to_ip{$name})) {
                   15318: 			$ip = $old_name_to_ip{$name};
                   15319: 			&logthis("Can't find $name defaulting to old $ip");
                   15320: 		    } else {
                   15321: 			&logthis("Name $name no IP found");
                   15322: 			next;
                   15323: 		    }
                   15324: 		} else {
                   15325: 		    $ip=inet_ntoa($ip);
1.847     albertel 15326: 		}
                   15327: 		$name_to_ip{$name} = $ip;
                   15328: 	    } else {
                   15329: 		$ip = $name_to_ip{$name};
1.653     albertel 15330: 	    }
1.888     albertel 15331: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   15332: 		$lonid_to_ip{$id} = $ip;
                   15333: 	    }
                   15334: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 15335: 	}
1.1172.2.70  raeburn  15336:         unless ($nocache) {
                   15337: 	    &do_cache_new('iphost','iphost',
                   15338: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   15339: 		          48*60*60);
                   15340:         }
1.869     albertel 15341: 
1.847     albertel 15342: 	return %iphost;
1.598     albertel 15343:     }
                   15344: 
1.992     raeburn  15345:     #
                   15346:     #  Given a DNS returns the loncapa host name for that DNS 
                   15347:     # 
                   15348:     sub host_from_dns {
                   15349:         my ($dns) = @_;
                   15350:         my @hosts;
                   15351:         my $ip;
                   15352: 
1.993     raeburn  15353:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  15354:             $ip = $name_to_ip{$dns};
                   15355:         }
                   15356:         if (!$ip) {
                   15357:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   15358:             if (length($ip) == 4) { 
                   15359: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   15360:             }
                   15361:         }
                   15362:         if ($ip) {
                   15363: 	    @hosts = get_hosts_from_ip($ip);
                   15364: 	    return $hosts[0];
                   15365:         }
                   15366:         return undef;
1.986     foxr     15367:     }
1.992     raeburn  15368: 
1.1074    raeburn  15369:     sub get_internet_names {
                   15370:         my ($lonid) = @_;
                   15371:         return if ($lonid eq '');
                   15372:         my ($idnref,$cached)=
                   15373:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   15374:         if ($cached) {
                   15375:             return $idnref;
                   15376:         }
                   15377:         my $ip = &get_host_ip($lonid);
                   15378:         my @hosts = &get_hosts_from_ip($ip);
                   15379:         my %iphost = &get_iphost();
                   15380:         my (@idns,%seen);
                   15381:         foreach my $id (@hosts) {
                   15382:             my $dom = &host_domain($id);
                   15383:             my $prim_id = &domain($dom,'primary');
                   15384:             my $prim_ip = &get_host_ip($prim_id);
                   15385:             next if ($seen{$prim_ip});
                   15386:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   15387:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   15388:                     my $intdom = &internet_dom($id);
                   15389:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   15390:                         push(@idns,$intdom);
                   15391:                     }
                   15392:                 }
                   15393:             }
                   15394:             $seen{$prim_ip} = 1;
                   15395:         }
1.1172.2.23  raeburn  15396:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  15397:     }
                   15398: 
1.986     foxr     15399: }
                   15400: 
1.1079    raeburn  15401: sub all_loncaparevs {
1.1172.2.39  raeburn  15402:     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  15403: }
                   15404: 
1.1172.2.27  raeburn  15405: # ------------------------------------------------------- Read loncaparev table
                   15406: {
                   15407:     sub load_loncaparevs {
                   15408:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  15409:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  15410:                 while (my $configline=<$config>) {
                   15411:                     chomp($configline);
                   15412:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   15413:                     $loncaparevs{$hostid}=$loncaparev;
                   15414:                 }
                   15415:                 close($config);
                   15416:             }
                   15417:         }
                   15418:     }
                   15419: }
                   15420: 
                   15421: # ----------------------------------------------------- Read serverhostID table
                   15422: {
                   15423:     sub load_serverhomeIDs {
                   15424:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  15425:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  15426:                 while (my $configline=<$config>) {
                   15427:                     chomp($configline);
                   15428:                     my ($name,$id)=split(/:/,$configline);
                   15429:                     $serverhomeIDs{$name}=$id;
                   15430:                 }
                   15431:                 close($config);
                   15432:             }
                   15433:         }
                   15434:     }
                   15435: }
                   15436: 
                   15437: 
1.862     albertel 15438: BEGIN {
                   15439: 
                   15440: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   15441:     unless ($readit) {
                   15442: {
                   15443:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   15444:     %perlvar = (%perlvar,%{$configvars});
                   15445: }
                   15446: 
                   15447: 
1.1       albertel 15448: # ------------------------------------------------------ Read spare server file
                   15449: {
1.1172.2.96  raeburn  15450:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 15451: 
                   15452:     while (my $configline=<$config>) {
                   15453:        chomp($configline);
1.284     matthew  15454:        if ($configline) {
1.784     albertel 15455: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 15456: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 15457: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 15458:        }
                   15459:     }
1.448     albertel 15460:     close($config);
1.1       albertel 15461: }
1.11      www      15462: # ------------------------------------------------------------ Read permissions
                   15463: {
1.1172.2.96  raeburn  15464:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      15465: 
                   15466:     while (my $configline=<$config>) {
1.448     albertel 15467: 	chomp($configline);
                   15468: 	if ($configline) {
                   15469: 	    my ($role,$perm)=split(/ /,$configline);
                   15470: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   15471: 	}
1.11      www      15472:     }
1.448     albertel 15473:     close($config);
1.11      www      15474: }
                   15475: 
                   15476: # -------------------------------------------- Read plain texts for permissions
                   15477: {
1.1172.2.96  raeburn  15478:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      15479: 
                   15480:     while (my $configline=<$config>) {
1.448     albertel 15481: 	chomp($configline);
                   15482: 	if ($configline) {
1.742     raeburn  15483: 	    my ($short,@plain)=split(/:/,$configline);
                   15484:             %{$prp{$short}} = ();
                   15485: 	    if (@plain > 0) {
                   15486:                 $prp{$short}{'std'} = $plain[0];
                   15487:                 for (my $i=1; $i<@plain; $i++) {
                   15488:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   15489:                 }
                   15490:             }
1.448     albertel 15491: 	}
1.135     www      15492:     }
1.448     albertel 15493:     close($config);
1.135     www      15494: }
                   15495: 
                   15496: # ---------------------------------------------------------- Read package table
                   15497: {
1.1172.2.96  raeburn  15498:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      15499: 
                   15500:     while (my $configline=<$config>) {
1.483     albertel 15501: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 15502: 	chomp($configline);
                   15503: 	my ($short,$plain)=split(/:/,$configline);
                   15504: 	my ($pack,$name)=split(/\&/,$short);
                   15505: 	if ($plain ne '') {
                   15506: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   15507: 	    $packagetab{$short}=$plain; 
                   15508: 	}
1.11      www      15509:     }
1.448     albertel 15510:     close($config);
1.329     matthew  15511: }
                   15512: 
1.1172.2.27  raeburn  15513: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  15514: 
1.1172.2.27  raeburn  15515: &load_loncaparevs();
                   15516: 
                   15517: # ------------------------------------------------------- Read serverhostID table
                   15518: 
                   15519: &load_serverhomeIDs();
1.1074    raeburn  15520: 
1.1172.2.27  raeburn  15521: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  15522: {
                   15523:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   15524:     if (-e $file) {
                   15525:         my $parser = HTML::LCParser->new($file);
                   15526:         while (my $token = $parser->get_token()) {
                   15527:             if ($token->[0] eq 'S') {
                   15528:                 my $item = $token->[1];
                   15529:                 my $name = $token->[2]{'name'};
                   15530:                 my $value = $token->[2]{'value'};
                   15531:                 if ($item ne '' && $name ne '' && $value ne '') {
                   15532:                     my $release = $parser->get_text();
                   15533:                     $release =~ s/(^\s*|\s*$ )//gx;
                   15534:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   15535:                 }
                   15536:             }
                   15537:         }
                   15538:     }
1.1073    raeburn  15539: }
                   15540: 
1.1138    raeburn  15541: # ---------------------------------------------------------- Read managers table
                   15542: {
                   15543:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  15544:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  15545:             while (my $configline=<$config>) {
                   15546:                 chomp($configline);
                   15547:                 next if ($configline =~ /^\#/);
                   15548:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   15549:                     $managerstab{$configline} = 1;
                   15550:                 }
                   15551:             }
                   15552:             close($config);
                   15553:         }
                   15554:     }
                   15555: }
                   15556: 
1.329     matthew  15557: # ------------- set up temporary directory
                   15558: {
1.1117    foxr     15559:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  15560: 
1.11      www      15561: }
                   15562: 
1.1172.2.104  raeburn  15563: # ------------- set default texengine (domain default overrides this)
                   15564: {
                   15565:     $deftex = LONCAPA::texengine();
                   15566: }
                   15567: 
1.1172.2.114  raeburn  15568: # ------------- set default minimum length for passwords for internal auth users
                   15569: {
                   15570:     $passwdmin = LONCAPA::passwd_min();
                   15571: }
                   15572: 
1.794     albertel 15573: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   15574: 				'compress_threshold'=> 20_000,
                   15575:  			        });
1.185     www      15576: 
1.281     www      15577: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      15578: $dumpcount=0;
1.958     www      15579: $locknum=0;
1.22      www      15580: 
1.163     harris41 15581: &logtouch();
1.672     albertel 15582: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      15583: $readit=1;
1.564     albertel 15584:     {
                   15585: 	use integer;
                   15586: 	my $test=(2**32)+1;
1.568     albertel 15587: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 15588: 	&logthis(" Detected 64bit platform ($_64bit)");
                   15589:     }
1.195     www      15590: }
1.1       albertel 15591: }
1.179     www      15592: 
1.1       albertel 15593: 1;
1.191     harris41 15594: __END__
                   15595: 
1.243     albertel 15596: =pod
                   15597: 
1.191     harris41 15598: =head1 NAME
                   15599: 
1.243     albertel 15600: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 15601: 
                   15602: =head1 SYNOPSIS
                   15603: 
1.243     albertel 15604: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 15605: 
                   15606:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   15607: 
1.243     albertel 15608: Common parameters:
                   15609: 
                   15610: =over 4
                   15611: 
                   15612: =item *
                   15613: 
                   15614: $uname : an internal username (if $cname expecting a course Id specifically)
                   15615: 
                   15616: =item *
                   15617: 
                   15618: $udom : a domain (if $cdom expecting a course's domain specifically)
                   15619: 
                   15620: =item *
                   15621: 
                   15622: $symb : a resource instance identifier
                   15623: 
                   15624: =item *
                   15625: 
                   15626: $namespace : the name of a .db file that contains the data needed or
                   15627: being set.
                   15628: 
                   15629: =back
                   15630: 
1.394     bowersj2 15631: =head1 OVERVIEW
1.191     harris41 15632: 
1.394     bowersj2 15633: lonnet provides subroutines which interact with the
                   15634: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   15635: about classes, users, and resources.
1.243     albertel 15636: 
                   15637: For many of these objects you can also use this to store data about
                   15638: them or modify them in various ways.
1.191     harris41 15639: 
1.394     bowersj2 15640: =head2 Symbs
1.191     harris41 15641: 
1.394     bowersj2 15642: To identify a specific instance of a resource, LON-CAPA uses symbols
                   15643: or "symbs"X<symb>. These identifiers are built from the URL of the
                   15644: map, the resource number of the resource in the map, and the URL of
                   15645: the resource itself. The latter is somewhat redundant, but might help
                   15646: if maps change.
                   15647: 
                   15648: An example is
                   15649: 
                   15650:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   15651: 
                   15652: The respective map entry is
                   15653: 
                   15654:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   15655:   title="Problem 2">
                   15656:  </resource>
                   15657: 
                   15658: Symbs are used by the random number generator, as well as to store and
                   15659: restore data specific to a certain instance of for example a problem.
                   15660: 
                   15661: =head2 Storing And Retrieving Data
                   15662: 
                   15663: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   15664: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   15665: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   15666: is is the non-critical message twin of cstore. These functions are for
                   15667: handlers to store a perl hash to a user's permanent data space in an
                   15668: easy manner, and to retrieve it again on another call. It is expected
                   15669: that a handler would use this once at the beginning to retrieve data,
                   15670: and then again once at the end to send only the new data back.
                   15671: 
                   15672: The data is stored in the user's data directory on the user's
                   15673: homeserver under the ID of the course.
                   15674: 
                   15675: The hash that is returned by restore will have all of the previous
                   15676: value for all of the elements of the hash.
                   15677: 
                   15678: Example:
                   15679: 
                   15680:  #creating a hash
                   15681:  my %hash;
                   15682:  $hash{'foo'}='bar';
                   15683: 
                   15684:  #storing it
                   15685:  &Apache::lonnet::cstore(\%hash);
                   15686: 
                   15687:  #changing a value
                   15688:  $hash{'foo'}='notbar';
                   15689: 
                   15690:  #adding a new value
                   15691:  $hash{'bar'}='foo';
                   15692:  &Apache::lonnet::cstore(\%hash);
                   15693: 
                   15694:  #retrieving the hash
                   15695:  my %history=&Apache::lonnet::restore();
                   15696: 
                   15697:  #print the hash
                   15698:  foreach my $key (sort(keys(%history))) {
                   15699:    print("\%history{$key} = $history{$key}");
                   15700:  }
                   15701: 
                   15702: Will print out:
1.191     harris41 15703: 
1.394     bowersj2 15704:  %history{1:foo} = bar
                   15705:  %history{1:keys} = foo:timestamp
                   15706:  %history{1:timestamp} = 990455579
                   15707:  %history{2:bar} = foo
                   15708:  %history{2:foo} = notbar
                   15709:  %history{2:keys} = foo:bar:timestamp
                   15710:  %history{2:timestamp} = 990455580
                   15711:  %history{bar} = foo
                   15712:  %history{foo} = notbar
                   15713:  %history{timestamp} = 990455580
                   15714:  %history{version} = 2
                   15715: 
                   15716: Note that the special hash entries C<keys>, C<version> and
                   15717: C<timestamp> were added to the hash. C<version> will be equal to the
                   15718: total number of versions of the data that have been stored. The
                   15719: C<timestamp> attribute will be the UNIX time the hash was
                   15720: stored. C<keys> is available in every historical section to list which
                   15721: keys were added or changed at a specific historical revision of a
                   15722: hash.
                   15723: 
                   15724: B<Warning>: do not store the hash that restore returns directly. This
                   15725: will cause a mess since it will restore the historical keys as if the
                   15726: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 15727: 
1.394     bowersj2 15728: Calling convention:
1.191     harris41 15729: 
1.1172.2.27  raeburn  15730:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  15731:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 15732: 
1.394     bowersj2 15733: For more detailed information, see lonnet specific documentation.
1.191     harris41 15734: 
1.394     bowersj2 15735: =head1 RETURN MESSAGES
1.191     harris41 15736: 
1.394     bowersj2 15737: =over 4
1.191     harris41 15738: 
1.394     bowersj2 15739: =item * B<con_lost>: unable to contact remote host
1.191     harris41 15740: 
1.394     bowersj2 15741: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   15742: when the connection is brought back up
1.191     harris41 15743: 
1.394     bowersj2 15744: =item * B<con_failed>: unable to contact remote host and unable to save message
                   15745: for later delivery
1.191     harris41 15746: 
1.967     bisitz   15747: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 15748: 
1.394     bowersj2 15749: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 15750: that was requested
1.191     harris41 15751: 
1.243     albertel 15752: =back
1.191     harris41 15753: 
1.243     albertel 15754: =head1 PUBLIC SUBROUTINES
1.191     harris41 15755: 
1.243     albertel 15756: =head2 Session Environment Functions
1.191     harris41 15757: 
1.243     albertel 15758: =over 4
1.191     harris41 15759: 
1.394     bowersj2 15760: =item * 
                   15761: X<appenv()>
1.949     raeburn  15762: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 15763: the user envirnoment file, and will be restored for each access this
1.620     albertel 15764: user makes during this session, also modifies the %env for the current
1.949     raeburn  15765: process. Optional rolesarrayref - if defined contains a reference to an array
                   15766: of roles which are exempt from the restriction on modifying user.role entries 
                   15767: in the user's environment.db and in %env.    
1.191     harris41 15768: 
                   15769: =item *
1.394     bowersj2 15770: X<delenv()>
1.987     raeburn  15771: B<delenv($delthis,$regexp)>: removes all items from the session
                   15772: environment file that begin with $delthis. If the 
                   15773: optional second arg - $regexp - is true, $delthis is treated as a 
                   15774: regular expression, otherwise \Q$delthis\E is used. 
                   15775: The values are also deleted from the current processes %env.
1.191     harris41 15776: 
1.795     albertel 15777: =item * get_env_multiple($name) 
                   15778: 
                   15779: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   15780: values may be defined and end up as an array ref.
                   15781: 
                   15782: returns an array of values
                   15783: 
1.243     albertel 15784: =back
                   15785: 
                   15786: =head2 User Information
1.191     harris41 15787: 
1.243     albertel 15788: =over 4
1.191     harris41 15789: 
                   15790: =item *
1.394     bowersj2 15791: X<queryauthenticate()>
                   15792: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 15793: authentication scheme
                   15794: 
                   15795: =item *
1.394     bowersj2 15796: X<authenticate()>
1.1073    raeburn  15797: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 15798: authenticate user from domain's lib servers (first use the current
                   15799: one). C<$upass> should be the users password.
1.1073    raeburn  15800: $checkdefauth is optional (value is 1 if a check should be made to
                   15801:    authenticate user using default authentication method, and allow
                   15802:    account creation if username does not have account in the domain).
                   15803: $clientcancheckhost is optional (value is 1 if checking whether the
                   15804:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 15805: 
                   15806: =item *
1.394     bowersj2 15807: X<homeserver()>
                   15808: B<homeserver($uname,$udom)>: find the server which has
                   15809: the user's directory and files (there must be only one), this caches
                   15810: the answer, and also caches if there is a borken connection.
1.191     harris41 15811: 
                   15812: =item *
1.394     bowersj2 15813: X<idget()>
                   15814: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   15815: (IDs are a unique resource in a domain, there must be only 1 ID per
                   15816: username, and only 1 username per ID in a specific domain) (returns
                   15817: hash: id=>name,id=>name)
1.191     harris41 15818: 
                   15819: =item *
1.394     bowersj2 15820: X<idrget()>
                   15821: B<idrget($udom,@unames)>: find the IDs behind a list of
                   15822: usernames (returns hash: name=>id,name=>id)
1.191     harris41 15823: 
                   15824: =item *
1.394     bowersj2 15825: X<idput()>
                   15826: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 15827: 
                   15828: =item *
1.394     bowersj2 15829: X<rolesinit()>
1.1169    droeschl 15830: B<rolesinit($udom,$username)>: get user privileges.
                   15831: returns user role, first access and timer interval hashes
1.243     albertel 15832: 
                   15833: =item *
1.1171    droeschl 15834: X<privileged()>
                   15835: B<privileged($username,$domain)>: returns a true if user has a
                   15836: privileged and active role (i.e. su or dc), false otherwise.
                   15837: 
                   15838: =item *
1.551     albertel 15839: X<getsection()>
                   15840: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 15841: course $cname, return section name/number or '' for "not in course"
                   15842: and '-1' for "no section"
                   15843: 
                   15844: =item *
1.394     bowersj2 15845: X<userenvironment()>
                   15846: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 15847: passed in @what from the requested user's environment, returns a hash
                   15848: 
1.858     raeburn  15849: =item * 
                   15850: X<userlog_query()>
1.859     albertel 15851: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   15852: activity.log file. %filters defines filters applied when parsing the
                   15853: log file. These can be start or end timestamps, or the type of action
                   15854: - log to look for Login or Logout events, check for Checkin or
                   15855: Checkout, role for role selection. The response is in the form
                   15856: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   15857: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  15858: 
1.243     albertel 15859: =back
                   15860: 
                   15861: =head2 User Roles
                   15862: 
                   15863: =over 4
                   15864: 
                   15865: =item *
                   15866: 
1.1172.2.65  raeburn  15867: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   15868: returns codes for allowed actions.
                   15869: 
                   15870: The first argument is required, all others are optional.
                   15871: 
                   15872: $priv is the privilege being checked.
                   15873: $uri contains additional information about what is being checked for access (e.g.,
                   15874: URL, course ID etc.).
                   15875: $symb is the unique resource instance identifier in a course; if needed,
                   15876: but not provided, it will be retrieved via a call to &symbread().
                   15877: $role is the role for which a priv is being checked (only used if priv is evb).
                   15878: $clientip is the user's IP address (only used when checking for access to portfolio
                   15879: files).
                   15880: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   15881: prevents recursive calls to &allowed.
                   15882: 
1.243     albertel 15883:  F: full access
                   15884:  U,I,K: authentication modes (cxx only)
                   15885:  '': forbidden
                   15886:  1: user needs to choose course
                   15887:  2: browse allowed
1.766     albertel 15888:  A: passphrase authentication needed
1.1172.2.65  raeburn  15889:  B: access temporarily blocked because of a blocking event in a course.
1.1172.2.146.  .1(raebu 15890:22):  D: access blocked because access is required via session initiated via deep-link
1.243     albertel 15891: 
                   15892: =item *
                   15893: 
1.1172.2.13  raeburn  15894: constructaccess($url,$setpriv) : check for access to construction space URL
                   15895: 
                   15896: See if the owner domain and name in the URL match those in the
                   15897: expected environment.  If so, return three element list
                   15898: ($ownername,$ownerdomain,$ownerhome).
                   15899: 
                   15900: Otherwise return the null string.
                   15901: 
                   15902: If second argument 'setpriv' is true, it assigns the privileges,
                   15903: and returns the same three element list, unless the owner has
                   15904: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   15905: in which case the null string is returned.
                   15906: 
                   15907: =item *
                   15908: 
1.1172.2.84  raeburn  15909: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   15910: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   15911: for system, domain, and course level. $uname and $udom are optional (current
                   15912: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 15913: 
                   15914: =item *
                   15915: 
1.988     raeburn  15916: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   15917: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  15918: $type is Course (default) or Community.
1.988     raeburn  15919: If $forcedefault evaluates to true, text returned will be default 
                   15920: text for $type. Otherwise, if this is a course, the text returned 
                   15921: will be a custom name for the role (if defined in the course's 
                   15922: environment).  If no custom name is defined the default is returned.
                   15923:    
1.832     raeburn  15924: =item *
                   15925: 
1.1172.2.23  raeburn  15926: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  15927: All arguments are optional. Returns a hash of a roles, either for
                   15928: co-author/assistant author roles for a user's Construction Space
1.906     albertel 15929: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  15930: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   15931: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   15932: For each key, value is set to colon-separated start and end times for
                   15933: the role.  If no username and domain are specified, will default to
1.934     raeburn  15934: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  15935: of role statuses (active, future or previous), roles 
                   15936: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   15937: to restrict the list of roles reported. If no array ref is 
                   15938: provided for types, will default to return only active roles.
1.834     albertel 15939: 
1.1172.2.13  raeburn  15940: =item *
                   15941: 
                   15942: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   15943: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   15944: 
                   15945: Additional optional arguments are: $type (if role checking is to be restricted
                   15946: to certain user status types -- previous (expired roles), active (currently
                   15947: available roles) or future (roles available in the future), and
                   15948: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  15949: have active Domain Coordinator role in course's domain or in additional
                   15950: domains (specified in 'Domains to check for privileged users' in course
                   15951: environment -- set via:  Course Settings -> Classlists and staff listing).
                   15952: 
                   15953: =item *
                   15954: 
                   15955: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   15956: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   15957: $possdomains and $possroles are optional array refs -- to domains to check and
                   15958: roles to check.  If $possdomains is not specified, a dump will be done of the
                   15959: users' roles.db to check for a dc or su role in any domain. This can be
                   15960: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   15961: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   15962: this then allows &privileged_by_domain() to be used, which caches the identity
                   15963: of privileged users, eliminating the need for repeated calls to &dump().
                   15964: 
                   15965: =item *
                   15966: 
                   15967: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15968: where the outer hash keys are domains specified in the $possdomains array ref,
                   15969: next inner hash keys are privileged roles specified in the $roles array ref,
                   15970: and the innermost hash contains key = value pairs for username:domain = end:start
                   15971: for active or future "privileged" users with that role in that domain. To avoid
                   15972: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15973: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  15974: 
1.243     albertel 15975: =back
                   15976: 
                   15977: =head2 User Modification
                   15978: 
                   15979: =over 4
                   15980: 
                   15981: =item *
                   15982: 
1.957     raeburn  15983: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15984: user for the level given by URL.  Optional start and end dates (leave empty
                   15985: string or zero for "no date")
1.191     harris41 15986: 
                   15987: =item *
                   15988: 
1.243     albertel 15989: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15990: change a users, password, possible return values are: ok,
                   15991: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15992: refused
1.191     harris41 15993: 
                   15994: =item *
                   15995: 
1.243     albertel 15996: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15997: 
                   15998: =item *
                   15999: 
1.1058    raeburn  16000: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   16001:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   16002: 
                   16003: will update user information (firstname,middlename,lastname,generation,
                   16004: permanentemail), and if forceid is true, student/employee ID also.
                   16005: A user's institutional affiliation(s) can also be updated.
                   16006: User information fields will not be overwritten with empty entries 
                   16007: unless the field is included in the $candelete array reference.
                   16008: This array is included when a single user is modified via "Manage Users",
                   16009: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 16010: 
                   16011: =item *
                   16012: 
1.286     matthew  16013: modifystudent
                   16014: 
1.957     raeburn  16015: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  16016: The course id is resolved based on the current user's environment.  
                   16017: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  16018: associated with a course.
                   16019: 
1.297     matthew  16020: This call is essentially a wrapper for lonnet::modifyuser and
                   16021: lonnet::modify_student_enrollment
1.286     matthew  16022: 
                   16023: Inputs: 
                   16024: 
                   16025: =over 4
                   16026: 
1.957     raeburn  16027: =item B<$udom> Student's loncapa domain
1.286     matthew  16028: 
1.957     raeburn  16029: =item B<$uname> Student's loncapa login name
1.286     matthew  16030: 
1.964     bisitz   16031: =item B<$uid> Student/Employee ID
1.286     matthew  16032: 
1.957     raeburn  16033: =item B<$umode> Student's authentication mode
1.286     matthew  16034: 
1.957     raeburn  16035: =item B<$upass> Student's password
1.286     matthew  16036: 
1.957     raeburn  16037: =item B<$first> Student's first name
1.286     matthew  16038: 
1.957     raeburn  16039: =item B<$middle> Student's middle name
1.286     matthew  16040: 
1.957     raeburn  16041: =item B<$last> Student's last name
1.286     matthew  16042: 
1.957     raeburn  16043: =item B<$gene> Student's generation
1.286     matthew  16044: 
1.957     raeburn  16045: =item B<$usec> Student's section in course
1.286     matthew  16046: 
                   16047: =item B<$end> Unix time of the roles expiration
                   16048: 
                   16049: =item B<$start> Unix time of the roles start date
                   16050: 
                   16051: =item B<$forceid> If defined, allow $uid to be changed
                   16052: 
                   16053: =item B<$desiredhome> server to use as home server for student
                   16054: 
1.957     raeburn  16055: =item B<$email> Student's permanent e-mail address
                   16056: 
                   16057: =item B<$type> Type of enrollment (auto or manual)
                   16058: 
1.963     raeburn  16059: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   16060: 
                   16061: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  16062: 
1.963     raeburn  16063: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  16064: 
1.963     raeburn  16065: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  16066: 
1.1172.2.19  raeburn  16067: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   16068: 
                   16069: =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  16070: 
1.286     matthew  16071: =back
1.297     matthew  16072: 
                   16073: =item *
                   16074: 
                   16075: modify_student_enrollment
                   16076: 
1.1172.2.31  raeburn  16077: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  16078: 'role.request.course' must be defined for this function to proceed.
                   16079: 
                   16080: Inputs:
                   16081: 
                   16082: =over 4
                   16083: 
1.1172.2.31  raeburn  16084: =item $udom, student's domain
1.297     matthew  16085: 
1.1172.2.31  raeburn  16086: =item $uname, student's name
1.297     matthew  16087: 
1.1172.2.31  raeburn  16088: =item $uid, student's user id
1.297     matthew  16089: 
1.1172.2.31  raeburn  16090: =item $first, student's first name
1.297     matthew  16091: 
                   16092: =item $middle
                   16093: 
                   16094: =item $last
                   16095: 
                   16096: =item $gene
                   16097: 
                   16098: =item $usec
                   16099: 
                   16100: =item $end
                   16101: 
                   16102: =item $start
                   16103: 
1.957     raeburn  16104: =item $type
                   16105: 
                   16106: =item $locktype
                   16107: 
                   16108: =item $cid
                   16109: 
                   16110: =item $selfenroll
                   16111: 
                   16112: =item $context
                   16113: 
1.1172.2.19  raeburn  16114: =item $credits, number of credits student will earn from this class
                   16115: 
1.1172.2.76  raeburn  16116: =item $instsec, institutional course section code for student
                   16117: 
1.297     matthew  16118: =back
                   16119: 
1.191     harris41 16120: 
                   16121: =item *
                   16122: 
1.243     albertel 16123: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   16124: custom role; give a custom role to a user for the level given by URL.  Specify
                   16125: name and domain of role author, and role name
1.191     harris41 16126: 
                   16127: =item *
                   16128: 
1.243     albertel 16129: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 16130: 
                   16131: =item *
                   16132: 
1.243     albertel 16133: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   16134: 
                   16135: =back
                   16136: 
                   16137: =head2 Course Infomation
                   16138: 
                   16139: =over 4
1.191     harris41 16140: 
                   16141: =item *
                   16142: 
1.1118    foxr     16143: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 16144: specified course id, including all environment settings for the
                   16145: course, the description of the course will be in the hash under the
                   16146: key 'description'
1.191     harris41 16147: 
1.1118    foxr     16148: $options is an optional parameter that if supplied is a hash reference that controls
                   16149: what how this function works.  It has the following key/values:
                   16150: 
                   16151: =over 4
                   16152: 
                   16153: =item freshen_cache
                   16154: 
                   16155: If defined, and the environment cache for the course is valid, it is 
                   16156: returned in the returned hash.
                   16157: 
                   16158: =item one_time
                   16159: 
                   16160: If defined, the last cache time is set to _now_
                   16161: 
                   16162: =item user
                   16163: 
                   16164: If defined, the supplied username is used instead of the current user.
                   16165: 
                   16166: 
                   16167: =back
                   16168: 
1.191     harris41 16169: =item *
                   16170: 
1.624     albertel 16171: resdata($name,$domain,$type,@which) : request for current parameter
                   16172: setting for a specific $type, where $type is either 'course' or 'user',
                   16173: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  16174: answers for 10 minutes.
1.243     albertel 16175: 
1.877     foxr     16176: =item *
                   16177: 
                   16178: get_courseresdata($courseid, $domain) : dump the entire course resource
                   16179: data base, returning a hash that is keyed by the resource name and has
                   16180: values that are the resource value.  I believe that the timestamps and
                   16181: versions are also returned.
                   16182: 
1.243     albertel 16183: =back
                   16184: 
                   16185: =head2 Course Modification
                   16186: 
                   16187: =over 4
1.191     harris41 16188: 
                   16189: =item *
                   16190: 
1.243     albertel 16191: writecoursepref($courseid,%prefs) : write preferences (environment
                   16192: database) for a course
1.191     harris41 16193: 
                   16194: =item *
                   16195: 
1.1011    raeburn  16196: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   16197: 
                   16198: =item *
                   16199: 
1.1038    raeburn  16200: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 16201: 
1.1167    droeschl 16202: =item *
                   16203: 
                   16204: is_course($courseid), is_course($cdom, $cnum)
                   16205: 
                   16206: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   16207: two component version $cdom, $cnum. It checks if the specified course exists.
                   16208: 
                   16209: Returns:
                   16210:     undef if the course doesn't exist, otherwise
                   16211:     in scalar context the combined courseid.
                   16212:     in list context the two components of the course identifier, domain and 
                   16213:     courseid.    
                   16214: 
1.243     albertel 16215: =back
                   16216: 
1.1172.2.109  raeburn  16217: =head2 Bubblesheet Configuration
                   16218: 
                   16219: =over 4
                   16220: 
                   16221: =item *
                   16222: 
                   16223: get_scantron_config($which)
                   16224: 
                   16225: $which - the name of the configuration to parse from the file.
                   16226: 
                   16227: Parses and returns the bubblesheet configuration line selected as a
                   16228: hash of configuration file fields.
                   16229: 
                   16230: 
                   16231: Returns:
                   16232:     If the named configuration is not in the file, an empty
                   16233:     hash is returned.
                   16234: 
                   16235:     a hash with the fields
                   16236:       name         - internal name for the this configuration setup
                   16237:       description  - text to display to operator that describes this config
                   16238:       CODElocation - if 0 or the string 'none'
                   16239:                           - no CODE exists for this config
                   16240:                      if -1 || the string 'letter'
                   16241:                           - a CODE exists for this config and is
                   16242:                             a string of letters
                   16243:                      Unsupported value (but planned for future support)
                   16244:                           if a positive integer
                   16245:                                - The CODE exists as the first n items from
                   16246:                                  the question section of the form
                   16247:                           if the string 'number'
                   16248:                                - The CODE exists for this config and is
                   16249:                                  a string of numbers
                   16250:       CODEstart   - (only matter if a CODE exists) column in the line where
                   16251:                      the CODE starts
                   16252:       CODElength  - length of the CODE
                   16253:       IDstart     - column where the student/employee ID starts
                   16254:       IDlength    - length of the student/employee ID info
                   16255:       Qstart      - column where the information from the bubbled
                   16256:                     'questions' start
                   16257:       Qlength     - number of columns comprising a single bubble line from
                   16258:                     the sheet. (usually either 1 or 10)
                   16259:       Qon         - either a single character representing the character used
                   16260:                     to signal a bubble was chosen in the positional setup, or
                   16261:                     the string 'letter' if the letter of the chosen bubble is
                   16262:                     in the final, or 'number' if a number representing the
                   16263:                     chosen bubble is in the file (1->A 0->J)
                   16264:       Qoff        - the character used to represent that a bubble was
                   16265:                     left blank
                   16266:       PaperID     - if the scanning process generates a unique number for each
                   16267:                     sheet scanned the column that this ID number starts in
                   16268:       PaperIDlength - number of columns that comprise the unique ID number
                   16269:                       for the sheet of paper
                   16270:       FirstName   - column that the first name starts in
                   16271:       FirstNameLength - number of columns that the first name spans
                   16272:       LastName    - column that the last name starts in
                   16273:       LastNameLength - number of columns that the last name spans
                   16274:       BubblesPerRow - number of bubbles available in each row used to
                   16275:                       bubble an answer. (If not specified, 10 assumed).
                   16276: 
                   16277: 
                   16278: =item *
                   16279: 
                   16280: get_scantronformat_file($cdom)
                   16281: 
                   16282: $cdom - the course's domain (optional); if not supplied, uses
                   16283: domain for current $env{'request.course.id'}.
                   16284: 
                   16285: Returns an array containing lines from the scantron format file for
                   16286: the domain of the course.
                   16287: 
                   16288: If a url for a custom.tab file is listed in domain's configuration.db,
                   16289: lines are from this file.
                   16290: 
                   16291: Otherwise, if a default.tab has been published in RES space by the
                   16292: domainconfig user, lines are from this file.
                   16293: 
                   16294: Otherwise, fall back to getting lines from the legacy file on the
                   16295: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   16296: 
                   16297: =back
                   16298: 
1.243     albertel 16299: =head2 Resource Subroutines
                   16300: 
                   16301: =over 4
1.191     harris41 16302: 
                   16303: =item *
                   16304: 
1.243     albertel 16305: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 16306: 
                   16307: =item *
                   16308: 
1.243     albertel 16309: repcopy($filename) : subscribes to the requested file, and attempts to
                   16310: replicate from the owning library server, Might return
1.607     raeburn  16311: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   16312: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 16313: resource. Expects the local filesystem pathname
                   16314: (/home/httpd/html/res/....)
                   16315: 
                   16316: =back
                   16317: 
                   16318: =head2 Resource Information
                   16319: 
                   16320: =over 4
1.191     harris41 16321: 
                   16322: =item *
                   16323: 
1.1172.2.28  raeburn  16324: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   16325: and returns the value of a variety of different possible values,
                   16326: $varname should be a request string, and the other parameters can be
                   16327: used to specify who and what one is asking about. Ordinarily, $cid 
                   16328: does not need to be specified, as it is retrived from 
                   16329: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   16330: within lonuserstate::loadmap() when initializing a course, before
                   16331: $env{'request.course.id'} has been set, so it needs to be provided
                   16332: in that one case.
1.243     albertel 16333: 
                   16334: Possible values for $varname are environment.lastname (or other item
                   16335: from the envirnment hash), user.name (or someother aspect about the
                   16336: user), resource.0.maxtries (or some other part and parameter of a
                   16337: resource)
1.204     albertel 16338: 
                   16339: =item *
                   16340: 
1.243     albertel 16341: directcondval($number) : get current value of a condition; reads from a state
                   16342: string
1.204     albertel 16343: 
                   16344: =item *
                   16345: 
1.243     albertel 16346: condval($condidx) : value of condition index based on state
1.204     albertel 16347: 
                   16348: =item *
                   16349: 
1.1172.2.146.  .13(raeb 16350:-23): metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 16351: resource's metadata, $what should be either a specific key, or either
                   16352: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1172.2.146.  .13(raeb 16353:-23): packages that this resource currently uses, the last 3 arguments are
                   16354:-23): only used internally for recursive metadata.
                   16355:-23): 
                   16356:-23): the toolsymb is only used where the uri is for an external tool (for which
                   16357:-23): the uri as well as the symb are guaranteed to be unique).
1.243     albertel 16358: 
                   16359: this function automatically caches all requests
1.191     harris41 16360: 
                   16361: =item *
                   16362: 
1.243     albertel 16363: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   16364: network of library servers; returns file handle of where SQL and regex results
                   16365: will be stored for query
1.191     harris41 16366: 
                   16367: =item *
                   16368: 
1.1172.2.66  raeburn  16369: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   16370: return symbolic list entry (all arguments optional).
                   16371: 
                   16372: Args: filename is the filename (including path) for the file for which a symb
                   16373: is required; donotrecurse, if true will prevent calls to allowed() being made
                   16374: to check access status if more than one resource was found in the bighash
                   16375: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   16376: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   16377: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   16378: cause possible symbs to be checked to determine if they are subject to content
                   16379: blocking, if so they will not be included as possible symbs; possibles is a
                   16380: ref to a hash, which, as a side effect, will be populated with all possible
                   16381: symbs (content blocking not tested).
                   16382: 
1.243     albertel 16383: returns the data handle
1.191     harris41 16384: 
                   16385: =item *
                   16386: 
1.1172.2.17  raeburn  16387: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  16388: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 16389: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  16390: on failure, user must be in a course, as it assumes the existence of
                   16391: the course initial hash, and uses $env('request.course.id'}.  The third
                   16392: arg is an optional reference to a scalar.  If this arg is passed in the
                   16393: call to symbverify, it will be set to 1 if the symb has been set to be 
                   16394: encrypted; otherwise it will be null.
1.243     albertel 16395: 
1.191     harris41 16396: =item *
                   16397: 
1.243     albertel 16398: symbclean($symb) : removes versions numbers from a symb, returns the
                   16399: cleaned symb
1.191     harris41 16400: 
                   16401: =item *
                   16402: 
1.243     albertel 16403: is_on_map($uri) : checks if the $uri is somewhere on the current
                   16404: course map, user must be in a course for it to work.
1.191     harris41 16405: 
                   16406: =item *
                   16407: 
1.243     albertel 16408: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 16409: 
                   16410: =item *
                   16411: 
1.243     albertel 16412: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   16413: a random seed, all arguments are optional, if they aren't sent it uses the
                   16414: environment to derive them. Note: if symb isn't sent and it can't get one
                   16415: from &symbread it will use the current time as its return value
1.191     harris41 16416: 
                   16417: =item *
                   16418: 
1.243     albertel 16419: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   16420: unfakeable, receipt
1.191     harris41 16421: 
                   16422: =item *
                   16423: 
1.620     albertel 16424: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 16425: 
                   16426: =item *
                   16427: 
1.243     albertel 16428: countacc($url) : count the number of accesses to a given URL
1.191     harris41 16429: 
                   16430: =item *
                   16431: 
1.243     albertel 16432: 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 16433: 
                   16434: =item *
                   16435: 
1.243     albertel 16436: 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 16437: 
                   16438: =item *
                   16439: 
1.243     albertel 16440: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 16441: 
                   16442: =item *
                   16443: 
1.243     albertel 16444: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   16445: forcing spreadsheet to reevaluate the resource scores next time.
                   16446: 
1.1172.2.13  raeburn  16447: =item *
                   16448: 
                   16449: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   16450: when viewing in course context.
                   16451: 
                   16452:  input: six args -- filename (decluttered), course number, course domain,
                   16453:                     url, symb (if registered) and group (if this is a
                   16454:                     group item -- e.g., bulletin board, group page etc.).
                   16455: 
                   16456:  output: array of five scalars --
                   16457:          $cfile -- url for file editing if editable on current server
                   16458:          $home -- homeserver of resource (i.e., for author if published,
                   16459:                                           or course if uploaded.).
                   16460:          $switchserver --  1 if server switch will be needed.
                   16461:          $forceedit -- 1 if icon/link should be to go to edit mode
                   16462:          $forceview -- 1 if icon/link should be to go to view mode
                   16463: 
                   16464: =item *
                   16465: 
                   16466: is_course_upload($file,$cnum,$cdom)
                   16467: 
                   16468: Used in course context to determine if current file was uploaded to
                   16469: the course (i.e., would be found in /userfiles/docs on the course's
                   16470: homeserver.
                   16471: 
                   16472:   input: 3 args -- filename (decluttered), course number and course domain.
                   16473:   output: boolean -- 1 if file was uploaded.
                   16474: 
1.243     albertel 16475: =back
                   16476: 
                   16477: =head2 Storing/Retreiving Data
                   16478: 
                   16479: =over 4
1.191     harris41 16480: 
                   16481: =item *
                   16482: 
1.1172.2.64  raeburn  16483: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   16484: permanently for this url; hashref needs to be given and should be a \%hashname;
                   16485: the remaining args aren't required and if they aren't passed or are '' they will
                   16486: be derived from the env (with the exception of $laststore, which is an
                   16487: optional arg used when a user's submission is stored in grading).
                   16488: $laststore is $version=$timestamp, where $version is the most recent version
                   16489: number retrieved for the corresponding $symb in the $namespace db file, and
                   16490: $timestamp is the timestamp for that transaction (UNIX time).
                   16491: $laststore is currently only passed when cstore() is called by
                   16492: structuretags::finalize_storage().
1.191     harris41 16493: 
                   16494: =item *
                   16495: 
1.1172.2.64  raeburn  16496: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   16497: but uses critical subroutine
1.191     harris41 16498: 
                   16499: =item *
                   16500: 
1.243     albertel 16501: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   16502: all args are optional
1.191     harris41 16503: 
                   16504: =item *
                   16505: 
1.717     albertel 16506: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   16507: dumps the complete (or key matching regexp) namespace into a hash
                   16508: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   16509: normally &store()ed into
                   16510: 
                   16511: $range should be either an integer '100' (give me the first 100
                   16512:                                            matching records)
                   16513:               or be  two integers sperated by a - with no spaces
                   16514:                  '30-50' (give me the 30th through the 50th matching
                   16515:                           records)
                   16516: 
                   16517: 
                   16518: =item *
                   16519: 
1.1172.2.59  raeburn  16520: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 16521: replaces a &store() version of data with a replacement set of data
                   16522: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  16523: reference. If $tolog is true, the transaction is logged in the courselog
                   16524: with an action=PUTSTORE.
1.717     albertel 16525: 
                   16526: =item *
                   16527: 
1.243     albertel 16528: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   16529: works very similar to store/cstore, but all data is stored in a
                   16530: temporary location and can be reset using tmpreset, $storehash should
                   16531: be a hash reference, returns nothing on success
1.191     harris41 16532: 
                   16533: =item *
                   16534: 
1.243     albertel 16535: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   16536: similar to restore, but all data is stored in a temporary location and
                   16537: can be reset using tmpreset. Returns a hash of values on success,
                   16538: error string otherwise.
1.191     harris41 16539: 
                   16540: =item *
                   16541: 
1.243     albertel 16542: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   16543: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 16544: 
                   16545: =item *
                   16546: 
1.243     albertel 16547: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16548: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 16549: 
                   16550: =item *
                   16551: 
1.243     albertel 16552: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   16553: namesp ($udom and $uname are optional)
1.191     harris41 16554: 
                   16555: =item *
                   16556: 
1.702     albertel 16557: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 16558: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 16559: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  16560: 
1.702     albertel 16561: $range should be either an integer '100' (give me the first 100
                   16562:                                            matching records)
                   16563:               or be  two integers sperated by a - with no spaces
                   16564:                  '30-50' (give me the 30th through the 50th matching
                   16565:                           records)
1.449     matthew  16566: =item *
                   16567: 
                   16568: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   16569: $store can be a scalar, an array reference, or if the amount to be 
                   16570: incremented is > 1, a hash reference.
                   16571: 
                   16572: ($udom and $uname are optional)
1.191     harris41 16573: 
                   16574: =item *
                   16575: 
1.243     albertel 16576: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   16577: ($udom and $uname are optional)
1.191     harris41 16578: 
                   16579: =item *
                   16580: 
1.243     albertel 16581: cput($namespace,$storehash,$udom,$uname) : critical put
                   16582: ($udom and $uname are optional)
1.191     harris41 16583: 
                   16584: =item *
                   16585: 
1.748     albertel 16586: newput($namespace,$storehash,$udom,$uname) :
                   16587: 
                   16588: Attempts to store the items in the $storehash, but only if they don't
                   16589: currently exist, if this succeeds you can be certain that you have 
                   16590: successfully created a new key value pair in the $namespace db.
                   16591: 
                   16592: 
                   16593: Args:
                   16594:  $namespace: name of database to store values to
                   16595:  $storehash: hashref to store to the db
                   16596:  $udom: (optional) domain of user containing the db
                   16597:  $uname: (optional) name of user caontaining the db
                   16598: 
                   16599: Returns:
                   16600:  'ok' -> succeeded in storing all keys of $storehash
                   16601:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   16602:                         least <key> already existed in the db (other
                   16603:                         requested keys may also already exist)
1.967     bisitz   16604:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 16605:  'con_lost' -> unable to contact request server
                   16606:  'refused' -> action was not allowed by remote machine
                   16607: 
                   16608: 
                   16609: =item *
                   16610: 
1.243     albertel 16611: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16612: reference filled in from namesp (encrypts the return communication)
                   16613: ($udom and $uname are optional)
1.191     harris41 16614: 
                   16615: =item *
                   16616: 
1.243     albertel 16617: log($udom,$name,$home,$message) : write to permanent log for user; use
                   16618: critical subroutine
                   16619: 
1.806     raeburn  16620: =item *
                   16621: 
1.860     raeburn  16622: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   16623: array reference filled in from namespace found in domain level on either
                   16624: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  16625: 
                   16626: =item *
                   16627: 
1.860     raeburn  16628: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   16629: domain level either on specified domain server ($uhome) or primary domain 
                   16630: server ($udom and $uhome are optional)
1.806     raeburn  16631: 
1.943     raeburn  16632: =item * 
                   16633: 
1.1172.2.35  raeburn  16634: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   16635: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   16636: the target domain.
                   16637: 
                   16638: May also include additional key => value pairs for the following groups:
                   16639: 
                   16640: =over
                   16641: 
                   16642: =item
                   16643: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   16644: 
                   16645: =over
                   16646: 
                   16647: =item defaultquota, authorquota
                   16648: 
                   16649: =back
                   16650: 
                   16651: =item
                   16652: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   16653: portfolio for users).
                   16654: 
                   16655: =over
                   16656: 
                   16657: =item
                   16658: aboutme, blog, webdav, portfolio
                   16659: 
                   16660: =back
                   16661: 
                   16662: =item
                   16663: requestcourses: ability to request courses, and how requests are processed.
                   16664: 
                   16665: =over
                   16666: 
                   16667: =item
1.1172.2.37  raeburn  16668: official, unofficial, community, textbook
1.1172.2.35  raeburn  16669: 
                   16670: =back
                   16671: 
                   16672: =item
                   16673: inststatus: types of institutional affiliation, and order in which they are displayed.
                   16674: 
                   16675: =over
                   16676: 
                   16677: =item
1.1172.2.44  raeburn  16678: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  16679: 
                   16680: =back
                   16681: 
                   16682: =item
                   16683: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   16684: for course's uploaded content.
                   16685: 
                   16686: =over
                   16687: 
                   16688: =item
1.1172.2.68  raeburn  16689: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   16690: communityquota, textbookquota
1.1172.2.35  raeburn  16691: 
                   16692: =back
                   16693: 
                   16694: =item
                   16695: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   16696: on your servers.
                   16697: 
                   16698: =over
                   16699: 
                   16700: =item
                   16701: remotesessions, hostedsessions
                   16702: 
                   16703: =back
                   16704: 
                   16705: =back
                   16706: 
                   16707: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   16708: utility to create a configuration.db file on a domain's primary library server
                   16709: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   16710: -- corresponding values are authentication type (internal, krb4, krb5,
                   16711: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   16712: will be available. Values are retrieved from cache (if current), unless the
                   16713: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   16714: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   16715: 
                   16716: Typical usage:
1.943     raeburn  16717: 
1.1172.2.35  raeburn  16718: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  16719: 
1.243     albertel 16720: =back
                   16721: 
                   16722: =head2 Network Status Functions
                   16723: 
                   16724: =over 4
1.191     harris41 16725: 
                   16726: =item *
                   16727: 
1.1137    raeburn  16728: dirlist() : return directory list based on URI (first arg).
                   16729: 
                   16730: Inputs: 1 required, 5 optional.
                   16731: 
                   16732: =over
                   16733: 
                   16734: =item 
                   16735: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   16736: 
                   16737: =item
                   16738: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   16739: 
                   16740: =item
                   16741: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   16742: 
                   16743: =item
                   16744: $getpropath - boolean: 1 if prepend path using &propath(). 
                   16745: 
                   16746: =item
                   16747: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   16748: 
                   16749: =item 
                   16750: $alternateRoot - path to prepend in place of path from $uri.
                   16751: 
                   16752: =back
                   16753: 
                   16754: Returns: Array of up to two items.
                   16755: 
                   16756: =over
                   16757: 
                   16758: a reference to an array of files/subdirectories
                   16759: 
                   16760: =over
                   16761: 
                   16762: Each element in the array of files/subdirectories is a & separated list of
                   16763: item name and the result of running stat on the item.  If dirlist was requested
                   16764: for a file instead of a directory, the item name will be ''. For a directory 
                   16765: listing, if the item is a metadata file, the element will end &N&M 
                   16766: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   16767: default copyright set (1).  
                   16768: 
                   16769: =back
                   16770: 
                   16771: a scalar containing error condition (if encountered).
                   16772: 
                   16773: =over
                   16774: 
                   16775: =item 
                   16776: no_host (no homeserver identified for $username:$domain).
                   16777: 
                   16778: =item 
                   16779: no_such_host (server contacted for listing not identified as valid host).
                   16780: 
                   16781: =item 
                   16782: con_lost (connection to remote server failed).
                   16783: 
                   16784: =item 
                   16785: refused (invalid $username:$domain received on lond side).
                   16786: 
                   16787: =item 
                   16788: no_such_dir (directory at specified path on lond side does not exist). 
                   16789: 
                   16790: =item 
                   16791: empty (directory at specified path on lond side is empty).
                   16792: 
                   16793: =over
                   16794: 
                   16795: This is currently not encountered because the &ls3, &ls2, 
                   16796: &ls (_handler) routines on the lond side do not filter out
                   16797: . and .. from a directory listing. 
                   16798: 
                   16799: =back
                   16800: 
                   16801: =back
                   16802: 
                   16803: =back
1.191     harris41 16804: 
                   16805: =item *
                   16806: 
1.243     albertel 16807: spareserver() : find server with least workload from spare.tab
                   16808: 
1.986     foxr     16809: 
                   16810: =item *
                   16811: 
                   16812: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   16813: if there is no corresponding loncapa host.
                   16814: 
1.243     albertel 16815: =back
                   16816: 
1.986     foxr     16817: 
1.243     albertel 16818: =head2 Apache Request
                   16819: 
                   16820: =over 4
1.191     harris41 16821: 
                   16822: =item *
                   16823: 
1.243     albertel 16824: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   16825: localhost, posts hash
                   16826: 
                   16827: =back
                   16828: 
                   16829: =head2 Data to String to Data
                   16830: 
                   16831: =over 4
1.191     harris41 16832: 
                   16833: =item *
                   16834: 
1.243     albertel 16835: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   16836: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 16837: 
                   16838: =item *
                   16839: 
1.243     albertel 16840: hashref2str($hashref) : convert a hashref into a string complete with
                   16841: escaping and '=' and '&' separators, supports elements that are
                   16842: arrayrefs and hashrefs
1.191     harris41 16843: 
                   16844: =item *
                   16845: 
1.243     albertel 16846: arrayref2str($arrayref) : convert an arrayref into a string complete
                   16847: with escaping and '&' separators, supports elements that are arrayrefs
                   16848: and hashrefs
1.191     harris41 16849: 
                   16850: =item *
                   16851: 
1.243     albertel 16852: str2hash($string) : convert string to hash using unescaping and
                   16853: splitting on '=' and '&', supports elements that are arrayrefs and
                   16854: hashrefs
1.191     harris41 16855: 
                   16856: =item *
                   16857: 
1.243     albertel 16858: str2array($string) : convert string to hash using unescaping and
                   16859: splitting on '&', supports elements that are arrayrefs and hashrefs
                   16860: 
                   16861: =back
                   16862: 
                   16863: =head2 Logging Routines
                   16864: 
                   16865: 
                   16866: These routines allow one to make log messages in the lonnet.log and
                   16867: lonnet.perm logfiles.
1.191     harris41 16868: 
1.1119    foxr     16869: =over 4
                   16870: 
1.191     harris41 16871: =item *
                   16872: 
1.243     albertel 16873: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 16874: 
                   16875: =item *
                   16876: 
1.243     albertel 16877: logthis() : append message to the normal lonnet.log file, it gets
                   16878: preiodically rolled over and deleted.
1.191     harris41 16879: 
                   16880: =item *
                   16881: 
1.243     albertel 16882: logperm() : append a permanent message to lonnet.perm.log, this log
                   16883: file never gets deleted by any automated portion of the system, only
                   16884: messages of critical importance should go in here.
                   16885: 
1.1119    foxr     16886: 
1.243     albertel 16887: =back
                   16888: 
                   16889: =head2 General File Helper Routines
                   16890: 
                   16891: =over 4
1.191     harris41 16892: 
                   16893: =item *
                   16894: 
1.481     raeburn  16895: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   16896: (a) files in /uploaded
                   16897:   (i) If a local copy of the file exists - 
                   16898:       compares modification date of local copy with last-modified date for 
                   16899:       definitive version stored on home server for course. If local copy is 
                   16900:       stale, requests a new version from the home server and stores it. 
                   16901:       If the original has been removed from the home server, then local copy 
                   16902:       is unlinked.
                   16903:   (ii) If local copy does not exist -
                   16904:       requests the file from the home server and stores it. 
                   16905:   
                   16906:   If $caller is 'uploadrep':  
                   16907:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   16908:     for request for files originally uploaded via DOCS. 
                   16909:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   16910:   
                   16911:   Otherwise:
                   16912:      This indicates a call from the content generation phase of the request.
                   16913:      -  returns the entire contents of the file or -1.
                   16914:      
                   16915: (b) files in /res
                   16916:    - returns the entire contents of a file or -1; 
                   16917:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 16918: 
1.712     albertel 16919: 
                   16920: =item *
                   16921: 
                   16922: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   16923:                   reference
                   16924: 
                   16925: returns either a stat() list of data about the file or an empty list
                   16926: if the file doesn't exist or couldn't find out about it (connection
                   16927: problems or user unknown)
                   16928: 
1.191     harris41 16929: =item *
                   16930: 
1.243     albertel 16931: filelocation($dir,$file) : returns file system location of a file
                   16932: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   16933: directory that relative $file lookups are to looked in ($dir of /a/dir
                   16934: and a file of ../bob will become /a/bob)
1.191     harris41 16935: 
                   16936: =item *
                   16937: 
                   16938: hreflocation($dir,$file) : returns file system location or a URL; same as
                   16939: filelocation except for hrefs
                   16940: 
                   16941: =item *
                   16942: 
1.1172.2.49  raeburn  16943: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   16944: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 16945: 
1.243     albertel 16946: =back
                   16947: 
1.608     albertel 16948: =head2 Usererfile file routines (/uploaded*)
                   16949: 
                   16950: =over 4
                   16951: 
                   16952: =item *
                   16953: 
                   16954: userfileupload(): main rotine for putting a file in a user or course's
                   16955:                   filespace, arguments are,
                   16956: 
1.620     albertel 16957:  formname - required - this is the name of the element in $env where the
1.608     albertel 16958:            filename, and the contents of the file to create/modifed exist
1.620     albertel 16959:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   16960:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  16961:  context - if coursedoc, store the file in the course of the active role
                   16962:              of the current user; 
                   16963:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   16964:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 16965:  subdir - required - subdirectory to put the file in under ../userfiles/
                   16966:          if undefined, it will be placed in "unknown"
                   16967: 
                   16968:  (This routine calls clean_filename() to remove any dangerous
                   16969:  characters from the filename, and then calls finuserfileupload() to
                   16970:  complete the transaction)
                   16971: 
                   16972:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16973:  and /adm/notfound.html if unsuccessful
                   16974: 
                   16975: =item *
                   16976: 
                   16977: clean_filename(): routine for cleaing a filename up for storage in
                   16978:                  userfile space, argument is:
                   16979: 
                   16980:  filename - proposed filename
                   16981: 
                   16982: returns: the new clean filename
                   16983: 
                   16984: =item *
                   16985: 
1.1090    raeburn  16986: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16987: userspace, probably shouldn't be called directly
                   16988: 
                   16989:   docuname: username or courseid of destination for the file
                   16990:   docudom: domain of user/course of destination for the file
                   16991:   formname: same as for userfileupload()
1.1090    raeburn  16992:   fname: filename (including subdirectories) for the file
                   16993:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  16994:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16995:   allfiles: reference to hash used to store objects found by parser
                   16996:   codebase: reference to hash used for codebases of java objects found by parser
                   16997:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16998:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16999:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   17000:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   17001:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   17002:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  17003:   mimetype: reference to scalar to accommodate mime type determined
                   17004:             from File::MMagic if $parser = parse.
1.608     albertel 17005: 
                   17006:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  17007:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   17008:  was 'overwrite').
                   17009:  
1.608     albertel 17010: 
                   17011: =item *
                   17012: 
                   17013: renameuserfile(): renames an existing userfile to a new name
                   17014: 
                   17015:   Args:
                   17016:    docuname: username or courseid of destination for the file
                   17017:    docudom: domain of user/course of destination for the file
                   17018:    old: current file name (including any subdirs under userfiles)
                   17019:    new: desired file name (including any subdirs under userfiles)
                   17020: 
                   17021: =item *
                   17022: 
                   17023: mkdiruserfile(): creates a directory is a userfiles dir
                   17024: 
                   17025:   Args:
                   17026:    docuname: username or courseid of destination for the file
                   17027:    docudom: domain of user/course of destination for the file
                   17028:    dir: dir to create (including any subdirs under userfiles)
                   17029: 
                   17030: =item *
                   17031: 
                   17032: removeuserfile(): removes a file that exists in userfiles
                   17033: 
                   17034:   Args:
                   17035:    docuname: username or courseid of destination for the file
                   17036:    docudom: domain of user/course of destination for the file
                   17037:    fname: filname to delete (including any subdirs under userfiles)
                   17038: 
                   17039: =item *
                   17040: 
                   17041: removeuploadedurl(): convience function for removeuserfile()
                   17042: 
                   17043:   Args:
                   17044:    url:  a full /uploaded/... url to delete
                   17045: 
1.747     albertel 17046: =item * 
                   17047: 
                   17048: get_portfile_permissions():
                   17049:   Args:
                   17050:     domain: domain of user or course contain the portfolio files
                   17051:     user: name of user or num of course contain the portfolio files
                   17052:   Returns:
                   17053:     hashref of a dump of the proper file_permissions.db
                   17054:    
                   17055: 
                   17056: =item * 
                   17057: 
                   17058: get_access_controls():
                   17059: 
                   17060: Args:
                   17061:   current_permissions: the hash ref returned from get_portfile_permissions()
                   17062:   group: (optional) the group you want the files associated with
                   17063:   file: (optional) the file you want access info on
                   17064: 
                   17065: Returns:
1.749     raeburn  17066:     a hash (keys are file names) of hashes containing
                   17067:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   17068:         values are XML containing access control settings (see below) 
1.747     albertel 17069: 
                   17070: Internal notes:
                   17071: 
1.749     raeburn  17072:  access controls are stored in file_permissions.db as key=value pairs.
                   17073:     key -> path to file/file_name\0uniqueID:scope_end_start
                   17074:         where scope -> public,guest,course,group,domains or users.
                   17075:               end -> UNIX time for end of access (0 -> no end date)
                   17076:               start -> UNIX time for start of access
                   17077: 
                   17078:     value -> XML description of access control
                   17079:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   17080:             <start></start>
                   17081:             <end></end>
                   17082: 
                   17083:             <password></password>  for scope type = guest
                   17084: 
                   17085:             <domain></domain>     for scope type = course or group
                   17086:             <number></number>
                   17087:             <roles id="">
                   17088:              <role></role>
                   17089:              <access></access>
                   17090:              <section></section>
                   17091:              <group></group>
                   17092:             </roles>
                   17093: 
                   17094:             <dom></dom>         for scope type = domains
                   17095: 
                   17096:             <users>             for scope type = users
                   17097:              <user>
                   17098:               <uname></uname>
                   17099:               <udom></udom>
                   17100:              </user>
                   17101:             </users>
                   17102:            </scope> 
                   17103:               
                   17104:  Access data is also aggregated for each file in an additional key=value pair:
                   17105:  key -> path to file/file_name\0accesscontrol 
                   17106:  value -> reference to hash
                   17107:           hash contains key = value pairs
                   17108:           where key = uniqueID:scope_end_start
                   17109:                 value = UNIX time record was last updated
                   17110: 
                   17111:           Used to improve speed of look-ups of access controls for each file.  
                   17112:  
                   17113:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   17114: 
1.1172.2.13  raeburn  17115: =item *
                   17116: 
1.749     raeburn  17117: modify_access_controls():
                   17118: 
                   17119: Modifies access controls for a portfolio file
                   17120: Args
                   17121: 1. file name
                   17122: 2. reference to hash of required changes,
                   17123: 3. domain
                   17124: 4. username
                   17125:   where domain,username are the domain of the portfolio owner 
                   17126:   (either a user or a course) 
                   17127: 
                   17128: Returns:
                   17129: 1. result of additions or updates ('ok' or 'error', with error message). 
                   17130: 2. result of deletions ('ok' or 'error', with error message).
                   17131: 3. reference to hash of any new or updated access controls.
                   17132: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   17133:    key = integer (inbound ID)
1.1172.2.13  raeburn  17134:    value = uniqueID
                   17135: 
                   17136: =item *
                   17137: 
                   17138: get_timebased_id():
                   17139: 
                   17140: Attempts to get a unique timestamp-based suffix for use with items added to a
                   17141: course via the Course Editor (e.g., folders, composite pages,
                   17142: group bulletin boards).
                   17143: 
                   17144: Args: (first three required; six others optional)
                   17145: 
                   17146: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   17147:    docssequence, or name of group
                   17148: 
                   17149: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   17150:    e.g., num, boardids
                   17151: 
                   17152: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   17153:    file will be named nohist_namespace.db
                   17154: 
                   17155: 4. cdom: domain of course; default is current course domain from %env
                   17156: 
                   17157: 5. cnum: course number; default is current course number from %env
                   17158: 
                   17159: 6. idtype: set to concat if an additional digit is to be appended to the
                   17160:    unix timestamp to form the suffix, if the plain timestamp is already
                   17161:    in use.  Default is to not do this, but simply increment the unix
                   17162:    timestamp by 1 until a unique key is obtained.
                   17163: 
                   17164: 7. who: holder of locking key; defaults to user:domain for user.
                   17165: 
                   17166: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   17167:    retrying); default is 3.
                   17168: 
                   17169: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   17170: 
                   17171: Returns:
                   17172: 
                   17173: 1. suffix obtained (numeric)
                   17174: 
                   17175: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   17176: 
                   17177: 3. error: contains (localized) error message if an error occurred.
                   17178: 
1.747     albertel 17179: 
1.608     albertel 17180: =back
                   17181: 
1.243     albertel 17182: =head2 HTTP Helper Routines
                   17183: 
                   17184: =over 4
                   17185: 
1.191     harris41 17186: =item *
                   17187: 
                   17188: escape() : unpack non-word characters into CGI-compatible hex codes
                   17189: 
                   17190: =item *
                   17191: 
                   17192: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   17193: 
1.243     albertel 17194: =back
                   17195: 
                   17196: =head1 PRIVATE SUBROUTINES
                   17197: 
                   17198: =head2 Underlying communication routines (Shouldn't call)
                   17199: 
                   17200: =over 4
                   17201: 
                   17202: =item *
                   17203: 
                   17204: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   17205: 
                   17206: =item *
                   17207: 
                   17208: reply() : uses subreply to send a message to remote machine, logs all failures
                   17209: 
                   17210: =item *
                   17211: 
                   17212: critical() : passes a critical message to another server; if cannot
                   17213: get through then place message in connection buffer directory and
                   17214: returns con_delayed, if incapable of saving message, returns
                   17215: con_failed
                   17216: 
                   17217: =item *
                   17218: 
                   17219: reconlonc() : tries to reconnect lonc client processes.
                   17220: 
                   17221: =back
                   17222: 
                   17223: =head2 Resource Access Logging
                   17224: 
                   17225: =over 4
                   17226: 
                   17227: =item *
                   17228: 
                   17229: flushcourselogs() : flush (save) buffer logs and access logs
                   17230: 
                   17231: =item *
                   17232: 
                   17233: courselog($what) : save message for course in hash
                   17234: 
                   17235: =item *
                   17236: 
                   17237: courseacclog($what) : save message for course using &courselog().  Perform
                   17238: special processing for specific resource types (problems, exams, quizzes, etc).
                   17239: 
1.191     harris41 17240: =item *
                   17241: 
                   17242: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   17243: as a PerlChildExitHandler
1.243     albertel 17244: 
                   17245: =back
                   17246: 
                   17247: =head2 Other
                   17248: 
                   17249: =over 4
                   17250: 
                   17251: =item *
                   17252: 
                   17253: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 17254: 
                   17255: =back
                   17256: 
                   17257: =cut
1.877     foxr     17258: 

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