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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.146.  .17(raeb    4:-24): # $Id: lonnet.pm,v 1.1172.2.146.2.16 2023/10/06 02:48:36 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
1.1172.2.107  raeburn    77: use CGI::Cookie;
1.977     amueller   78: 
1.1172.2.104  raeburn    79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138    raeburn    80:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1172.2.114  raeburn    81:             %managerstab $passwdmin);
1.871     albertel   82: 
                     83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     84:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     85:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        86:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        87: 
1.1       albertel   88: use IO::Socket;
1.31      www        89: use GDBM_File;
1.208     albertel   90: use HTML::LCParser;
1.88      www        91: use Fcntl qw(:flock);
1.870     albertel   92: use Storable qw(thaw nfreeze);
1.1172.2.79  raeburn    93: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   94: use Cache::Memcached;
1.676     albertel   95: use Digest::MD5;
1.790     albertel   96: use Math::Random;
1.1024    raeburn    97: use File::MMagic;
1.1172.2.142  raeburn    98: use Net::CIDR;
                     99: use Sys::Hostname::FQDN();
1.807     albertel  100: use LONCAPA qw(:DEFAULT :match);
1.740     www       101: use LONCAPA::Configuration;
1.1160    www       102: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   103: use LONCAPA::Lond;
1.1172.2.110  raeburn   104: use LONCAPA::transliterate;
1.1117    foxr      105: 
1.1090    raeburn   106: use File::Copy;
1.676     albertel  107: 
1.195     www       108: my $readit;
1.1172.2.79  raeburn   109: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  110: 
1.619     albertel  111: require Exporter;
                    112: 
                    113: our @ISA = qw (Exporter);
                    114: our @EXPORT = qw(%env);
                    115: 
1.1172.2.9  raeburn   116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       117: {
                    118:     my $logid;
1.1172.2.9  raeburn   119:     sub write_log {
                    120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    121:         if ($context eq 'course') {
                    122:             if (($cnum eq '') || ($cdom eq '')) {
                    123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    125:             }
1.957     raeburn   126:         }
1.1172.2.13  raeburn   127: 	$logid ++;
1.957     raeburn   128:         my $now = time();
                    129: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.146.  .1(raebu  130:22):         my $ip = &get_requestor_ip();
1.1172.2.9  raeburn   131:         my $logentry = {
                    132:                          $id => {
                    133:                                   'exe_uname' => $env{'user.name'},
                    134:                                   'exe_udom'  => $env{'user.domain'},
                    135:                                   'exe_time'  => $now,
1.1172.2.134  raeburn   136:                                   'exe_ip'    => $ip,
1.1172.2.9  raeburn   137:                                   'delflag'   => $delflag,
                    138:                                   'logentry'  => $storehash,
                    139:                                   'uname'     => $uname,
                    140:                                   'udom'      => $udom,
                    141:                                 }
                    142:                        };
                    143:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       144:     }
                    145: }
1.1       albertel  146: 
1.163     harris41  147: sub logtouch {
                    148:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  149:     unless (-e "$execdir/logs/lonnet.log") {	
1.1172.2.96  raeburn   150: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  151: 	close $fh;
                    152:     }
                    153:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    154:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    155: }
                    156: 
1.1       albertel  157: sub logthis {
                    158:     my $message=shift;
                    159:     my $execdir=$perlvar{'lonDaemons'};
                    160:     my $now=time;
                    161:     my $local=localtime($now);
1.1172.2.96  raeburn   162:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      163: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    164: 	print $fh $logstring;
1.448     albertel  165: 	close($fh);
                    166:     }
1.1       albertel  167:     return 1;
                    168: }
                    169: 
                    170: sub logperm {
                    171:     my $message=shift;
                    172:     my $execdir=$perlvar{'lonDaemons'};
                    173:     my $now=time;
                    174:     my $local=localtime($now);
1.1172.2.96  raeburn   175:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  176: 	print $fh "$now:$message:$local\n";
                    177: 	close($fh);
                    178:     }
1.1       albertel  179:     return 1;
                    180: }
                    181: 
1.850     albertel  182: sub create_connection {
1.853     albertel  183:     my ($hostname,$lonid) = @_;
1.851     albertel  184:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  185: 				     Type    => SOCK_STREAM,
                    186: 				     Timeout => 10);
                    187:     return 0 if (!$client);
1.890     albertel  188:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  189:     my $result = <$client>;
                    190:     chomp($result);
                    191:     return 1 if ($result eq 'done');
                    192:     return 0;
                    193: }
                    194: 
1.983     raeburn   195: sub get_server_timezone {
                    196:     my ($cnum,$cdom) = @_;
                    197:     my $home=&homeserver($cnum,$cdom);
                    198:     if ($home ne 'no_host') {
                    199:         my $cachetime = 24*3600;
                    200:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    201:         if (defined($cached)) {
                    202:             return $timezone;
                    203:         } else {
                    204:             my $timezone = &reply('servertimezone',$home);
                    205:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    206:         }
                    207:     }
                    208: }
1.850     albertel  209: 
1.1106    raeburn   210: sub get_server_distarch {
                    211:     my ($lonhost,$ignore_cache) = @_;
                    212:     if (defined($lonhost)) {
                    213:         if (!defined(&hostname($lonhost))) {
                    214:             return;
                    215:         }
                    216:         my $cachetime = 12*3600;
                    217:         if (!$ignore_cache) {
                    218:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    219:             if (defined($cached)) {
                    220:                 return $distarch;
                    221:             }
                    222:         }
                    223:         my $rep = &reply('serverdistarch',$lonhost);
                    224:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    225:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    226:                 $rep eq '') {
                    227:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    228:         }
                    229:     }
                    230:     return;
                    231: }
                    232: 
1.993     raeburn   233: sub get_server_loncaparev {
1.1073    raeburn   234:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   235:     if (defined($lonhost)) {
                    236:         if (!defined(&hostname($lonhost))) {
                    237:             undef($lonhost);
                    238:         }
                    239:     }
                    240:     if (!defined($lonhost)) {
                    241:         if (defined(&domain($dom,'primary'))) {
                    242:             $lonhost=&domain($dom,'primary');
                    243:             if ($lonhost eq 'no_host') {
                    244:                 undef($lonhost);
                    245:             }
                    246:         }
                    247:     }
                    248:     if (defined($lonhost)) {
1.1073    raeburn   249:         my $cachetime = 12*3600;
                    250:         if (!$ignore_cache) {
                    251:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    252:             if (defined($cached)) {
                    253:                 return $loncaparev;
                    254:             }
                    255:         }
                    256:         my ($answer,$loncaparev);
                    257:         my @ids=&current_machine_ids();
                    258:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    259:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   260:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   261:                 $loncaparev = $1;
                    262:             }
                    263:         } else {
                    264:             $answer = &reply('serverloncaparev',$lonhost);
                    265:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    266:                 if ($caller eq 'loncron') {
                    267:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   268:                     $ua->timeout(4);
1.1172.2.120  raeburn   269:                     my $hostname = &hostname($lonhost);
1.1073    raeburn   270:                     my $protocol = $protocol{$lonhost};
                    271:                     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn   272:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   273:                     my $request=new HTTP::Request('GET',$url);
                    274:                     my $response=$ua->request($request);
                    275:                     unless ($response->is_error()) {
                    276:                         my $content = $response->content;
1.1081    raeburn   277:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   278:                             $loncaparev = $1;
                    279:                         }
                    280:                     }
                    281:                 } else {
                    282:                     $loncaparev = $loncaparevs{$lonhost};
                    283:                 }
1.1081    raeburn   284:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   285:                 $loncaparev = $1;
                    286:             }
1.993     raeburn   287:         }
1.1073    raeburn   288:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   289:     }
                    290: }
                    291: 
1.1074    raeburn   292: sub get_server_homeID {
                    293:     my ($hostname,$ignore_cache,$caller) = @_;
                    294:     unless ($ignore_cache) {
                    295:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    296:         if (defined($cached)) {
                    297:             return $serverhomeID;
                    298:         }
                    299:     }
                    300:     my $cachetime = 12*3600;
                    301:     my $serverhomeID;
                    302:     if ($caller eq 'loncron') { 
                    303:         my @machine_ids = &machine_ids($hostname);
                    304:         foreach my $id (@machine_ids) {
                    305:             my $response = &reply('serverhomeID',$id);
                    306:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    307:                 $serverhomeID = $response;
                    308:                 last;
                    309:             }
                    310:         }
                    311:         if ($serverhomeID eq '') {
                    312:             $serverhomeID = $machine_ids[-1];
                    313:         }
                    314:     } else {
                    315:         $serverhomeID = $serverhomeIDs{$hostname};
                    316:     }
                    317:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    318: }
                    319: 
1.1121    raeburn   320: sub get_remote_globals {
                    321:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   322:     my ($result,%returnhash,%whatneeded);
                    323:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   324:         foreach my $what (sort(keys(%{$whathash}))) {
                    325:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   326:             my ($response,$cached);
1.1121    raeburn   327:             unless ($ignore_cache) {
1.1125    raeburn   328:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   329:             }
                    330:             if (defined($cached)) {
1.1125    raeburn   331:                 $returnhash{$what} = $response;
1.1121    raeburn   332:             } else {
1.1125    raeburn   333:                 $whatneeded{$what} = 1;
1.1121    raeburn   334:             }
                    335:         }
1.1125    raeburn   336:         if (keys(%whatneeded) == 0) {
                    337:             $result = 'ok';
                    338:         } else {
1.1121    raeburn   339:             my $requested = &freeze_escape(\%whatneeded);
                    340:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   341:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    342:                 ($rep eq 'unknown_cmd')) {
                    343:                 $result = $rep;
                    344:             } else {
                    345:                 $result = 'ok';
1.1121    raeburn   346:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   347:                 foreach my $item (@pairs) {
                    348:                     my ($key,$value)=split(/=/,$item,2);
                    349:                     my $what = &unescape($key);
                    350:                     my $hashid = $lonhost.'-'.$what;
                    351:                     $returnhash{$what}=&thaw_unescape($value);
                    352:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   353:                 }
                    354:             }
                    355:         }
                    356:     }
1.1125    raeburn   357:     return ($result,\%returnhash);
1.1121    raeburn   358: }
                    359: 
1.1124    raeburn   360: sub remote_devalidate_cache {
1.1172.2.35  raeburn   361:     my ($lonhost,$cachekeys) = @_;
                    362:     my $items;
                    363:     return unless (ref($cachekeys) eq 'ARRAY');
                    364:     my $cachestr = join('&',@{$cachekeys});
                    365:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   366: }
                    367: 
1.1172.2.146.  .13(raeb  368:-23): sub sign_lti {
                    369:-23):     my ($cdom,$cnum,$crsdef,$type,$context,$url,$ltinum,$keynum,$paramsref,$inforef) = @_;
                    370:-23):     my $chome;
                    371:-23):     if (&domain($cdom) ne '') {
                    372:-23):         if ($crsdef) {
                    373:-23):             $chome = &homeserver($cnum,$cdom);
                    374:-23):         } else {
                    375:-23):             $chome = &domain($cdom,'primary');
                    376:-23):         }
                    377:-23):     }
                    378:-23):     if ($cdom && $chome && ($chome ne 'no_host')) {
                    379:-23):         if ((ref($paramsref) eq 'HASH') &&
                    380:-23):             (ref($inforef) eq 'HASH')) {
                    381:-23):             my $rep;
                    382:-23):             if (grep { $_ eq $chome } &current_machine_ids()) {
                    383:-23):                 # domain information is hosted on this machine
                    384:-23):                 $rep =
                    385:-23):                     &LONCAPA::Lond::sign_lti_payload($cdom,$cnum,$crsdef,$type,
                    386:-23):                                                      $context,$url,$ltinum,$keynum,
                    387:-23):                                                      $perlvar{'lonVersion'},
                    388:-23):                                                      $paramsref,$inforef);
                    389:-23):                 if (ref($rep) eq 'HASH') {
                    390:-23):                     return ('ok',$rep);
                    391:-23):                 }
                    392:-23):             } else {
                    393:-23):                 my ($escurl,$params,$info);
                    394:-23):                 $escurl = &escape($url);
                    395:-23):                 if (ref($paramsref) eq 'HASH') {
                    396:-23):                     $params = &freeze_escape($paramsref);
                    397:-23):                 }
                    398:-23):                 if (ref($inforef) eq 'HASH') {
                    399:-23):                     $info = &freeze_escape($inforef);
                    400:-23):                 }
                    401:-23):                 $rep=&reply("encrypt:signlti:$cdom:$cnum:$crsdef:$type:$context:$escurl:$ltinum:$keynum:$params:$info",$chome);
                    402:-23):             }
                    403:-23):             if (($rep eq '') || ($rep =~ /^con_lost|error|no_such_host|unknown_cmd/i)) {
                    404:-23):                 return ();
                    405:-23):             } elsif (($inforef->{'respfmt'} eq 'to_post_body') ||
                    406:-23):                      ($inforef->{'respfmt'} eq 'to_authorization_header')) {
                    407:-23):                 return ('ok',$rep);
                    408:-23):             } else {
                    409:-23):                 my %returnhash;
                    410:-23):                 foreach my $item (split(/\&/,$rep)) {
                    411:-23):                     my ($name,$value)=split(/\=/,$item);
                    412:-23):                     $returnhash{&unescape($name)}=&thaw_unescape($value);
                    413:-23):                 }
                    414:-23):                 return('ok',\%returnhash);
                    415:-23):             }
                    416:-23):         } else {
                    417:-23):             return ();
                    418:-23):         }
                    419:-23):     } else {
                    420:-23):         return ();
                    421:-23):         &logthis("sign_lti failed - no homeserver and/or domain ($cdom) ($chome)");
                    422:-23):     }
                    423:-23): }
                    424:-23): 
1.1       albertel  425: # -------------------------------------------------- Non-critical communication
                    426: sub subreply {
                    427:     my ($cmd,$server)=@_;
1.838     albertel  428:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      429:     #
                    430:     #  With loncnew process trimming, there's a timing hole between lonc server
                    431:     #  process exit and the master server picking up the listen on the AF_UNIX
                    432:     #  socket.  In that time interval, a lock file will exist:
                    433: 
                    434:     my $lockfile=$peerfile.".lock";
                    435:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   436: 	sleep(0.1);
1.549     foxr      437:     }
                    438:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      439:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      440:     #
1.550     foxr      441:     #   We'll give the connection a few tries before abandoning it.  If
                    442:     #   connection is not possible, we'll con_lost back to the client.
                    443:     #   
                    444:     my $client;
                    445:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    446: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    447: 				      Type    => SOCK_STREAM,
                    448: 				      Timeout => 10);
1.869     albertel  449: 	if ($client) {
1.550     foxr      450: 	    last;		# Connected!
1.850     albertel  451: 	} else {
1.853     albertel  452: 	    &create_connection(&hostname($server),$server);
1.550     foxr      453: 	}
1.1172.2.79  raeburn   454:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      455:     }
                    456:     my $answer;
                    457:     if ($client) {
1.704     albertel  458: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      459: 	$answer=<$client>;
                    460: 	if (!$answer) { $answer="con_lost"; }
                    461: 	chomp($answer);
                    462:     } else {
                    463: 	$answer = 'con_lost';	# Failed connection.
                    464:     }
1.1       albertel  465:     return $answer;
                    466: }
                    467: 
                    468: sub reply {
                    469:     my ($cmd,$server)=@_;
1.838     albertel  470:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  471:     my $answer=subreply($cmd,$server);
1.65      www       472:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111  raeburn   473:         my $logged = $cmd;
                    474:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    475:             my $subcmd = $1;
                    476:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    477:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1172.2.146.  .13(raeb  478:-23):                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
                    479:-23):                 ($subcmd eq 'put')) {
1.1172.2.111  raeburn   480:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    481:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    482:                     splice(@rest,2,1,'Hidden');
                    483:                 } elsif ($subcmd eq 'passwd') {
                    484:                     splice(@rest,2,2,('Hidden','Hidden'));
                    485:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1172.2.146.  .13(raeb  486:-23):                          ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
1.1172.2.111  raeburn   487:                     splice(@rest,3,1,'Hidden');
                    488:                 }
                    489:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    490:             }
                    491:         }
                    492:         &logthis("<font color=\"blue\">WARNING:".
                    493:                  " $logged to $server returned $answer</font>");
1.12      www       494:     }
1.1       albertel  495:     return $answer;
                    496: }
                    497: 
                    498: # ----------------------------------------------------------- Send USR1 to lonc
                    499: 
                    500: sub reconlonc {
1.891     albertel  501:     my ($lonid) = @_;
                    502:     if ($lonid) {
1.1172.2.72  raeburn   503:         my $hostname = &hostname($lonid);
1.891     albertel  504: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    505: 	if ($hostname && -e $peerfile) {
                    506: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    507: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    508: 					     Type    => SOCK_STREAM,
                    509: 					     Timeout => 10);
                    510: 	    if ($client) {
                    511: 		print $client ("reset_retries\n");
                    512: 		my $answer=<$client>;
                    513: 		#reset just this one.
                    514: 	    }
                    515: 	}
                    516: 	return;
                    517:     }
                    518: 
1.836     www       519:     &logthis("Trying to reconnect lonc");
1.1       albertel  520:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96  raeburn   521:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  522: 	my $loncpid=<$fh>;
                    523:         chomp($loncpid);
                    524:         if (kill 0 => $loncpid) {
                    525: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    526:             kill USR1 => $loncpid;
                    527:             sleep 1;
1.836     www       528:          } else {
1.12      www       529: 	    &logthis(
1.672     albertel  530:                "<font color=\"blue\">WARNING:".
1.12      www       531:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  532:         }
                    533:     } else {
1.836     www       534: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  535:     }
                    536: }
                    537: 
                    538: # ------------------------------------------------------ Critical communication
1.12      www       539: 
1.1       albertel  540: sub critical {
                    541:     my ($cmd,$server)=@_;
1.838     albertel  542:     unless (&hostname($server)) {
1.672     albertel  543:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       544:                " Critical message to unknown server ($server)</font>");
                    545:         return 'no_such_host';
                    546:     }
1.1       albertel  547:     my $answer=reply($cmd,$server);
                    548:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   549: 	&reconlonc($server);
1.589     albertel  550: 	my $answer=reply($cmd,$server);
1.1       albertel  551:         if ($answer eq 'con_lost') {
                    552:             my $now=time;
                    553:             my $middlename=$cmd;
1.5       www       554:             $middlename=substr($middlename,0,16);
1.1       albertel  555:             $middlename=~s/\W//g;
                    556:             my $dfilename=
1.305     www       557:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    558:             $dumpcount++;
1.1       albertel  559:             {
1.448     albertel  560: 		my $dfh;
1.1172.2.96  raeburn   561: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  562: 		    print $dfh "$cmd\n"; 
                    563: 		    close($dfh);
                    564: 		}
1.1       albertel  565:             }
1.1172.2.79  raeburn   566:             sleep 1;
1.1       albertel  567:             my $wcmd='';
                    568:             {
1.448     albertel  569: 		my $dfh;
1.1172.2.96  raeburn   570: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  571: 		    $wcmd=<$dfh>; 
                    572: 		    close($dfh);
                    573: 		}
1.1       albertel  574:             }
                    575:             chomp($wcmd);
1.7       www       576:             if ($wcmd eq $cmd) {
1.672     albertel  577: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       578:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  579:                 &logperm("D:$server:$cmd");
                    580: 	        return 'con_delayed';
                    581:             } else {
1.672     albertel  582:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       583:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  584:                 &logperm("F:$server:$cmd");
                    585:                 return 'con_failed';
                    586:             }
                    587:         }
                    588:     }
                    589:     return $answer;
1.405     albertel  590: }
                    591: 
1.755     albertel  592: # ------------------------------------------- check if return value is an error
                    593: 
                    594: sub error {
                    595:     my ($result) = @_;
1.756     albertel  596:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  597: 	if ($2 == 2) { return undef; }
                    598: 	return $1;
                    599:     }
                    600:     return undef;
                    601: }
                    602: 
1.783     albertel  603: sub convert_and_load_session_env {
                    604:     my ($lonidsdir,$handle)=@_;
                    605:     my @profile;
                    606:     {
1.917     albertel  607: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    608: 	if (!$opened) {
1.915     albertel  609: 	    return 0;
                    610: 	}
1.783     albertel  611: 	flock($idf,LOCK_SH);
                    612: 	@profile=<$idf>;
                    613: 	close($idf);
                    614:     }
                    615:     my %temp_env;
                    616:     foreach my $line (@profile) {
1.786     albertel  617: 	if ($line !~ m/=/) {
                    618: 	    return 0;
                    619: 	}
1.783     albertel  620: 	chomp($line);
                    621: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    622: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    623:     }
                    624:     unlink("$lonidsdir/$handle.id");
                    625:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    626: 	    0640)) {
                    627: 	%disk_env = %temp_env;
                    628: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    629: 	untie(%disk_env);
                    630:     }
1.786     albertel  631:     return 1;
1.783     albertel  632: }
                    633: 
1.374     www       634: # ------------------------------------------- Transfer profile into environment
1.780     albertel  635: my $env_loaded;
                    636: sub transfer_profile_to_env {
1.788     albertel  637:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    638:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       639: 
1.720     albertel  640:     if (!defined($lonidsdir)) {
                    641: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    642:     }
                    643:     if (!defined($handle)) {
                    644:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    645:     }
                    646: 
1.786     albertel  647:     my $convert;
                    648:     {
1.917     albertel  649:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    650: 	if (!$opened) {
1.915     albertel  651: 	    return;
                    652: 	}
1.786     albertel  653: 	flock($idf,LOCK_SH);
                    654: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    655: 		&GDBM_READER(),0640)) {
                    656: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    657: 	    untie(%disk_env);
                    658: 	} else {
                    659: 	    $convert = 1;
                    660: 	}
                    661:     }
                    662:     if ($convert) {
                    663: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    664: 	    &logthis("Failed to load session, or convert session.");
                    665: 	}
1.374     www       666:     }
1.783     albertel  667: 
1.786     albertel  668:     my %remove;
1.783     albertel  669:     while ( my $envname = each(%env) ) {
1.433     matthew   670:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    671:             if ($time < time-300) {
1.783     albertel  672:                 $remove{$key}++;
1.433     matthew   673:             }
                    674:         }
                    675:     }
1.783     albertel  676: 
1.619     albertel  677:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  678:     $env_loaded=1;
1.783     albertel  679:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   680:         &delenv($expired_key);
1.374     www       681:     }
1.1       albertel  682: }
                    683: 
1.916     albertel  684: # ---------------------------------------------------- Check for valid session 
                    685: sub check_for_valid_session {
1.1172.2.96  raeburn   686:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  687:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108  raeburn   688:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155    raeburn   689:     if ($name eq 'lonDAV') {
                    690:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    691:     } else {
                    692:         $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108  raeburn   693:         if ($name eq '') {
                    694:             $name = 'lonID';
                    695:         }
                    696:     }
                    697:     if ($name eq 'lonID') {
                    698:         $secure = 'lonSID';
                    699:         $linkname = 'lonLinkID';
                    700:         $pubname = 'lonPubID';
                    701:         if (exists($cookies{$secure})) {
                    702:             $lonid=$cookies{$secure};
                    703:         } elsif (exists($cookies{$name})) {
                    704:             $lonid=$cookies{$name};
                    705:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
                    706:             $lonid=$cookies{$linkname};
                    707:         } elsif (exists($cookies{$pubname})) {
                    708:             $lonid=$cookies{$pubname};
                    709:         }
                    710:     } else {
                    711:         $lonid=$cookies{$name};
                    712:     }
                    713:     return undef if (!$lonid);
                    714: 
                    715:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    716:     if (-l "$lonidsdir/$handle.id") {
                    717:         my $link = readlink("$lonidsdir/$handle.id");
                    718:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    719:             $handle = $1;
                    720:         }
1.1155    raeburn   721:     }
1.1172.2.96  raeburn   722:     if (!-e "$lonidsdir/$handle.id") {
                    723:         if ((ref($domref)) && ($name eq 'lonID') &&
                    724:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    725:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    726:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    727:                 $$domref = $possudom;
                    728:             }
                    729:         }
                    730:         return undef;
                    731:     }
1.916     albertel  732: 
1.917     albertel  733:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    734:     return undef if (!$opened);
1.916     albertel  735: 
                    736:     flock($idf,LOCK_SH);
                    737:     my %disk_env;
                    738:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    739: 	    &GDBM_READER(),0640)) {
                    740: 	return undef;	
                    741:     }
                    742: 
                    743:     if (!defined($disk_env{'user.name'})
                    744: 	|| !defined($disk_env{'user.domain'})) {
1.1172.2.107  raeburn   745:         untie(%disk_env);
1.916     albertel  746: 	return undef;
                    747:     }
1.1172.2.18  raeburn   748: 
1.1172.2.36  raeburn   749:     if (ref($userhashref) eq 'HASH') {
                    750:         $userhashref->{'name'} = $disk_env{'user.name'};
                    751:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.142  raeburn   752:         if ($disk_env{'request.role'}) {
                    753:             $userhashref->{'role'} = $disk_env{'request.role'};
                    754:         }
1.1172.2.146.  .13(raeb  755:-23):         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
                    756:-23):         if ($userhashref->{'lti'}) {
                    757:-23):             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
                    758:-23):             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
                    759:-23):         }
1.1172.2.18  raeburn   760:     }
1.1172.2.107  raeburn   761:     untie(%disk_env);
1.1172.2.18  raeburn   762: 
1.916     albertel  763:     return $handle;
                    764: }
                    765: 
1.830     albertel  766: sub timed_flock {
                    767:     my ($file,$lock_type) = @_;
                    768:     my $failed=0;
                    769:     eval {
                    770: 	local $SIG{__DIE__}='DEFAULT';
                    771: 	local $SIG{ALRM}=sub {
                    772: 	    $failed=1;
                    773: 	    die("failed lock");
                    774: 	};
                    775: 	alarm(13);
                    776: 	flock($file,$lock_type);
                    777: 	alarm(0);
                    778:     };
                    779:     if ($failed) {
                    780: 	return undef;
                    781:     } else {
                    782: 	return 1;
                    783:     }
                    784: }
                    785: 
1.1172.2.107  raeburn   786: sub get_sessionfile_vars {
                    787:     my ($handle,$lonidsdir,$storearr) = @_;
                    788:     my %returnhash;
                    789:     unless (ref($storearr) eq 'ARRAY') {
                    790:         return %returnhash;
                    791:     }
                    792:     if (-l "$lonidsdir/$handle.id") {
                    793:         my $link = readlink("$lonidsdir/$handle.id");
                    794:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    795:             $handle = $1;
                    796:         }
                    797:     }
                    798:     if ((-e "$lonidsdir/$handle.id") &&
                    799:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    800:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    801:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    802:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    803:                 flock($idf,LOCK_SH);
                    804:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    805:                         &GDBM_READER(),0640)) {
                    806:                     foreach my $item (@{$storearr}) {
                    807:                         $returnhash{$item} = $disk_env{$item};
                    808:                     }
                    809:                     untie(%disk_env);
                    810:                 }
                    811:             }
                    812:         }
                    813:     }
                    814:     return %returnhash;
                    815: }
                    816: 
1.5       www       817: # ---------------------------------------------------------- Append Environment
                    818: 
                    819: sub appenv {
1.949     raeburn   820:     my ($newenv,$roles) = @_;
                    821:     if (ref($newenv) eq 'HASH') {
                    822:         foreach my $key (keys(%{$newenv})) {
                    823:             my $refused = 0;
                    824: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    825:                 $refused = 1;
                    826:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   827:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   828:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    829:                         $refused = 0;
                    830:                     }
                    831:                 }
                    832:             }
                    833:             if ($refused) {
                    834:                 &logthis("<font color=\"blue\">WARNING: ".
                    835:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    836:                          .'</font>');
                    837: 	        delete($newenv->{$key});
                    838:             } else {
                    839:                 $env{$key}=$newenv->{$key};
                    840:             }
                    841:         }
1.1172.2.96  raeburn   842:         my $lonids = $perlvar{'lonIDsDir'};
                    843:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    844:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    845:             if ($opened
                    846: 	        && &timed_flock($env_file,LOCK_EX)
                    847: 	        &&
                    848: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    849: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    850: 	        while (my ($key,$value) = each(%{$newenv})) {
                    851: 	            $disk_env{$key} = $value;
                    852: 	        }
                    853: 	        untie(%disk_env);
                    854:             }
1.35      www       855:         }
1.191     harris41  856:     }
1.56      www       857:     return 'ok';
                    858: }
                    859: # ----------------------------------------------------- Delete from Environment
                    860: 
                    861: sub delenv {
1.1104    raeburn   862:     my ($delthis,$regexp,$roles) = @_;
                    863:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    864:         my $refused = 1;
                    865:         if (ref($roles) eq 'ARRAY') {
                    866:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    867:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    868:                 $refused = 0;
                    869:             }
                    870:         }
                    871:         if ($refused) {
                    872:             &logthis("<font color=\"blue\">WARNING: ".
                    873:                      "Attempt to delete from environment ".$delthis);
                    874:             return 'error';
                    875:         }
1.56      www       876:     }
1.917     albertel  877:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    878:     if ($opened
1.915     albertel  879: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  880: 	&&
                    881: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    882: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  883: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   884: 	    if ($regexp) {
                    885:                 if ($key=~/^$delthis/) {
                    886:                     delete($env{$key});
                    887:                     delete($disk_env{$key});
                    888:                 } 
                    889:             } else {
                    890:                 if ($key=~/^\Q$delthis\E/) {
                    891: 		    delete($env{$key});
                    892: 		    delete($disk_env{$key});
                    893: 	        }
                    894:             }
1.448     albertel  895: 	}
1.783     albertel  896: 	untie(%disk_env);
1.5       www       897:     }
                    898:     return 'ok';
1.369     albertel  899: }
                    900: 
1.790     albertel  901: sub get_env_multiple {
                    902:     my ($name) = @_;
                    903:     my @values;
                    904:     if (defined($env{$name})) {
                    905:         # exists is it an array
                    906:         if (ref($env{$name})) {
                    907:             @values=@{ $env{$name} };
                    908:         } else {
                    909:             $values[0]=$env{$name};
                    910:         }
                    911:     }
                    912:     return(@values);
                    913: }
                    914: 
1.958     www       915: # ------------------------------------------------------------------- Locking
                    916: 
                    917: sub set_lock {
                    918:     my ($text)=@_;
                    919:     $locknum++;
                    920:     my $id=$$.'-'.$locknum;
                    921:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    922:              'session.lock.'.$id => $text});
                    923:     return $id;
                    924: }
                    925: 
                    926: sub get_locks {
                    927:     my $num=0;
                    928:     my %texts=();
                    929:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    930:        if ($lock=~/\w/) {
                    931:           $num++;
                    932:           $texts{$lock}=$env{'session.lock.'.$lock};
                    933:        }
                    934:    }
                    935:    return ($num,%texts);
                    936: }
                    937: 
                    938: sub remove_lock {
                    939:     my ($id)=@_;
                    940:     my $newlocks='';
                    941:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    942:        if (($lock=~/\w/) && ($lock ne $id)) {
                    943:           $newlocks.=','.$lock;
                    944:        }
                    945:     }
                    946:     &appenv({'session.locks' => $newlocks});
                    947:     &delenv('session.lock.'.$id);
                    948: }
                    949: 
                    950: sub remove_all_locks {
                    951:     my $activelocks=$env{'session.locks'};
                    952:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    953:        if ($lock=~/\w/) {
                    954:           &remove_lock($lock);
                    955:        }
                    956:     }
                    957: }
                    958: 
                    959: 
1.369     albertel  960: # ------------------------------------------ Find out current server userload
                    961: sub userload {
                    962:     my $numusers=0;
                    963:     {
                    964: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    965: 	my $filename;
                    966: 	my $curtime=time;
                    967: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  968: 	    next if ($filename eq '.' || $filename eq '..');
                    969: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112  raeburn   970:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  971: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  972: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  973: 	}
                    974: 	closedir(LONIDS);
                    975:     }
                    976:     my $userloadpercent=0;
                    977:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    978:     if ($maxuserload) {
1.371     albertel  979: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  980:     }
1.372     albertel  981:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  982:     return $userloadpercent;
1.283     www       983: }
                    984: 
1.1       albertel  985: # ------------------------------ Find server with least workload from spare.tab
1.11      www       986: 
1.1       albertel  987: sub spareserver {
1.1172.2.142  raeburn   988:     my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  989:     my $spare_server;
1.370     albertel  990:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  991:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    992:                                                      :  $userloadpercent;
1.1083    raeburn   993:     my ($uint_dom,$remotesessions);
                    994:     if (($udom ne '') && (&domain($udom) ne '')) {
                    995:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    996:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    997:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    998:         $remotesessions = $udomdefaults{'remotesessions'};
                    999:     }
1.1123    raeburn  1000:     my $spareshash = &this_host_spares($udom);
                   1001:     if (ref($spareshash) eq 'HASH') {
                   1002:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1003:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn  1004:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                   1005:                                              $try_server));
1.1123    raeburn  1006: 	        ($spare_server, $lowest_load) =
                   1007: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                   1008:             }
1.1083    raeburn  1009:         }
1.784     albertel 1010: 
1.1123    raeburn  1011:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                   1012: 
                   1013:         if (!$found_server) {
                   1014:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                   1015: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn  1016:                     next unless (&spare_can_host($udom,$uint_dom,
                   1017:                                                  $remotesessions,$try_server));
1.1123    raeburn  1018: 	            ($spare_server, $lowest_load) =
                   1019: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                   1020:                 }
                   1021: 	    }
                   1022:         }
1.784     albertel 1023:     }
                   1024: 
                   1025:     if (!$want_server_name) {
1.1001    raeburn  1026:         if (defined($spare_server)) {
                   1027:             my $hostname = &hostname($spare_server);
1.1083    raeburn  1028:             if (defined($hostname)) {
1.1172.2.120  raeburn  1029:                 my $protocol = 'http';
                   1030:                 if ($protocol{$spare_server} eq 'https') {
                   1031:                     $protocol = $protocol{$spare_server};
                   1032:                 }
1.1172.2.142  raeburn  1033:                 my $alias = &Apache::lonnet::use_proxy_alias($r,$spare_server);
                   1034:                 $hostname = $alias if ($alias ne '');
1.1001    raeburn  1035: 	        $spare_server = $protocol.'://'.$hostname;
                   1036:             }
                   1037:         }
1.784     albertel 1038:     }
                   1039:     return $spare_server;
                   1040: }
                   1041: 
                   1042: sub compare_server_load {
1.1172.2.41  raeburn  1043:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                   1044: 
                   1045:     if ($required) {
                   1046:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   1047:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1048:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   1049:         if (($major eq '' && $minor eq '') ||
                   1050:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   1051:             return ($spare_server,$lowest_load);
                   1052:         }
                   1053:     }
1.784     albertel 1054: 
                   1055:     my $loadans     = &reply('load',    $try_server);
                   1056:     my $userloadans = &reply('userload',$try_server);
                   1057: 
                   1058:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn  1059: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel 1060:     }
                   1061: 
                   1062:     my $load;
                   1063:     if ($loadans =~ /\d/) {
                   1064: 	if ($userloadans =~ /\d/) {
                   1065: 	    #both are numbers, pick the bigger one
                   1066: 	    $load = ($loadans > $userloadans) ? $loadans 
                   1067: 		                              : $userloadans;
1.411     albertel 1068: 	} else {
1.784     albertel 1069: 	    $load = $loadans;
1.411     albertel 1070: 	}
1.784     albertel 1071:     } else {
                   1072: 	$load = $userloadans;
                   1073:     }
                   1074: 
                   1075:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1076: 	$spare_server = $try_server;
                   1077: 	$lowest_load  = $load;
1.370     albertel 1078:     }
1.784     albertel 1079:     return ($spare_server,$lowest_load);
1.202     matthew  1080: }
1.914     albertel 1081: 
                   1082: # --------------------------- ask offload servers if user already has a session
                   1083: sub find_existing_session {
                   1084:     my ($udom,$uname) = @_;
1.1123    raeburn  1085:     my $spareshash = &this_host_spares($udom);
                   1086:     if (ref($spareshash) eq 'HASH') {
                   1087:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1088:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1089:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1090:             }
                   1091:         }
                   1092:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1093:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1094:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1095:             }
                   1096:         }
1.914     albertel 1097:     }
                   1098:     return;
                   1099: }
                   1100: 
1.1172.2.146.  .13(raeb 1101:-23): sub delusersession {
                   1102:-23):     my ($lonid,$udom,$uname) = @_;
                   1103:-23):     my $uprimary_id = &domain($udom,'primary');
                   1104:-23):     my $uintdom = &internet_dom($uprimary_id);
                   1105:-23):     my $intdom = &internet_dom($lonid);
                   1106:-23):     my $serverhomedom = &host_domain($lonid);
                   1107:-23):     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1108:-23):         return &reply(join(':','delusersession',
                   1109:-23):                             map {&escape($_)} ($udom,$uname)),$lonid);
                   1110:-23):     }
                   1111:-23):     return;
                   1112:-23): }
                   1113:-23): 
                   1114:-23): 
1.1172.2.107  raeburn  1115: # check if user's browser sent load balancer cookie and server still has session
                   1116: # and is not overloaded.
                   1117: sub check_for_balancer_cookie {
                   1118:     my ($r,$update_mtime) = @_;
                   1119:     my ($otherserver,$cookie);
                   1120:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1121:     if (exists($cookies{'balanceID'})) {
                   1122:         my $balid = $cookies{'balanceID'};
                   1123:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1124:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1125:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1126:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1127:                 my ($possudom,$possuname) = ($1,$2);
                   1128:                 my $has_session = 0;
                   1129:                 if ((&domain($possudom) ne '') &&
                   1130:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1131:                     my $try_server;
                   1132:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1133:                     if ($opened) {
                   1134:                         flock($idf,LOCK_SH);
                   1135:                         while (my $line = <$idf>) {
                   1136:                             chomp($line);
                   1137:                             if (&hostname($line) ne '') {
                   1138:                                 $try_server = $line;
                   1139:                                 last;
                   1140:                             }
                   1141:                         }
                   1142:                         close($idf);
                   1143:                         if (($try_server) &&
                   1144:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1145:                             my $lowest_load = 30000;
                   1146:                             ($otherserver,$lowest_load) =
                   1147:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1148:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1149:                                 $has_session = 1;
                   1150:                             } else {
                   1151:                                 undef($otherserver);
                   1152:                             }
                   1153:                         }
                   1154:                     }
                   1155:                 }
                   1156:                 if ($has_session) {
                   1157:                     if ($update_mtime) {
                   1158:                         my $atime = my $mtime = time;
                   1159:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1160:                     }
                   1161:                 } else {
                   1162:                     unlink("$balancedir/$cookie.id");
                   1163:                 }
                   1164:             }
                   1165:         }
                   1166:     }
                   1167:     return ($otherserver,$cookie);
                   1168: }
                   1169: 
1.1172.2.130  raeburn  1170: sub updatebalcookie {
                   1171:     my ($cookie,$balancer,$lastentry)=@_;
                   1172:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1173:         my ($udom,$uname) = ($1,$2);
                   1174:         my $uprimary_id = &domain($udom,'primary');
                   1175:         my $uintdom = &internet_dom($uprimary_id);
                   1176:         my $intdom = &internet_dom($balancer);
                   1177:         my $serverhomedom = &host_domain($balancer);
                   1178:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1179:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
                   1180:         }
                   1181:     }
                   1182:     return;
                   1183: }
                   1184: 
1.1172.2.107  raeburn  1185: sub delbalcookie {
                   1186:     my ($cookie,$balancer) =@_;
                   1187:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1188:         my ($udom,$uname) = ($1,$2);
                   1189:         my $uprimary_id = &domain($udom,'primary');
                   1190:         my $uintdom = &internet_dom($uprimary_id);
                   1191:         my $intdom = &internet_dom($balancer);
                   1192:         my $serverhomedom = &host_domain($balancer);
                   1193:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1172.2.130  raeburn  1194:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1172.2.107  raeburn  1195:         }
                   1196:     }
                   1197: }
                   1198: 
1.914     albertel 1199: # -------------------------------- ask if server already has a session for user
                   1200: sub has_user_session {
                   1201:     my ($lonid,$udom,$uname) = @_;
                   1202:     my $result = &reply(join(':','userhassession',
                   1203: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1204:     return 1 if ($result eq 'ok');
                   1205: 
                   1206:     return 0;
                   1207: }
                   1208: 
1.1076    raeburn  1209: # --------- determine least loaded server in a user's domain which allows login
                   1210: 
                   1211: sub choose_server {
1.1172.2.47  raeburn  1212:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1213:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1214:     my %servers = &get_servers($udom);
1.1076    raeburn  1215:     my $lowest_load = 30000;
1.1172.2.47  raeburn  1216:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1217:     if ($skiploadbal) {
                   1218:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1219:         unless (defined($cached)) {
                   1220:             my $cachetime = 60*60*24;
                   1221:             my %domconfig =
                   1222:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1223:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1224:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1225:                                            $cachetime);
                   1226:             }
                   1227:         }
                   1228:     }
1.1076    raeburn  1229:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn  1230:         my $loginvia;
1.1172.2.47  raeburn  1231:         if ($skiploadbal) {
                   1232:             if (ref($balancers) eq 'HASH') {
                   1233:                 next if (exists($balancers->{$lonhost}));
                   1234:             }
                   1235:         }
1.1115    raeburn  1236:         if ($checkloginvia) {
                   1237:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1238:             if ($loginvia) {
                   1239:                 my ($server,$path) = split(/:/,$loginvia);
                   1240:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1241:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1242:                 if ($login_host eq $server) {
                   1243:                     $portal_path = $path;
1.1151    raeburn  1244:                     $isredirect = 1;
1.1116    raeburn  1245:                 }
                   1246:             } else {
                   1247:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1248:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1249:                 if ($login_host eq $lonhost) {
                   1250:                     $portal_path = '';
1.1151    raeburn  1251:                     $isredirect = ''; 
1.1116    raeburn  1252:                 }
                   1253:             }
                   1254:         } else {
1.1076    raeburn  1255:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1256:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1257:         }
                   1258:     }
                   1259:     if ($login_host ne '') {
1.1116    raeburn  1260:         $hostname = &hostname($login_host);
1.1076    raeburn  1261:     }
1.1172.2.88  raeburn  1262:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1263: }
                   1264: 
1.1172.2.123  raeburn  1265: sub get_course_sessions {
                   1266:     my ($cnum,$cdom,$lastactivity) = @_;
                   1267:     my %servers = &internet_dom_servers($cdom);
                   1268:     my %returnhash;
                   1269:     foreach my $server (sort(keys(%servers))) {
                   1270:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1271:         my @pairs=split(/\&/,$rep);
                   1272:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1273:             foreach my $item (@pairs) {
                   1274:                 my ($key,$value)=split(/=/,$item,2);
                   1275:                 $key = &unescape($key);
                   1276:                 next if ($key =~ /^error: 2 /);
                   1277:                 if (exists($returnhash{$key})) {
                   1278:                     next if ($value < $returnhash{$key});
                   1279:                 }
                   1280:                 $returnhash{$key}=$value;
                   1281:             }
                   1282:         }
                   1283:     }
                   1284:     return %returnhash;
                   1285: }
                   1286: 
1.202     matthew  1287: # --------------------------------------------- Try to change a user's password
                   1288: 
                   1289: sub changepass {
1.799     raeburn  1290:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1291:     $currentpass = &escape($currentpass);
                   1292:     $newpass     = &escape($newpass);
1.1030    raeburn  1293:     my $lonhost = $perlvar{'lonHostID'};
                   1294:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1295: 		       $server);
                   1296:     if (! $answer) {
                   1297: 	&logthis("No reply on password change request to $server ".
                   1298: 		 "by $uname in domain $udom.");
                   1299:     } elsif ($answer =~ "^ok") {
                   1300:         &logthis("$uname in $udom successfully changed their password ".
                   1301: 		 "on $server.");
                   1302:     } elsif ($answer =~ "^pwchange_failure") {
                   1303: 	&logthis("$uname in $udom was unable to change their password ".
                   1304: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1305: 		 "or pwchange");
                   1306:     } elsif ($answer =~ "^non_authorized") {
                   1307:         &logthis("$uname in $udom did not get their password correct when ".
                   1308: 		 "attempting to change it on $server.");
                   1309:     } elsif ($answer =~ "^auth_mode_error") {
                   1310:         &logthis("$uname in $udom attempted to change their password despite ".
                   1311: 		 "not being locally or internally authenticated on $server.");
                   1312:     } elsif ($answer =~ "^unknown_user") {
                   1313:         &logthis("$uname in $udom attempted to change their password ".
                   1314: 		 "on $server but were unable to because $server is not ".
                   1315: 		 "their home server.");
                   1316:     } elsif ($answer =~ "^refused") {
                   1317: 	&logthis("$server refused to change $uname in $udom password because ".
                   1318: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1319:     } elsif ($answer =~ "invalid_client") {
                   1320:         &logthis("$server refused to change $uname in $udom password because ".
                   1321:                  "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113  raeburn  1322:     } elsif ($answer =~ "^prioruse") {
                   1323:        &logthis("$server refused to change $uname in $udom password because ".
                   1324:                 "the password had been used before");
1.202     matthew  1325:     }
                   1326:     return $answer;
1.1       albertel 1327: }
                   1328: 
1.169     harris41 1329: # ----------------------- Try to determine user's current authentication scheme
                   1330: 
                   1331: sub queryauthenticate {
                   1332:     my ($uname,$udom)=@_;
1.456     albertel 1333:     my $uhome=&homeserver($uname,$udom);
1.1172.2.146.  .5(raebu 1334:22):     if ((!$uhome) || ($uhome eq 'no_host')) {
1.456     albertel 1335: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1336: 	return 'no_host';
                   1337:     }
                   1338:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1339:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1340: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1341:     }
1.456     albertel 1342:     return $answer;
1.169     harris41 1343: }
                   1344: 
1.1       albertel 1345: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1346: 
1.1       albertel 1347: sub authenticate {
1.1073    raeburn  1348:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1349:     $upass=&escape($upass);
                   1350:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1351:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1352:     my $newhome;
1.836     www      1353:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1354: # Maybe the machine was offline and only re-appeared again recently?
                   1355:         &reconlonc();
                   1356: # One more
1.952     raeburn  1357: 	$uhome=&homeserver($uname,$udom,1);
                   1358:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1359:             if (defined(&domain($udom,'primary'))) {
                   1360:                 $newhome=&domain($udom,'primary');
                   1361:             }
                   1362:             if ($newhome ne '') {
                   1363:                 $uhome = $newhome;
                   1364:             }
                   1365:         }
1.836     www      1366: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1367: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1368: 	    return 'no_host';
                   1369:         }
1.1       albertel 1370:     }
1.1073    raeburn  1371:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1372:     if ($answer eq 'authorized') {
1.952     raeburn  1373:         if ($newhome) {
                   1374:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1375:             return 'no_account_on_host'; 
                   1376:         } else {
                   1377:             &logthis("User $uname at $udom authorized by $uhome");
                   1378:             return $uhome;
                   1379:         }
1.471     albertel 1380:     }
                   1381:     if ($answer eq 'non_authorized') {
                   1382: 	&logthis("User $uname at $udom rejected by $uhome");
1.1172.2.146.  .5(raebu 1383:22): 	return 'no_host';
1.9       www      1384:     }
1.471     albertel 1385:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1386:     return 'no_host';
                   1387: }
                   1388: 
1.1172.2.146.  .6(raebu 1389:22): sub can_switchserver {
                   1390:22):     my ($udom,$home) = @_;
                   1391:22):     my ($canswitch,@intdoms);
                   1392:22):     my $internet_names = &get_internet_names($home);
                   1393:22):     if (ref($internet_names) eq 'ARRAY') {
                   1394:22):         @intdoms = @{$internet_names};
                   1395:22):     }
                   1396:22):     my $uint_dom = &internet_dom(&domain($udom,'primary'));
                   1397:22):     if ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1398:22):         $canswitch = 1;
                   1399:22):     } else {
                   1400:22):          my $serverhomeID = &get_server_homeID(&hostname($home));
                   1401:22):          my $serverhomedom = &host_domain($serverhomeID);
                   1402:22):          my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1403:22):          my %udomdefaults = &get_domain_defaults($udom);
                   1404:22):          my $remoterev = &get_server_loncaparev('',$home);
                   1405:22):          $canswitch = &can_host_session($udom,$home,$remoterev,
                   1406:22):                                         $udomdefaults{'remotesessions'},
                   1407:22):                                         $defdomdefaults{'hostedsessions'});
                   1408:22):     }
                   1409:22):     return $canswitch;
                   1410:22): }
                   1411:22): 
1.1073    raeburn  1412: sub can_host_session {
1.1074    raeburn  1413:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1414:     my $canhost = 1;
1.1074    raeburn  1415:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1416:     if (ref($remotesessions) eq 'HASH') {
                   1417:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1418:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1419:                 $canhost = 0;
                   1420:             } else {
                   1421:                 $canhost = 1;
                   1422:             }
                   1423:         }
                   1424:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1425:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1426:                 $canhost = 1;
                   1427:             } else {
                   1428:                 $canhost = 0;
                   1429:             }
                   1430:         }
                   1431:         if ($canhost) {
                   1432:             if ($remotesessions->{'version'} ne '') {
                   1433:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1434:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1435:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1436:                         my $major = $1;
                   1437:                         my $minor = $2;
                   1438:                         if (($major < $reqmajor ) ||
                   1439:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1440:                             $canhost = 0;
                   1441:                         }
                   1442:                     } else {
                   1443:                         $canhost = 0;
                   1444:                     }
                   1445:                 }
                   1446:             }
                   1447:         }
                   1448:     }
                   1449:     if ($canhost) {
                   1450:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1451:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1452:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1453:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1454:                 if (($uint_dom ne '') && 
                   1455:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1456:                     $canhost = 0;
                   1457:                 } else {
                   1458:                     $canhost = 1;
                   1459:                 }
                   1460:             }
                   1461:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1462:                 if (($uint_dom ne '') && 
                   1463:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1464:                     $canhost = 1;
                   1465:                 } else {
                   1466:                     $canhost = 0;
                   1467:                 }
                   1468:             }
                   1469:         }
                   1470:     }
                   1471:     return $canhost;
                   1472: }
                   1473: 
1.1083    raeburn  1474: sub spare_can_host {
                   1475:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1476:     my $canhost=1;
1.1172.2.62  raeburn  1477:     my $try_server_hostname = &hostname($try_server);
                   1478:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1479:     my $serverhomedom = &host_domain($serverhomeID);
                   1480:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1481:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1482:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1483:             $canhost = 0;
                   1484:         }
                   1485:     }
1.1172.2.136  raeburn  1486:     if ($canhost) {
                   1487:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
                   1488:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
                   1489:                 unless (&shared_institution($udom,$try_server)) {
                   1490:                     $canhost = 0;
                   1491:                 }
                   1492:             }
                   1493:         }
                   1494:     }
1.1172.2.62  raeburn  1495:     if (($canhost) && ($uint_dom)) {
                   1496:         my @intdoms;
                   1497:         my $internet_names = &get_internet_names($try_server);
                   1498:         if (ref($internet_names) eq 'ARRAY') {
                   1499:             @intdoms = @{$internet_names};
                   1500:         }
                   1501:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1502:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1503:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1504:                                          $remotesessions,
                   1505:                                          $defdomdefaults{'hostedsessions'});
                   1506:         }
1.1083    raeburn  1507:     }
                   1508:     return $canhost;
                   1509: }
                   1510: 
1.1123    raeburn  1511: sub this_host_spares {
                   1512:     my ($dom) = @_;
1.1126    raeburn  1513:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1514:     my @hosts = &current_machine_ids();
                   1515:     foreach my $lonhost (@hosts) {
                   1516:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1517:             $dom_in_use = $dom;
                   1518:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1519:             last;
                   1520:         }
                   1521:     }
1.1126    raeburn  1522:     if ($dom_in_use ne '') {
                   1523:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1524:     }
                   1525:     if (ref($result) ne 'HASH') {
                   1526:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1527:         $dom_in_use = &host_domain($lonhost_in_use);
                   1528:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1529:         if (ref($result) ne 'HASH') {
                   1530:             $result = \%spareid;
                   1531:         }
                   1532:     }
                   1533:     return $result;
                   1534: }
                   1535: 
                   1536: sub spares_for_offload  {
                   1537:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1538:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1539:     if (defined($cached)) {
                   1540:         return $result;
                   1541:     } else {
1.1126    raeburn  1542:         my $cachetime = 60*60*24;
                   1543:         my %domconfig =
                   1544:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1545:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1546:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1547:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1548:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1549:                 }
                   1550:             }
                   1551:         }
                   1552:     }
1.1126    raeburn  1553:     return;
1.1123    raeburn  1554: }
                   1555: 
1.1129    raeburn  1556: sub get_lonbalancer_config {
                   1557:     my ($servers) = @_;
                   1558:     my ($currbalancer,$currtargets);
                   1559:     if (ref($servers) eq 'HASH') {
                   1560:         foreach my $server (keys(%{$servers})) {
                   1561:             my %what = (
                   1562:                          spareid => 1,
                   1563:                          perlvar => 1,
                   1564:                        );
                   1565:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1566:             if ($result eq 'ok') {
                   1567:                 if (ref($returnhash) eq 'HASH') {
                   1568:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1569:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1570:                             $currbalancer = $server;
                   1571:                             $currtargets = {};
                   1572:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1573:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1574:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1575:                                 }
                   1576:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1577:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1578:                                 }
                   1579:                             }
                   1580:                             last;
                   1581:                         }
                   1582:                     }
                   1583:                 }
                   1584:             }
                   1585:         }
                   1586:     }
                   1587:     return ($currbalancer,$currtargets);
                   1588: }
                   1589: 
                   1590: sub check_loadbalancing {
1.1172.2.88  raeburn  1591:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1592:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1593:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1594:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1595:     my @hosts = &current_machine_ids();
1.1129    raeburn  1596:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1597:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1598:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1599:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1600:     my $domneedscache; 
1.1129    raeburn  1601:     my $cachetime = 60*60*24;
                   1602: 
                   1603:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1604:         $dom_in_use = $udom;
                   1605:         $homeintdom = 1;
                   1606:     } else {
                   1607:         $dom_in_use = $serverhomedom;
                   1608:     }
                   1609:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1610:     unless (defined($cached)) {
                   1611:         my %domconfig =
                   1612:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1613:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1614:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1615:         } else {
                   1616:             $domneedscache = $dom_in_use;
1.1129    raeburn  1617:         }
                   1618:     }
                   1619:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1620:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1621:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1622:         if ($is_balancer) {
                   1623:             if (ref($currrules) eq 'HASH') {
                   1624:                 if ($homeintdom) {
                   1625:                     if ($uname ne '') {
                   1626:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1627:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1628:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1629:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1630:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1631:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1632:                             }
                   1633:                         }
                   1634:                         if ($rule_in_effect eq '') {
                   1635:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1636:                             if ($userenv{'inststatus'} ne '') {
                   1637:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1638:                                 my ($othertitle,$usertypes,$types) =
                   1639:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1640:                                 if (ref($types) eq 'ARRAY') {
                   1641:                                     foreach my $type (@{$types}) {
                   1642:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1643:                                             if (exists($currrules->{$type})) {
                   1644:                                                 $rule_in_effect = $currrules->{$type};
                   1645:                                             }
                   1646:                                         }
                   1647:                                     }
                   1648:                                 }
                   1649:                             } else {
                   1650:                                 if (exists($currrules->{'default'})) {
                   1651:                                     $rule_in_effect = $currrules->{'default'};
                   1652:                                 }
                   1653:                             }
                   1654:                         }
                   1655:                     } else {
                   1656:                         if (exists($currrules->{'default'})) {
                   1657:                             $rule_in_effect = $currrules->{'default'};
                   1658:                         }
                   1659:                     }
                   1660:                 } else {
                   1661:                     if ($currrules->{'_LC_external'} ne '') {
                   1662:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1663:                     }
                   1664:                 }
                   1665:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1666:                                                        $uname,$udom);
                   1667:             }
                   1668:         }
                   1669:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1670:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1671:         unless (defined($cached)) {
                   1672:             my %domconfig =
                   1673:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1674:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1675:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1676:             } else {
                   1677:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1678:             }
                   1679:         }
                   1680:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1681:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1682:                 &check_balancer_result($result,@hosts);
                   1683:             if ($is_balancer) {
1.1129    raeburn  1684:                 if (ref($currrules) eq 'HASH') {
                   1685:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1686:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1687:                     }
                   1688:                 }
                   1689:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1690:                                                        $uname,$udom);
                   1691:             }
                   1692:         } else {
                   1693:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1694:                 $is_balancer = 1;
                   1695:                 $offloadto = &this_host_spares($dom_in_use);
                   1696:             }
1.1172.2.75  raeburn  1697:             unless (defined($cached)) {
                   1698:                 $domneedscache = $serverhomedom;
                   1699:             }
1.1129    raeburn  1700:         }
                   1701:     } else {
                   1702:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1703:             $is_balancer = 1;
                   1704:             $offloadto = &this_host_spares($dom_in_use);
                   1705:         }
1.1172.2.75  raeburn  1706:         unless (defined($cached)) {
                   1707:             $domneedscache = $serverhomedom;
                   1708:         }
                   1709:     }
                   1710:     if ($domneedscache) {
                   1711:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1712:     }
1.1172.2.130  raeburn  1713:     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1172.2.5  raeburn  1714:         my $lowest_load = 30000;
                   1715:         if (ref($offloadto) eq 'HASH') {
                   1716:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1717:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1718:                     ($otherserver,$lowest_load) =
                   1719:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1720:                 }
1.1129    raeburn  1721:             }
1.1172.2.5  raeburn  1722:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1723: 
1.1172.2.5  raeburn  1724:             if (!$found_server) {
                   1725:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1726:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1727:                         ($otherserver,$lowest_load) =
                   1728:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1729:                     }
                   1730:                 }
                   1731:             }
                   1732:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1733:             if (@{$offloadto} == 1) {
                   1734:                 $otherserver = $offloadto->[0];
                   1735:             } elsif (@{$offloadto} > 1) {
                   1736:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1737:                     ($otherserver,$lowest_load) =
                   1738:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1739:                 }
                   1740:             }
                   1741:         }
1.1172.2.88  raeburn  1742:         unless ($caller eq 'login') {
                   1743:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1744:                 $is_balancer = 0;
                   1745:                 if ($uname ne '' && $udom ne '') {
                   1746:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1747:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1748:                                  'user.loadbalcheck.time' => time});
                   1749:                     }
1.1172.2.5  raeburn  1750:                 }
1.1129    raeburn  1751:             }
                   1752:         }
1.1172.2.130  raeburn  1753:     }
                   1754:     if (($is_balancer) && (!$homeintdom)) {
                   1755:         undef($setcookie);
1.1129    raeburn  1756:     }
1.1172.2.107  raeburn  1757:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1758: }
                   1759: 
1.1172.2.12  raeburn  1760: sub check_balancer_result {
                   1761:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1762:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1763:     if (ref($result) eq 'HASH') {
                   1764:         if ($result->{'lonhost'} ne '') {
                   1765:             my $currbalancer = $result->{'lonhost'};
                   1766:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1767:                 $is_balancer = 1;
                   1768:                 $currtargets = $result->{'targets'};
                   1769:                 $currrules = $result->{'rules'};
                   1770:             }
                   1771:         } else {
                   1772:             foreach my $key (keys(%{$result})) {
                   1773:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1774:                     (ref($result->{$key}) eq 'HASH')) {
                   1775:                     $is_balancer = 1;
                   1776:                     $currrules = $result->{$key}{'rules'};
                   1777:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1778:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1779:                     last;
                   1780:                 }
                   1781:             }
                   1782:         }
                   1783:     }
1.1172.2.107  raeburn  1784:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1785: }
                   1786: 
1.1129    raeburn  1787: sub get_loadbalancer_targets {
                   1788:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1789:     my $offloadto;
1.1172.2.4  raeburn  1790:     if ($rule_in_effect eq 'none') {
                   1791:         return [$perlvar{'lonHostID'}];
                   1792:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1793:         $offloadto = $currtargets;
                   1794:     } else {
                   1795:         if ($rule_in_effect eq 'homeserver') {
                   1796:             my $homeserver = &homeserver($uname,$udom);
                   1797:             if ($homeserver ne 'no_host') {
                   1798:                 $offloadto = [$homeserver];
                   1799:             }
                   1800:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1801:             my %domconfig =
                   1802:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1803:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1804:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1805:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1806:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1807:                     }
                   1808:                 }
                   1809:             } else {
1.1172.2.7  raeburn  1810:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1811:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1812:                 if (&hostname($remotebalancer) ne '') {
                   1813:                     $offloadto = [$remotebalancer];
                   1814:                 }
                   1815:             }
                   1816:         } elsif (&hostname($rule_in_effect) ne '') {
                   1817:             $offloadto = [$rule_in_effect];
                   1818:         }
                   1819:     }
                   1820:     return $offloadto;
                   1821: }
                   1822: 
1.1127    raeburn  1823: sub internet_dom_servers {
                   1824:     my ($dom) = @_;
                   1825:     my (%uniqservers,%servers);
                   1826:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1827:     my @machinedoms = &machine_domains($primaryserver);
                   1828:     foreach my $mdom (@machinedoms) {
                   1829:         my %currservers = %servers;
                   1830:         my %server = &get_servers($mdom);
                   1831:         %servers = (%currservers,%server);
                   1832:     }
                   1833:     my %by_hostname;
                   1834:     foreach my $id (keys(%servers)) {
                   1835:         push(@{$by_hostname{$servers{$id}}},$id);
                   1836:     }
                   1837:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1838:         if (@{$by_hostname{$hostname}} > 1) {
                   1839:             my $match = 0;
                   1840:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1841:                 if (&host_domain($id) eq $dom) {
                   1842:                     $uniqservers{$id} = $hostname;
                   1843:                     $match = 1;
                   1844:                 }
                   1845:             }
                   1846:             unless ($match) {
                   1847:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1848:             }
                   1849:         } else {
                   1850:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1851:         }
                   1852:     }
                   1853:     return %uniqservers;
                   1854: }
                   1855: 
1.1       albertel 1856: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1857: 
1.599     albertel 1858: my %homecache;
1.1       albertel 1859: sub homeserver {
1.230     stredwic 1860:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1861:     my $index="$uname:$udom";
1.426     albertel 1862: 
1.599     albertel 1863:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1864: 
                   1865:     my %servers = &get_servers($udom,'library');
                   1866:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1867:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1868: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1869: 
                   1870: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1871: 	if ($answer eq 'found') {
                   1872: 	    delete($badServerCache{$tryserver}); 
                   1873: 	    return $homecache{$index}=$tryserver;
                   1874: 	} elsif ($answer eq 'no_host') {
                   1875: 	    $badServerCache{$tryserver}=1;
                   1876: 	}
1.1       albertel 1877:     }    
                   1878:     return 'no_host';
1.70      www      1879: }
                   1880: 
                   1881: # ------------------------------------- Find the usernames behind a list of IDs
                   1882: 
                   1883: sub idget {
                   1884:     my ($udom,@ids)=@_;
                   1885:     my %returnhash=();
                   1886:     
1.841     albertel 1887:     my %servers = &get_servers($udom,'library');
                   1888:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1889: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1890: 	$idlist=~tr/A-Z/a-z/; 
                   1891: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1892: 	my @answer=();
                   1893: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1894: 	    @answer=split(/\&/,$reply);
                   1895: 	}                    ;
                   1896: 	my $i;
                   1897: 	for ($i=0;$i<=$#ids;$i++) {
                   1898: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1899: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1900: 	    } 
                   1901: 	}
                   1902:     } 
1.70      www      1903:     return %returnhash;
                   1904: }
                   1905: 
                   1906: # ------------------------------------- Find the IDs behind a list of usernames
                   1907: 
                   1908: sub idrget {
                   1909:     my ($udom,@unames)=@_;
                   1910:     my %returnhash=();
1.800     albertel 1911:     foreach my $uname (@unames) {
                   1912:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1913:     }
1.70      www      1914:     return %returnhash;
                   1915: }
                   1916: 
                   1917: # ------------------------------- Store away a list of names and associated IDs
                   1918: 
                   1919: sub idput {
                   1920:     my ($udom,%ids)=@_;
                   1921:     my %servers=();
1.800     albertel 1922:     foreach my $uname (keys(%ids)) {
                   1923: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1924:         my $uhom=&homeserver($uname,$udom);
1.70      www      1925:         if ($uhom ne 'no_host') {
1.800     albertel 1926:             my $id=&escape($ids{$uname});
1.70      www      1927:             $id=~tr/A-Z/a-z/;
1.800     albertel 1928:             my $esc_unam=&escape($uname);
1.70      www      1929: 	    if ($servers{$uhom}) {
1.800     albertel 1930: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1931:             } else {
1.800     albertel 1932:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1933:             }
                   1934:         }
1.191     harris41 1935:     }
1.800     albertel 1936:     foreach my $server (keys(%servers)) {
                   1937:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1938:     }
1.344     www      1939: }
                   1940: 
1.1172.2.30  raeburn  1941: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1942: 
                   1943: sub iddel {
                   1944:     my ($udom,$idshashref,$uhome)=@_;
                   1945:     my %result=();
                   1946:     unless (ref($idshashref) eq 'HASH') {
                   1947:         return %result;
                   1948:     }
                   1949:     my %servers=();
                   1950:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1951:         my $uhom;
                   1952:         if ($uhome) {
                   1953:             $uhom = $uhome;
                   1954:         } else {
                   1955:             $uhom=&homeserver($uname,$udom);
                   1956:         }
                   1957:         if ($uhom ne 'no_host') {
                   1958:             if ($servers{$uhom}) {
                   1959:                 $servers{$uhom}.='&'.&escape($id);
                   1960:             } else {
                   1961:                 $servers{$uhom}=&escape($id);
                   1962:             }
                   1963:         }
                   1964:     }
                   1965:     foreach my $server (keys(%servers)) {
                   1966:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1967:     }
                   1968:     return %result;
                   1969: }
                   1970: 
1.1023    raeburn  1971: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1972: sub dump_dom {
1.1165    droeschl 1973:     my ($namespace, $udom, $regexp) = @_;
                   1974: 
                   1975:     $udom ||= $env{'user.domain'};
                   1976: 
                   1977:     return () unless $udom;
                   1978: 
                   1979:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1980: }
                   1981: 
1.1023    raeburn  1982: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1983: 
                   1984: sub get_dom {
1.1172.2.146.  .1(raebu 1985:22):     my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
1.1172.2.57  raeburn  1986:     return if ($udom eq 'public');
1.806     raeburn  1987:     my $items='';
                   1988:     foreach my $item (@$storearr) {
                   1989:         $items.=&escape($item).'&';
                   1990:     }
                   1991:     $items=~s/\&$//;
1.860     raeburn  1992:     if (!$udom) {
                   1993:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1994:         return if ($udom eq 'public');
1.860     raeburn  1995:         if (defined(&domain($udom,'primary'))) {
                   1996:             $uhome=&domain($udom,'primary');
                   1997:         } else {
1.874     albertel 1998:             undef($uhome);
1.860     raeburn  1999:         }
                   2000:     } else {
                   2001:         if (!$uhome) {
                   2002:             if (defined(&domain($udom,'primary'))) {
                   2003:                 $uhome=&domain($udom,'primary');
                   2004:             }
                   2005:         }
                   2006:     }
                   2007:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.139  raeburn  2008:         my $rep;
                   2009:         if (grep { $_ eq $uhome } &current_machine_ids()) {
                   2010:             # domain information is hosted on this machine
                   2011:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1.1172.2.146.  .1(raebu 2012:22):         } else {
                   2013:22):             if ($encrypt) {
                   2014:22):                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2015:22):             } else {
                   2016:22):                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2017:22):             }
1.1172.2.139  raeburn  2018:         }
1.866     raeburn  2019:         my %returnhash;
1.875     albertel 2020:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2021:             return %returnhash;
                   2022:         }
1.806     raeburn  2023:         my @pairs=split(/\&/,$rep);
                   2024:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2025:             return @pairs;
                   2026:         }
                   2027:         my $i=0;
                   2028:         foreach my $item (@$storearr) {
                   2029:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2030:             $i++;
                   2031:         }
                   2032:         return %returnhash;
                   2033:     } else {
1.880     banghart 2034:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2035:     }
                   2036: }
                   2037: 
                   2038: # -------------------------------------------- put items in domain db files 
                   2039: 
                   2040: sub put_dom {
1.1172.2.146.  .1(raebu 2041:22):     my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
1.860     raeburn  2042:     if (!$udom) {
                   2043:         $udom=$env{'user.domain'};
                   2044:         if (defined(&domain($udom,'primary'))) {
                   2045:             $uhome=&domain($udom,'primary');
                   2046:         } else {
1.874     albertel 2047:             undef($uhome);
1.860     raeburn  2048:         }
                   2049:     } else {
                   2050:         if (!$uhome) {
                   2051:             if (defined(&domain($udom,'primary'))) {
                   2052:                 $uhome=&domain($udom,'primary');
                   2053:             }
                   2054:         }
                   2055:     } 
                   2056:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2057:         my $items='';
                   2058:         foreach my $item (keys(%$storehash)) {
                   2059:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2060:         }
                   2061:         $items=~s/\&$//;
1.1172.2.146.  .1(raebu 2062:22):         if ($encrypt) {
                   2063:22):             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2064:22):         } else {
                   2065:22):             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2066:22):         }
1.806     raeburn  2067:     } else {
1.860     raeburn  2068:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2069:     }
                   2070: }
                   2071: 
1.1023    raeburn  2072: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2073: sub newput_dom {
1.1023    raeburn  2074:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2075:     my $result;
                   2076:     if (!$udom) {
                   2077:         $udom=$env{'user.domain'};
                   2078:     }
1.1023    raeburn  2079:     if ($udom) {
                   2080:         my $uname = &get_domainconfiguser($udom);
                   2081:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2082:     }
                   2083:     return $result;
                   2084: }
                   2085: 
1.1023    raeburn  2086: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2087: sub del_dom {
1.1023    raeburn  2088:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2089:     if (ref($storearr) eq 'ARRAY') {
                   2090:         if (!$udom) {
                   2091:             $udom=$env{'user.domain'};
                   2092:         }
1.1023    raeburn  2093:         if ($udom) {
                   2094:             my $uname = &get_domainconfiguser($udom); 
                   2095:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2096:         }
                   2097:     }
                   2098: }
                   2099: 
1.1172.2.146.  .4(raebu 2100:22): sub store_dom {
                   2101:22):     my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
                   2102:22):     $$storehash{'ip'}=&get_requestor_ip();
                   2103:22):     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2104:22):     my $namevalue='';
                   2105:22):     foreach my $key (keys(%{$storehash})) {
                   2106:22):         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   2107:22):     }
                   2108:22):     $namevalue=~s/\&$//;
                   2109:22):     if (grep { $_ eq $home } current_machine_ids()) {
                   2110:22):         return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
                   2111:22):     } else {
                   2112:22):         if ($namespace eq 'private') {
                   2113:22):             return 'refused';
                   2114:22):         } elsif ($encrypt) {
                   2115:22):             return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
                   2116:22):         } else {
                   2117:22):             return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
                   2118:22):         }
                   2119:22):     }
                   2120:22): }
                   2121:22): 
                   2122:22): sub restore_dom {
                   2123:22):     my ($id,$namespace,$dom,$home,$encrypt) = @_;
                   2124:22):     my $answer;
                   2125:22):     if (grep { $_ eq $home } current_machine_ids()) {
                   2126:22):         $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
                   2127:22):     } elsif ($namespace ne 'private') {
                   2128:22):         if ($encrypt) {
                   2129:22):             $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
                   2130:22):         } else {
                   2131:22):             $answer=&reply("restoredom:$dom:$namespace:$id",$home);
                   2132:22):         }
                   2133:22):     }
                   2134:22):     my %returnhash=();
                   2135:22):     unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') ||
                   2136:22):             ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
                   2137:22):         foreach my $line (split(/\&/,$answer)) {
                   2138:22):             my ($name,$value)=split(/\=/,$line);
                   2139:22):             $returnhash{&unescape($name)}=&thaw_unescape($value);
                   2140:22):         }
                   2141:22):         my $version;
                   2142:22):         for ($version=1;$version<=$returnhash{'version'};$version++) {
                   2143:22):             foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2144:22):                 $returnhash{$item}=$returnhash{$version.':'.$item};
                   2145:22):             }
                   2146:22):         }
                   2147:22):     }
                   2148:22):     return %returnhash;
                   2149:22): }
                   2150:22): 
1.1023    raeburn  2151: # ----------------------------------construct domainconfig user for a domain 
                   2152: sub get_domainconfiguser {
                   2153:     my ($udom) = @_;
                   2154:     return $udom.'-domainconfig';
                   2155: }
                   2156: 
1.837     raeburn  2157: sub retrieve_inst_usertypes {
                   2158:     my ($udom) = @_;
                   2159:     my (%returnhash,@order);
1.989     raeburn  2160:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2161:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2162:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  2163:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2164:     } else {
                   2165:         if (defined(&domain($udom,'primary'))) {
                   2166:             my $uhome=&domain($udom,'primary');
                   2167:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2168:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  2169:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2170:                 return (\%returnhash,\@order);
                   2171:             }
                   2172:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2173:             my @pairs=split(/\&/,$hashitems);
                   2174:             foreach my $item (@pairs) {
                   2175:                 my ($key,$value)=split(/=/,$item,2);
                   2176:                 $key = &unescape($key);
                   2177:                 next if ($key =~ /^error: 2 /);
                   2178:                 $returnhash{$key}=&thaw_unescape($value);
                   2179:             }
                   2180:             my @esc_order = split(/\&/,$orderitems);
                   2181:             foreach my $item (@esc_order) {
                   2182:                 push(@order,&unescape($item));
                   2183:             }
                   2184:         } else {
1.1172.2.44  raeburn  2185:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2186:         }
1.1172.2.44  raeburn  2187:         return (\%returnhash,\@order);
1.837     raeburn  2188:     }
                   2189: }
                   2190: 
1.868     raeburn  2191: sub is_domainimage {
                   2192:     my ($url) = @_;
1.1172.2.142  raeburn  2193:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868     raeburn  2194:         if (&domain($1) ne '') {
                   2195:             return '1';
                   2196:         }
                   2197:     }
                   2198:     return;
                   2199: }
                   2200: 
1.899     raeburn  2201: sub inst_directory_query {
                   2202:     my ($srch) = @_;
                   2203:     my $udom = $srch->{'srchdomain'};
                   2204:     my %results;
                   2205:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2206:     my $outcome;
1.899     raeburn  2207:     if ($homeserver ne '') {
1.1172.2.116  raeburn  2208:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2209:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2210:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  2211:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   2212:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2213:                     (($major == 2) && ($minor < 11)) ||
                   2214:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   2215:                     return;
                   2216:                 }
                   2217:             }
                   2218:         }
1.904     albertel 2219: 	my $queryid=&reply("querysend:instdirsearch:".
                   2220: 			   &escape($srch->{'srchby'}).':'.
                   2221: 			   &escape($srch->{'srchterm'}).':'.
                   2222: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2223: 	my $host=&hostname($homeserver);
                   2224: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2225: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2226: 	    return;
                   2227: 	}
                   2228: 	my $response = &get_query_reply($queryid);
                   2229: 	my $maxtries = 5;
                   2230: 	my $tries = 1;
                   2231: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2232: 	    $response = &get_query_reply($queryid);
                   2233: 	    $tries ++;
                   2234: 	}
                   2235: 
                   2236:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2237:             if ($response eq 'unavailable') {
                   2238:                 $outcome = $response;
                   2239:             } else {
                   2240:                 $outcome = 'ok';
                   2241:                 my @matches = split(/\n/,$response);
                   2242:                 foreach my $match (@matches) {
                   2243:                     my ($key,$value) = split(/=/,$match);
                   2244:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2245:                 }
1.899     raeburn  2246:             }
                   2247:         }
                   2248:     }
1.909     raeburn  2249:     return ($outcome,%results);
1.899     raeburn  2250: }
                   2251: 
                   2252: sub usersearch {
                   2253:     my ($srch) = @_;
                   2254:     my $dom = $srch->{'srchdomain'};
                   2255:     my %results;
                   2256:     my %libserv = &all_library();
                   2257:     my $query = 'usersearch';
                   2258:     foreach my $tryserver (keys(%libserv)) {
                   2259:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2260:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2261:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2262:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.119  raeburn  2263:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2264:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2265:                              (($major == 2) && ($minor < 11)) ||
                   2266:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2267:                 }
                   2268:             }
1.899     raeburn  2269:             my $host=&hostname($tryserver);
                   2270:             my $queryid=
1.911     raeburn  2271:                 &reply("querysend:".&escape($query).':'.
                   2272:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2273:                        &escape($srch->{'srchtype'}).':'.
                   2274:                        &escape($srch->{'srchterm'}),$tryserver);
                   2275:             if ($queryid !~/^\Q$host\E\_/) {
                   2276:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2277:                 next;
1.899     raeburn  2278:             }
                   2279:             my $reply = &get_query_reply($queryid);
                   2280:             my $maxtries = 1;
                   2281:             my $tries = 1;
                   2282:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2283:                 $reply = &get_query_reply($queryid);
                   2284:                 $tries ++;
                   2285:             }
                   2286:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2287:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2288:             } else {
1.911     raeburn  2289:                 my @matches;
                   2290:                 if ($reply =~ /\n/) {
                   2291:                     @matches = split(/\n/,$reply);
                   2292:                 } else {
                   2293:                     @matches = split(/\&/,$reply);
                   2294:                 }
1.899     raeburn  2295:                 foreach my $match (@matches) {
                   2296:                     my ($uname,$udom,%userhash);
1.911     raeburn  2297:                     foreach my $entry (split(/:/,$match)) {
                   2298:                         my ($key,$value) =
                   2299:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2300:                         $userhash{$key} = $value;
                   2301:                         if ($key eq 'username') {
                   2302:                             $uname = $value;
                   2303:                         } elsif ($key eq 'domain') {
                   2304:                             $udom = $value;
1.911     raeburn  2305:                         }
1.899     raeburn  2306:                     }
                   2307:                     $results{$uname.':'.$udom} = \%userhash;
                   2308:                 }
                   2309:             }
                   2310:         }
                   2311:     }
                   2312:     return %results;
                   2313: }
                   2314: 
1.912     raeburn  2315: sub get_instuser {
                   2316:     my ($udom,$uname,$id) = @_;
                   2317:     my $homeserver = &domain($udom,'primary');
                   2318:     my ($outcome,%results);
                   2319:     if ($homeserver ne '') {
                   2320:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2321:                            &escape($id).':'.&escape($udom),$homeserver);
                   2322:         my $host=&hostname($homeserver);
                   2323:         if ($queryid !~/^\Q$host\E\_/) {
                   2324:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2325:             return;
                   2326:         }
                   2327:         my $response = &get_query_reply($queryid);
                   2328:         my $maxtries = 5;
                   2329:         my $tries = 1;
                   2330:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2331:             $response = &get_query_reply($queryid);
                   2332:             $tries ++;
                   2333:         }
                   2334:         if (!&error($response) && $response ne 'refused') {
                   2335:             if ($response eq 'unavailable') {
                   2336:                 $outcome = $response;
                   2337:             } else {
                   2338:                 $outcome = 'ok';
                   2339:                 my @matches = split(/\n/,$response);
                   2340:                 foreach my $match (@matches) {
                   2341:                     my ($key,$value) = split(/=/,$match);
                   2342:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2343:                 }
                   2344:             }
                   2345:         }
                   2346:     }
                   2347:     my %userinfo;
                   2348:     if (ref($results{$uname}) eq 'HASH') {
                   2349:         %userinfo = %{$results{$uname}};
                   2350:     } 
                   2351:     return ($outcome,%userinfo);
                   2352: }
                   2353: 
1.1172.2.69  raeburn  2354: sub get_multiple_instusers {
                   2355:     my ($udom,$users,$caller) = @_;
                   2356:     my ($outcome,$results);
                   2357:     if (ref($users) eq 'HASH') {
                   2358:         my $count = keys(%{$users});
                   2359:         my $requested = &freeze_escape($users);
                   2360:         my $homeserver = &domain($udom,'primary');
                   2361:         if ($homeserver ne '') {
                   2362:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2363:             my $host=&hostname($homeserver);
                   2364:             if ($queryid !~/^\Q$host\E\_/) {
                   2365:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2366:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2367:                 return ($outcome,$results);
                   2368:             }
                   2369:             my $response = &get_query_reply($queryid);
                   2370:             my $maxtries = 5;
                   2371:             if ($count > 100) {
                   2372:                 $maxtries = 1+int($count/20);
                   2373:             }
                   2374:             my $tries = 1;
                   2375:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2376:                 $response = &get_query_reply($queryid);
                   2377:                 $tries ++;
                   2378:             }
                   2379:             if ($response eq '') {
                   2380:                 $results = {};
                   2381:                 foreach my $key (keys(%{$users})) {
                   2382:                     my ($uname,$id);
                   2383:                     if ($caller eq 'id') {
                   2384:                         $id = $key;
                   2385:                     } else {
                   2386:                         $uname = $key;
                   2387:                     }
                   2388:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2389:                     $outcome = $resp;
                   2390:                     if ($resp eq 'ok') {
                   2391:                         %{$results} = (%{$results}, %info);
                   2392:                     } else {
                   2393:                         last;
                   2394:                     }
                   2395:                 }
                   2396:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2397:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2398:                     $outcome = $response;
                   2399:                 } else {
                   2400:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2401:                     if ($outcome eq 'ok') {
                   2402:                         $results = &thaw_unescape($userdata);
                   2403:                     }
                   2404:                 }
                   2405:             }
                   2406:         }
                   2407:     }
                   2408:     return ($outcome,$results);
                   2409: }
                   2410: 
1.912     raeburn  2411: sub inst_rulecheck {
1.923     raeburn  2412:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2413:     my %returnhash;
                   2414:     if ($udom ne '') {
                   2415:         if (ref($rules) eq 'ARRAY') {
                   2416:             @{$rules} = map {&escape($_);} (@{$rules});
                   2417:             my $rulestr = join(':',@{$rules});
                   2418:             my $homeserver=&domain($udom,'primary');
                   2419:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2420:                 my $response;
                   2421:                 if ($item eq 'username') {                
                   2422:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2423:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2424:                                               $homeserver));
1.923     raeburn  2425:                 } elsif ($item eq 'id') {
                   2426:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2427:                                               ':'.&escape($id).':'.$rulestr,
                   2428:                                               $homeserver));
1.1172.2.146.  .5(raebu 2429:22):                 } elsif ($item eq 'unamemap') {
                   2430:22):                     $response=&unescape(&reply('instunamemapcheck:'.
                   2431:22):                                                &escape($udom).':'.&escape($uname).
                   2432:22):                                               ':'.$rulestr,$homeserver));
1.945     raeburn  2433:                 } elsif ($item eq 'selfcreate') {
                   2434:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2435:                                                &escape($udom).':'.&escape($uname).
                   2436:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2437:                 }
1.912     raeburn  2438:                 if ($response ne 'refused') {
                   2439:                     my @pairs=split(/\&/,$response);
                   2440:                     foreach my $item (@pairs) {
                   2441:                         my ($key,$value)=split(/=/,$item,2);
                   2442:                         $key = &unescape($key);
                   2443:                         next if ($key =~ /^error: 2 /);
                   2444:                         $returnhash{$key}=&thaw_unescape($value);
                   2445:                     }
                   2446:                 }
                   2447:             }
                   2448:         }
                   2449:     }
                   2450:     return %returnhash;
                   2451: }
                   2452: 
                   2453: sub inst_userrules {
1.923     raeburn  2454:     my ($udom,$check) = @_;
1.912     raeburn  2455:     my (%ruleshash,@ruleorder);
                   2456:     if ($udom ne '') {
                   2457:         my $homeserver=&domain($udom,'primary');
                   2458:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2459:             my $response;
                   2460:             if ($check eq 'id') {
                   2461:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2462:                                  $homeserver);
1.943     raeburn  2463:             } elsif ($check eq 'email') {
                   2464:                 $response=&reply('instemailrules:'.&escape($udom),
                   2465:                                  $homeserver);
1.1172.2.146.  .5(raebu 2466:22):             } elsif ($check eq 'unamemap') {
                   2467:22):                 $response=&reply('unamemaprules:'.&escape($udom),
                   2468:22):                                  $homeserver);
1.923     raeburn  2469:             } else {
                   2470:                 $response=&reply('instuserrules:'.&escape($udom),
                   2471:                                  $homeserver);
                   2472:             }
1.912     raeburn  2473:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2474:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2475:                 ($response ne 'no_such_host')) {
                   2476:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2477:                 my @pairs=split(/\&/,$hashitems);
                   2478:                 foreach my $item (@pairs) {
                   2479:                     my ($key,$value)=split(/=/,$item,2);
                   2480:                     $key = &unescape($key);
                   2481:                     next if ($key =~ /^error: 2 /);
                   2482:                     $ruleshash{$key}=&thaw_unescape($value);
                   2483:                 }
                   2484:                 my @esc_order = split(/\&/,$orderitems);
                   2485:                 foreach my $item (@esc_order) {
                   2486:                     push(@ruleorder,&unescape($item));
                   2487:                 }
                   2488:             }
                   2489:         }
                   2490:     }
                   2491:     return (\%ruleshash,\@ruleorder);
                   2492: }
                   2493: 
1.976     raeburn  2494: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2495: 
                   2496: sub get_domain_defaults {
1.1172.2.35  raeburn  2497:     my ($domain,$ignore_cache) = @_;
                   2498:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2499:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2500:     unless ($ignore_cache) {
                   2501:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2502:         if (defined($cached)) {
                   2503:             if (ref($result) eq 'HASH') {
                   2504:                 return %{$result};
                   2505:             }
1.943     raeburn  2506:         }
                   2507:     }
                   2508:     my %domdefaults;
                   2509:     my %domconfig =
1.989     raeburn  2510:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2511:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2512:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2513:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2514:                                   'coursecategories','autoenroll',
1.1172.2.146.  .13(raeb 2515:-23):                                   'helpsettings','wafproxy','ltisec',
                   2516:-23):                                   'toolsec','domexttool','exttool'],
                   2517:-23):                                   $domain);
1.1172.2.41  raeburn  2518:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2519:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2520:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2521:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2522:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2523:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2524:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2525:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.146.  .12(raeb 2526:-23):         $domdefaults{'portal_def_email'} = $domconfig{'defaults'}{'portal_def_email'};
                   2527:-23):         $domdefaults{'portal_def_web'} = $domconfig{'defaults'}{'portal_def_web'};
1.1172.2.91  raeburn  2528:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2529:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2530:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.1172.2.146.  .5(raebu 2531:22):         $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
1.943     raeburn  2532:     } else {
                   2533:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2534:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2535:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2536:     }
1.976     raeburn  2537:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2538:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2539:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2540:         } else {
                   2541:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2542:         }
1.1172.2.6  raeburn  2543:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2544:         foreach my $item (@usertools) {
                   2545:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2546:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2547:             }
                   2548:         }
1.1172.2.29  raeburn  2549:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2550:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2551:         }
1.976     raeburn  2552:     }
1.985     raeburn  2553:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2554:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2555:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2556:         }
                   2557:     }
1.1172.2.9  raeburn  2558:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2559:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2560:     }
1.989     raeburn  2561:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2562:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2563:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2564:         }
                   2565:     }
1.1047    raeburn  2566:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2567:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1172.2.144  raeburn  2568:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1172.2.60  raeburn  2569:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2570:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2571:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2572:         }
1.1172.2.41  raeburn  2573:         foreach my $type (@coursetypes) {
                   2574:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2575:                 unless ($type eq 'community') {
                   2576:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2577:                 }
                   2578:             }
                   2579:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2580:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2581:             }
1.1172.2.146.  .14(raeb 2582:-23):             if (ref($domconfig{'coursedefaults'}{'coursequota'}) eq 'HASH') {
                   2583:-23):                 $domdefaults{$type.'coursequota'} = $domconfig{'coursedefaults'}{'coursequota'}{$type};
                   2584:-23):             }
1.1172.2.60  raeburn  2585:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2586:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2587:                     $domdefaults{$type.'postsubtimeout'} =
                   2588:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2589:                 }
                   2590:             }
1.1172.2.146.  .13(raeb 2591:-23):             if (ref($domconfig{'coursedefaults'}{'domexttool'}) eq 'HASH') {
                   2592:-23):                 $domdefaults{$type.'domexttool'} = $domconfig{'coursedefaults'}{'domexttool'}{$type};
                   2593:-23):             } else {
                   2594:-23):                 $domdefaults{$type.'domexttool'} = 1;
                   2595:-23):             }
                   2596:-23):             if (ref($domconfig{'coursedefaults'}{'exttool'}) eq 'HASH') {
                   2597:-23):                 $domdefaults{$type.'exttool'} = $domconfig{'coursedefaults'}{'exttool'}{$type};
                   2598:-23):             } else {
                   2599:-23):                 $domdefaults{$type.'exttool'} = 0;
                   2600:-23):             }
1.1172.2.30  raeburn  2601:         }
1.1172.2.67  raeburn  2602:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2603:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2604:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2605:                 if (@clonecodes) {
                   2606:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2607:                 }
                   2608:             }
                   2609:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2610:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2611:         }
1.1172.2.103  raeburn  2612:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2613:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2614:         }
1.1172.2.146.  .3(raebu 2615:22):         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
                   2616:22):             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
                   2617:22):         }
1.1047    raeburn  2618:     }
1.1073    raeburn  2619:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2620:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2621:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2622:         }
                   2623:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2624:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2625:         }
1.1172.2.62  raeburn  2626:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2627:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2628:         }
1.1172.2.137  raeburn  2629:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1172.2.136  raeburn  2630:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2631:         }
1.1073    raeburn  2632:     }
1.1172.2.41  raeburn  2633:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2634:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2635:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2636:                             'approval','limit');
                   2637:             foreach my $type (@coursetypes) {
                   2638:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2639:                     my @mgrdc = ();
                   2640:                     foreach my $item (@settings) {
                   2641:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2642:                             push(@mgrdc,$item);
                   2643:                         }
                   2644:                     }
                   2645:                     if (@mgrdc) {
                   2646:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2647:                     }
                   2648:                 }
                   2649:             }
                   2650:         }
                   2651:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2652:             foreach my $type (@coursetypes) {
                   2653:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2654:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2655:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2656:                     }
                   2657:                 }
                   2658:             }
                   2659:         }
                   2660:     }
1.1172.2.46  raeburn  2661:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2662:         $domdefaults{'catauth'} = 'std';
                   2663:         $domdefaults{'catunauth'} = 'std';
                   2664:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2665:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2666:         }
                   2667:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2668:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2669:         }
                   2670:     }
1.1172.2.76  raeburn  2671:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2672:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1172.2.146  raeburn  2673:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1172.2.76  raeburn  2674:     }
1.1172.2.89  raeburn  2675:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2676:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2677:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2678:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2679:         }
                   2680:     }
1.1172.2.142  raeburn  2681:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   2682:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
                   2683:             if ($domconfig{'wafproxy'}{$item}) {
                   2684:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
                   2685:             }
                   2686:         }
                   2687:     }
1.1172.2.146.  .4(raebu 2688:22):     if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   2689:22):         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
                   2690:22):             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
                   2691:22):             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
                   2692:22):             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
                   2693:22):         }
                   2694:22):         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
                   2695:22):             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
          .13(raeb 2696:-23):                 $domdefaults{'ltiprivhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
                   2697:-23):             }
                   2698:-23):         }
          .17(raeb 2699:-24):         if (ref($domconfig{'ltisec'}{'suggested'}) eq 'HASH') {
                   2700:-24):             my %suggestions = %{$domconfig{'ltisec'}{'suggested'}};
                   2701:-24):             foreach my $item (keys(%{$domconfig{'ltisec'}{'suggested'}})) {
                   2702:-24):                 unless (ref($domconfig{'ltisec'}{'suggested'}{$item}) eq 'HASH') {
                   2703:-24):                     delete($suggestions{$item});
                   2704:-24):                 }
                   2705:-24):             }
                   2706:-24):             if (keys(%suggestions)) {
                   2707:-24):                 $domdefaults{'linkprotsuggested'} = \%suggestions;
                   2708:-24):             }
                   2709:-24):         }
          .13(raeb 2710:-23):     }
                   2711:-23):     if (ref($domconfig{'toolsec'}) eq 'HASH') {
                   2712:-23):         if (ref($domconfig{'toolsec'}{'encrypt'}) eq 'HASH') {
                   2713:-23):             $domdefaults{'toolenc_crs'} = $domconfig{'toolsec'}{'encrypt'}{'crs'};
                   2714:-23):             $domdefaults{'toolenc_dom'} = $domconfig{'toolsec'}{'encrypt'}{'dom'};
                   2715:-23):         }
                   2716:-23):         if (ref($domconfig{'toolsec'}{'private'}) eq 'HASH') {
                   2717:-23):             if (ref($domconfig{'toolsec'}{'private'}{'keys'}) eq 'ARRAY') {
                   2718:-23):                 $domdefaults{'toolprivhosts'} = $domconfig{'toolsec'}{'private'}{'keys'};
          .4(raebu 2719:22):             }
                   2720:22):         }
                   2721:22):     }
1.1172.2.23  raeburn  2722:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2723:     return %domdefaults;
                   2724: }
                   2725: 
1.1172.2.106  raeburn  2726: sub get_dom_cats {
                   2727:     my ($dom) = @_;
                   2728:     return unless (&domain($dom));
                   2729:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2730:     unless (defined($cached)) {
                   2731:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2732:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2733:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2734:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2735:             } else {
                   2736:                 $cats = {};
                   2737:             }
                   2738:         } else {
                   2739:             $cats = {};
                   2740:         }
                   2741:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2742:     }
                   2743:     return $cats;
                   2744: }
                   2745: 
                   2746: sub get_dom_instcats {
                   2747:     my ($dom) = @_;
                   2748:     return unless (&domain($dom));
                   2749:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2750:     unless (defined($cached)) {
                   2751:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2752:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2753:         if ($totcodes > 0) {
                   2754:             my $caller = 'global';
                   2755:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2756:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2757:                 $instcats = {
1.1172.2.146.  .10(raeb 2758:-23):                                 totcodes => $totcodes,
1.1172.2.106  raeburn  2759:                                 codes => \%codes,
                   2760:                                 codetitles => \@codetitles,
                   2761:                                 cat_titles => \%cat_titles,
                   2762:                                 cat_order => \%cat_order,
                   2763:                             };
                   2764:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2765:             }
                   2766:         }
                   2767:     }
                   2768:     return $instcats;
                   2769: }
                   2770: 
                   2771: sub retrieve_instcodes {
                   2772:     my ($coursecodes,$dom) = @_;
                   2773:     my $totcodes;
                   2774:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2775:     foreach my $course (keys(%courses)) {
                   2776:         if (ref($courses{$course}) eq 'HASH') {
                   2777:             if ($courses{$course}{'inst_code'} ne '') {
                   2778:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2779:                 $totcodes ++;
                   2780:             }
                   2781:         }
                   2782:     }
                   2783:     return $totcodes;
                   2784: }
                   2785: 
1.1172.2.113  raeburn  2786: # --------------------------------------------- Get domain config for passwords
                   2787: 
                   2788: sub get_passwdconf {
                   2789:     my ($dom) = @_;
                   2790:     my (%passwdconf,$gotconf,$lookup);
                   2791:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2792:     if (defined($cached)) {
                   2793:         if (ref($result) eq 'HASH') {
                   2794:             %passwdconf = %{$result};
                   2795:             $gotconf = 1;
                   2796:         }
                   2797:     }
                   2798:     unless ($gotconf) {
                   2799:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2800:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2801:             %passwdconf = %{$domconfig{'passwords'}};
                   2802:         }
                   2803:         my $cachetime = 24*60*60;
                   2804:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2805:     }
                   2806:     return %passwdconf;
                   2807: }
                   2808: 
1.1172.2.146.  .1(raebu 2809:22): sub course_portal_url {
                   2810:22):     my ($cnum,$cdom,$r) = @_;
                   2811:22):     my $chome = &homeserver($cnum,$cdom);
                   2812:22):     my $hostname = &hostname($chome);
                   2813:22):     my $protocol = $protocol{$chome};
                   2814:22):     $protocol = 'http' if ($protocol ne 'https');
                   2815:22):     my %domdefaults = &get_domain_defaults($cdom);
                   2816:22):     my $firsturl;
                   2817:22):     if ($domdefaults{'portal_def'}) {
                   2818:22):         $firsturl = $domdefaults{'portal_def'};
                   2819:22):     } else {
                   2820:22):         my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
                   2821:22):         $hostname = $alias if ($alias ne '');
                   2822:22):         $firsturl = $protocol.'://'.$hostname;
                   2823:22):     }
                   2824:22):     return $firsturl;
                   2825:22): }
                   2826:22): 
          .12(raeb 2827:-23): sub url_prefix {
                   2828:-23):     my ($r,$dom,$home,$context) = @_;
                   2829:-23):     my $prefix;
                   2830:-23):     my %domdefs = &get_domain_defaults($dom);
                   2831:-23):     if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
                   2832:-23):         if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
                   2833:-23):             $prefix = $1;
                   2834:-23):         }
                   2835:-23):     }
                   2836:-23):     if ($prefix eq '') {
                   2837:-23):         my $hostname = &hostname($home);
                   2838:-23):         my $protocol = $protocol{$home};
                   2839:-23):         $protocol = 'http' if ($protocol{$home} ne 'https');
                   2840:-23):         my $alias = &use_proxy_alias($r,$home);
                   2841:-23):         $hostname = $alias if ($alias ne '');
                   2842:-23):         $prefix = $protocol.'://'.$hostname;
                   2843:-23):     }
                   2844:-23):     return $prefix;
                   2845:-23): }
                   2846:-23): 
1.344     www      2847: # --------------------------------------------------- Assign a key to a student
                   2848: 
                   2849: sub assign_access_key {
1.364     www      2850: #
                   2851: # a valid key looks like uname:udom#comments
                   2852: # comments are being appended
                   2853: #
1.498     www      2854:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2855:     $kdom=
1.620     albertel 2856:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2857:     $knum=
1.620     albertel 2858:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2859:     $cdom=
1.620     albertel 2860:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2861:     $cnum=
1.620     albertel 2862:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2863:     $udom=$env{'user.name'} unless (defined($udom));
                   2864:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2865:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2866:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2867:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2868:                                                   # assigned to this person
                   2869:                                                   # - this should not happen,
1.345     www      2870:                                                   # unless something went wrong
                   2871:                                                   # the first time around
                   2872: # ready to assign
1.364     www      2873:         $logentry=$1.'; '.$logentry;
1.496     www      2874:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2875:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2876: # key now belongs to user
1.346     www      2877: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2878:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2879:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2880:                 return 'ok';
                   2881:             } else {
                   2882:                 return 
                   2883:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2884: 	    }
                   2885:         } else {
                   2886:             return 'error: Could not assign key, try again later.';
                   2887:         }
1.364     www      2888:     } elsif (!$existing{$ckey}) {
1.345     www      2889: # the key does not exist
                   2890: 	return 'error: The key does not exist';
                   2891:     } else {
                   2892: # the key is somebody else's
                   2893: 	return 'error: The key is already in use';
                   2894:     }
1.344     www      2895: }
                   2896: 
1.364     www      2897: # ------------------------------------------ put an additional comment on a key
                   2898: 
                   2899: sub comment_access_key {
                   2900: #
                   2901: # a valid key looks like uname:udom#comments
                   2902: # comments are being appended
                   2903: #
                   2904:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2905:     $cdom=
1.620     albertel 2906:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2907:     $cnum=
1.620     albertel 2908:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2909:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2910:     if ($existing{$ckey}) {
                   2911:         $existing{$ckey}.='; '.$logentry;
                   2912: # ready to assign
1.367     www      2913:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2914:                                                  $cdom,$cnum) eq 'ok') {
                   2915: 	    return 'ok';
                   2916:         } else {
                   2917: 	    return 'error: Count not store comment.';
                   2918:         }
                   2919:     } else {
                   2920: # the key does not exist
                   2921: 	return 'error: The key does not exist';
                   2922:     }
                   2923: }
                   2924: 
1.344     www      2925: # ------------------------------------------------------ Generate a set of keys
                   2926: 
                   2927: sub generate_access_keys {
1.364     www      2928:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2929:     $cdom=
1.620     albertel 2930:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2931:     $cnum=
1.620     albertel 2932:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2933:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2934:     unless (($cdom) && ($cnum)) { return 0; }
                   2935:     if ($number>10000) { return 0; }
                   2936:     sleep(2); # make sure don't get same seed twice
                   2937:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2938:     my $total=0;
                   2939:     for (my $i=1;$i<=$number;$i++) {
                   2940:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2941:                   sprintf("%lx",int(100000*rand)).'-'.
                   2942:                   sprintf("%lx",int(100000*rand));
                   2943:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2944:        $newkey=~s/0/h/g; # and also 0 and O
                   2945:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2946:        if ($existing{$newkey}) {
                   2947:            $i--;
                   2948:        } else {
1.364     www      2949: 	  if (&put('accesskeys',
                   2950:               { $newkey => '# generated '.localtime().
1.620     albertel 2951:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2952:                            '; '.$logentry },
                   2953: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2954:               $total++;
                   2955: 	  }
                   2956:        }
                   2957:     }
1.620     albertel 2958:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2959:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2960:     return $total;
                   2961: }
                   2962: 
                   2963: # ------------------------------------------------------- Validate an accesskey
                   2964: 
                   2965: sub validate_access_key {
                   2966:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2967:     $cdom=
1.620     albertel 2968:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2969:     $cnum=
1.620     albertel 2970:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2971:     $udom=$env{'user.domain'} unless (defined($udom));
                   2972:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2973:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2974:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2975: }
                   2976: 
                   2977: # ------------------------------------- Find the section of student in a course
1.652     albertel 2978: sub devalidate_getsection_cache {
                   2979:     my ($udom,$unam,$courseid)=@_;
                   2980:     my $hashid="$udom:$unam:$courseid";
                   2981:     &devalidate_cache_new('getsection',$hashid);
                   2982: }
1.298     matthew  2983: 
1.815     albertel 2984: sub courseid_to_courseurl {
                   2985:     my ($courseid) = @_;
                   2986:     #already url style courseid
                   2987:     return $courseid if ($courseid =~ m{^/});
                   2988: 
                   2989:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2990: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2991: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2992: 	return "/$cdom/$cnum";
                   2993:     }
                   2994: 
                   2995:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2996:     if (exists($courseinfo{'num'})) {
                   2997: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2998:     }
                   2999: 
                   3000:     return undef;
                   3001: }
                   3002: 
1.298     matthew  3003: sub getsection {
                   3004:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 3005:     my $cachetime=1800;
1.551     albertel 3006: 
                   3007:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 3008:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 3009:     if (defined($cached)) { return $result; }
                   3010: 
1.298     matthew  3011:     my %Pending; 
                   3012:     my %Expired;
                   3013:     #
                   3014:     # Each role can either have not started yet (pending), be active, 
                   3015:     #    or have expired.
                   3016:     #
                   3017:     # If there is an active role, we are done.
                   3018:     #
                   3019:     # If there is more than one role which has not started yet, 
                   3020:     #     choose the one which will start sooner
                   3021:     # If there is one role which has not started yet, return it.
                   3022:     #
                   3023:     # If there is more than one expired role, choose the one which ended last.
                   3024:     # If there is a role which has expired, return it.
                   3025:     #
1.815     albertel 3026:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  3027:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  3028:     foreach my $key (keys(%roleshash)) {
1.479     albertel 3029:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  3030:         my $section=$1;
                   3031:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  3032:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  3033:         my $now=time;
1.548     albertel 3034:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  3035:             $Expired{$end}=$section;
                   3036:             next;
                   3037:         }
1.548     albertel 3038:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  3039:             $Pending{$start}=$section;
                   3040:             next;
                   3041:         }
1.599     albertel 3042:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  3043:     }
                   3044:     #
                   3045:     # Presumedly there will be few matching roles from the above
                   3046:     # loop and the sorting time will be negligible.
                   3047:     if (scalar(keys(%Pending))) {
                   3048:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 3049:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  3050:     } 
                   3051:     if (scalar(keys(%Expired))) {
                   3052:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   3053:         my $time = pop(@sorted);
1.599     albertel 3054:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  3055:     }
1.599     albertel 3056:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  3057: }
1.70      www      3058: 
1.599     albertel 3059: sub save_cache {
                   3060:     &purge_remembered();
1.722     albertel 3061:     #&Apache::loncommon::validate_page();
1.620     albertel 3062:     undef(%env);
1.780     albertel 3063:     undef($env_loaded);
1.599     albertel 3064: }
1.452     albertel 3065: 
1.599     albertel 3066: my $to_remember=-1;
                   3067: my %remembered;
                   3068: my %accessed;
                   3069: my $kicks=0;
                   3070: my $hits=0;
1.849     albertel 3071: sub make_key {
                   3072:     my ($name,$id) = @_;
1.872     albertel 3073:     if (length($id) > 65 
                   3074: 	&& length(&escape($id)) > 200) {
                   3075: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   3076:     }
1.849     albertel 3077:     return &escape($name.':'.$id);
                   3078: }
                   3079: 
1.599     albertel 3080: sub devalidate_cache_new {
                   3081:     my ($name,$id,$debug) = @_;
                   3082:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  3083:     my $remembered_id=$name.':'.$id;
1.849     albertel 3084:     $id=&make_key($name,$id);
1.599     albertel 3085:     $memcache->delete($id);
1.1172.2.81  raeburn  3086:     delete($remembered{$remembered_id});
                   3087:     delete($accessed{$remembered_id});
1.599     albertel 3088: }
                   3089: 
                   3090: sub is_cached_new {
                   3091:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  3092:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   3093:                                      # keys in %remembered hash, which persists for
                   3094:                                      # duration of request (no restriction on key length).
                   3095:     if (exists($remembered{$remembered_id})) {
                   3096: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   3097: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3098: 	$hits++;
1.1172.2.81  raeburn  3099: 	return ($remembered{$remembered_id},1);
1.599     albertel 3100:     }
1.1172.2.81  raeburn  3101:     $id=&make_key($name,$id);
1.599     albertel 3102:     my $value = $memcache->get($id);
                   3103:     if (!(defined($value))) {
                   3104: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 3105: 	return (undef,undef);
1.416     albertel 3106:     }
1.599     albertel 3107:     if ($value eq '__undef__') {
                   3108: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   3109: 	$value=undef;
                   3110:     }
1.1172.2.81  raeburn  3111:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3112:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   3113:     return ($value,1);
                   3114: }
                   3115: 
                   3116: sub do_cache_new {
                   3117:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  3118:     my $remembered_id=$name.':'.$id;
1.849     albertel 3119:     $id=&make_key($name,$id);
1.599     albertel 3120:     my $setvalue=$value;
                   3121:     if (!defined($setvalue)) {
                   3122: 	$setvalue='__undef__';
                   3123:     }
1.623     albertel 3124:     if (!defined($time) ) {
                   3125: 	$time=600;
                   3126:     }
1.599     albertel 3127:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 3128:     my $result = $memcache->set($id,$setvalue,$time);
                   3129:     if (! $result) {
1.872     albertel 3130: 	&logthis("caching of id -> $id  failed");
1.910     albertel 3131: 	$memcache->disconnect_all();
1.872     albertel 3132:     }
1.600     albertel 3133:     # need to make a copy of $value
1.1172.2.81  raeburn  3134:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3135:     return $value;
                   3136: }
                   3137: 
                   3138: sub make_room {
1.1172.2.81  raeburn  3139:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3140: 
1.1172.2.81  raeburn  3141:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3142:                                     : $value;
1.599     albertel 3143:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  3144:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3145:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3146:     my $to_kick;
                   3147:     my $max_time=0;
                   3148:     foreach my $other (keys(%accessed)) {
                   3149: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3150: 	    $to_kick=$other;
                   3151: 	    $max_time=&tv_interval($accessed{$other});
                   3152: 	}
                   3153:     }
                   3154:     delete($remembered{$to_kick});
                   3155:     delete($accessed{$to_kick});
                   3156:     $kicks++;
                   3157:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3158:     return;
                   3159: }
                   3160: 
1.599     albertel 3161: sub purge_remembered {
1.604     albertel 3162:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3163:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3164:     undef(%remembered);
                   3165:     undef(%accessed);
1.428     albertel 3166: }
1.70      www      3167: # ------------------------------------- Read an entry from a user's environment
                   3168: 
                   3169: sub userenvironment {
                   3170:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3171:     my $items;
                   3172:     foreach my $item (@what) {
                   3173:         $items.=&escape($item).'&';
                   3174:     }
                   3175:     $items=~s/\&$//;
1.70      www      3176:     my %returnhash=();
1.1009    raeburn  3177:     my $uhome = &homeserver($unam,$udom);
                   3178:     unless ($uhome eq 'no_host') {
                   3179:         my @answer=split(/\&/, 
                   3180:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3181:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3182:             return %returnhash;
                   3183:         }
1.1009    raeburn  3184:         my $i;
                   3185:         for ($i=0;$i<=$#what;$i++) {
                   3186: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3187:         }
1.70      www      3188:     }
                   3189:     return %returnhash;
1.1       albertel 3190: }
                   3191: 
1.617     albertel 3192: # ---------------------------------------------------------- Get a studentphoto
                   3193: sub studentphoto {
                   3194:     my ($udom,$unam,$ext) = @_;
                   3195:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3196:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3197:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3198:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3199:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3200:             } else {
                   3201:                 my ($result,$perm_reqd)=
1.707     albertel 3202: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3203:                 if ($result eq 'ok') {
                   3204:                     if (!($perm_reqd eq 'yes')) {
                   3205:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3206:                     }
                   3207:                 }
                   3208:             }
                   3209:         }
                   3210:     } else {
                   3211:         my ($result,$perm_reqd) = 
1.707     albertel 3212: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3213:         if ($result eq 'ok') {
                   3214:             if (!($perm_reqd eq 'yes')) {
                   3215:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3216:             }
                   3217:         }
                   3218:     }
                   3219:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3220: }
                   3221: 
                   3222: sub retrievestudentphoto {
                   3223:     my ($udom,$unam,$ext,$type) = @_;
                   3224:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3225:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3226:     if ($ret eq 'ok') {
                   3227:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3228:         if ($type eq 'thumbnail') {
                   3229:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3230:         }
                   3231:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3232:         return $tokenurl;
                   3233:     } else {
                   3234:         if ($type eq 'thumbnail') {
                   3235:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3236:         } else { 
                   3237:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3238:         }
1.617     albertel 3239:     }
                   3240: }
                   3241: 
1.263     www      3242: # -------------------------------------------------------------------- New chat
                   3243: 
                   3244: sub chatsend {
1.724     raeburn  3245:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3246:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3247:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3248:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3249:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3250: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3251: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3252: }
                   3253: 
                   3254: # ------------------------------------------ Find current version of a resource
                   3255: 
                   3256: sub getversion {
                   3257:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  3258:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3259:     return &currentversion(&filelocation('',$fname));
                   3260: }
                   3261: 
                   3262: sub currentversion {
                   3263:     my $fname=shift;
                   3264:     my $author=$fname;
                   3265:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3266:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3267:     my $home=&homeserver($uname,$udom);
1.292     www      3268:     if ($home eq 'no_host') { 
                   3269:         return -1; 
                   3270:     }
1.1112    www      3271:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3272:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3273: 	return -1;
                   3274:     }
1.1112    www      3275:     return $answer;
1.263     www      3276: }
                   3277: 
1.1111    www      3278: #
                   3279: # Return special version number of resource if set by override, empty otherwise
                   3280: #
                   3281: sub usedversion {
                   3282:     my $fname=shift;
                   3283:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3284:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3285:     if ($urlversion) { return $urlversion; }
                   3286:     return '';
                   3287: }
                   3288: 
1.1       albertel 3289: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3290: 
1.1       albertel 3291: sub subscribe {
                   3292:     my $fname=shift;
1.761     raeburn  3293:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3294:     $fname=~s/[\n\r]//g;
1.1       albertel 3295:     my $author=$fname;
                   3296:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3297:     my ($udom,$uname)=split(/\//,$author);
                   3298:     my $home=homeserver($uname,$udom);
1.335     albertel 3299:     if ($home eq 'no_host') {
                   3300:         return 'not_found';
1.1       albertel 3301:     }
                   3302:     my $answer=reply("sub:$fname",$home);
1.64      www      3303:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3304: 	$answer.=' by '.$home;
                   3305:     }
1.1       albertel 3306:     return $answer;
                   3307: }
                   3308:     
1.8       www      3309: # -------------------------------------------------------------- Replicate file
                   3310: 
                   3311: sub repcopy {
                   3312:     my $filename=shift;
1.23      www      3313:     $filename=~s/\/+/\//g;
1.1142    raeburn  3314:     my $londocroot = $perlvar{'lonDocRoot'};
                   3315:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3316:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3317:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3318: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3319: 	return &repcopy_userfile($filename);
                   3320:     }
1.532     albertel 3321:     $filename=~s/[\n\r]//g;
1.8       www      3322:     my $transname="$filename.in.transfer";
1.828     www      3323: # FIXME: this should flock
1.607     raeburn  3324:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3325:     my $remoteurl=subscribe($filename);
1.64      www      3326:     if ($remoteurl =~ /^con_lost by/) {
                   3327: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3328:            return 'unavailable';
1.8       www      3329:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3330: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3331: 	   return 'not_found';
1.64      www      3332:     } elsif ($remoteurl =~ /^rejected by/) {
                   3333: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3334:            return 'forbidden';
1.20      www      3335:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3336:            return 'ok';
1.8       www      3337:     } else {
1.290     www      3338:         my $author=$filename;
                   3339:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3340:         my ($udom,$uname)=split(/\//,$author);
                   3341:         my $home=homeserver($uname,$udom);
                   3342:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3343:            my @parts=split(/\//,$filename);
                   3344:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3345:            if ($path ne "$londocroot/res") {
1.8       www      3346:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3347: 	       return 'bad_request';
1.8       www      3348:            }
                   3349:            my $count;
                   3350:            for ($count=5;$count<$#parts;$count++) {
                   3351:                $path.="/$parts[$count]";
                   3352:                if ((-e $path)!=1) {
                   3353: 		   mkdir($path,0777);
                   3354:                }
                   3355:            }
                   3356:            my $ua=new LWP::UserAgent;
                   3357:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3358:            my $response=$ua->request($request,$transname);
                   3359:            if ($response->is_error()) {
                   3360: 	       unlink($transname);
                   3361:                my $message=$response->status_line;
1.672     albertel 3362:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3363:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3364:                return 'unavailable';
1.8       www      3365:            } else {
1.16      www      3366: 	       if ($remoteurl!~/\.meta$/) {
                   3367:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3368:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3369:                   if ($mresponse->is_error()) {
                   3370: 		      unlink($filename.'.meta');
                   3371:                       &logthis(
1.672     albertel 3372:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3373:                   }
                   3374: 	       }
1.8       www      3375:                rename($transname,$filename);
1.607     raeburn  3376:                return 'ok';
1.8       www      3377:            }
1.290     www      3378:        }
1.8       www      3379:     }
1.330     www      3380: }
                   3381: 
1.1172.2.124  raeburn  3382: # ------------------------------------------------- Unsubscribe from a resource
                   3383: 
                   3384: sub unsubscribe {
                   3385:     my ($fname) = @_;
                   3386:     my $answer;
                   3387:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3388:     $fname=~s/[\n\r]//g;
                   3389:     my $author=$fname;
                   3390:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3391:     my ($udom,$uname)=split(/\//,$author);
                   3392:     my $home=homeserver($uname,$udom);
                   3393:     if ($home eq 'no_host') {
                   3394:         $answer = 'no_host';
                   3395:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3396:         $answer = 'home';
                   3397:     } else {
1.1172.2.125  raeburn  3398:         $answer = reply("unsub:$fname",$home);
1.1172.2.124  raeburn  3399:     }
                   3400:     return $answer;
                   3401: }
                   3402: 
1.330     www      3403: # ------------------------------------------------ Get server side include body
                   3404: sub ssi_body {
1.381     albertel 3405:     my ($filelink,%form)=@_;
1.606     matthew  3406:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3407:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3408:     }
1.953     www      3409:     my $output='';
                   3410:     my $response;
1.980     raeburn  3411:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3412:        ($output,$response)=&externalssi($filelink);
1.953     www      3413:     } else {
1.1004    droeschl 3414:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3415:        $filelink .= 'inhibitmenu=yes';
1.953     www      3416:        ($output,$response)=&ssi($filelink,%form);
                   3417:     }
1.778     albertel 3418:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3419:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3420:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3421:     if (wantarray) {
                   3422:         return ($output, $response);
                   3423:     } else {
                   3424:         return $output;
                   3425:     }
1.8       www      3426: }
                   3427: 
1.15      www      3428: # --------------------------------------------------------- Server Side Include
                   3429: 
1.782     albertel 3430: sub absolute_url {
1.1172.2.145  raeburn  3431:     my ($host_name,$unalias,$keep_proto) = @_;
1.782     albertel 3432:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3433:     if ($host_name eq '') {
                   3434: 	$host_name = $ENV{'SERVER_NAME'};
                   3435:     }
1.1172.2.145  raeburn  3436:     if ($unalias) {
                   3437:         my $alias = &get_proxy_alias();
                   3438:         if ($alias eq $host_name) {
                   3439:             my $lonhost = $perlvar{'lonHostID'};
                   3440:             my $hostname = &hostname($lonhost);
                   3441:             my $lcproto;
                   3442:             if (($keep_proto) || ($hostname eq '')) {
                   3443:                 $lcproto = $protocol;
                   3444:             } else {
                   3445:                 $lcproto = $protocol{$lonhost};
                   3446:                 $lcproto = 'http' if ($lcproto ne 'https');
                   3447:                 $lcproto .= '://';
                   3448:             }
                   3449:             unless ($hostname eq '') {
                   3450:                 return $lcproto.$hostname;
                   3451:             }
                   3452:         }
                   3453:     } 
1.782     albertel 3454:     return $protocol.$host_name;
                   3455: }
                   3456: 
1.942     foxr     3457: #
                   3458: #   Server side include.
                   3459: # Parameters:
                   3460: #  fn     Possibly encrypted resource name/id.
                   3461: #  form   Hash that describes how the rendering should be done
                   3462: #         and other things.
1.944     foxr     3463: # Returns:
1.950     raeburn  3464: #   Scalar context: The content of the response.
                   3465: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3466: #     
1.15      www      3467: sub ssi {
                   3468: 
1.944     foxr     3469:     my ($fn,%form)=@_;
1.1172.2.145  raeburn  3470:     my ($host,$request,$response);
                   3471:     $host = &absolute_url('',1);
1.711     albertel 3472: 
                   3473:     $form{'no_update_last_known'}=1;
1.895     albertel 3474:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3475:     if (%form) {
1.1172.2.145  raeburn  3476:       $request=new HTTP::Request('POST',$host.$fn);
1.1172.2.58  raeburn  3477:       $request->content(join('&',map {
                   3478:             my $name = escape($_);
                   3479:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3480:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3481:             : &escape($form{$_}) );
                   3482:         } keys(%form)));
1.23      www      3483:     } else {
1.1172.2.145  raeburn  3484:       $request=new HTTP::Request('GET',$host.$fn);
1.23      www      3485:     }
                   3486: 
1.15      www      3487:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3488: 
1.1172.2.101  raeburn  3489:     if (($env{'request.course.id'}) &&
                   3490:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3491:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3492:         ($form{'grade_symb'} ne '') &&
                   3493:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3494:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3495:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3496:             my $ua=new LWP::UserAgent;
                   3497:             $ua->local_address('127.0.0.1');
                   3498:             $response = $ua->request($request);
                   3499:         } else {
                   3500:             {
                   3501:                 require LWP::Protocol::http;
                   3502:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3503:                 my $ua=new LWP::UserAgent;
                   3504:                 $response = $ua->request($request);
                   3505:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3506:             }
                   3507:         }
                   3508:     } else {
                   3509:         my $ua=new LWP::UserAgent;
                   3510:         $response = $ua->request($request);
                   3511:     }
1.944     foxr     3512:     if (wantarray) {
1.1172.2.3  raeburn  3513: 	return ($response->content, $response);
1.944     foxr     3514:     } else {
1.1172.2.3  raeburn  3515: 	return $response->content;
1.942     foxr     3516:     }
1.324     www      3517: }
                   3518: 
                   3519: sub externalssi {
                   3520:     my ($url)=@_;
                   3521:     my $ua=new LWP::UserAgent;
                   3522:     my $request=new HTTP::Request('GET',$url);
                   3523:     my $response=$ua->request($request);
1.954     raeburn  3524:     if (wantarray) {
                   3525:         return ($response->content, $response);
                   3526:     } else {
                   3527:         return $response->content;
                   3528:     }
1.15      www      3529: }
1.254     www      3530: 
1.1172.2.98  raeburn  3531: # If the local copy of a replicated resource is outdated, trigger a
                   3532: # connection from the homeserver to flush the delayed queue. If no update
                   3533: # happens, remove local copies of outdated resource (and corresponding
                   3534: # metadata file).
                   3535: 
                   3536: sub remove_stale_resfile {
                   3537:     my ($url) = @_;
                   3538:     my $removed;
                   3539:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3540:         my $audom = $1;
                   3541:         my $auname = $2;
                   3542:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3543:             my $homeserver = &homeserver($auname,$audom);
                   3544:             unless (($homeserver eq 'no_host') ||
                   3545:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3546:                 my $fname = &filelocation('',$url);
                   3547:                 if (-e $fname) {
                   3548:                     my $hostname = &hostname($homeserver);
                   3549:                     if ($hostname) {
1.1172.2.120  raeburn  3550:                         my $protocol = $protocol{$homeserver};
                   3551:                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3552:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120  raeburn  3553:                         my $ua=new LWP::UserAgent;
                   3554:                         $ua->timeout(5);
1.1172.2.98  raeburn  3555:                         my $request=new HTTP::Request('HEAD',$uri);
                   3556:                         my $response=$ua->request($request);
                   3557:                         if ($response->is_success()) {
                   3558:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3559:                             my $locmodtime = (stat($fname))[9];
                   3560:                             if ($locmodtime < $remmodtime) {
                   3561:                                 my $stale;
                   3562:                                 my $answer = &reply('pong',$homeserver);
                   3563:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3564:                                     sleep(0.2);
                   3565:                                     $locmodtime = (stat($fname))[9];
                   3566:                                     if ($locmodtime < $remmodtime) {
                   3567:                                         my $posstransfer = $fname.'.in.transfer';
                   3568:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3569:                                             $removed = 1;
                   3570:                                         } else {
                   3571:                                             $stale = 1;
                   3572:                                         }
                   3573:                                     } else {
                   3574:                                         $removed = 1;
                   3575:                                     }
                   3576:                                 } else {
                   3577:                                     $stale = 1;
                   3578:                                 }
                   3579:                                 if ($stale) {
1.1172.2.124  raeburn  3580:                                     if (unlink($fname)) {
                   3581:                                         if ($uri!~/\.meta$/) {
                   3582:                                             if (-e $fname.'.meta') {
                   3583:                                                 unlink($fname.'.meta');
                   3584:                                             }
                   3585:                                         }
                   3586:                                         my $unsubresult = &unsubscribe($fname);
                   3587:                                         unless ($unsubresult eq 'ok') {
                   3588:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3589:                                         }
                   3590:                                         $removed = 1;
1.1172.2.98  raeburn  3591:                                     }
                   3592:                                 }
                   3593:                             }
                   3594:                         }
                   3595:                     }
                   3596:                 }
                   3597:             }
                   3598:         }
                   3599:     }
                   3600:     return $removed;
                   3601: }
                   3602: 
1.492     albertel 3603: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3604: 
                   3605: sub allowuploaded {
                   3606:     my ($srcurl,$url)=@_;
                   3607:     $url=&clutter(&declutter($url));
                   3608:     my $dir=$url;
                   3609:     $dir=~s/\/[^\/]+$//;
                   3610:     my %httpref=();
                   3611:     my $httpurl=&hreflocation('',$url);
                   3612:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3613:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3614: }
1.477     raeburn  3615: 
1.1172.2.13  raeburn  3616: #
                   3617: # Determine if the current user should be able to edit a particular resource,
                   3618: # when viewing in course context.
                   3619: # (a) When viewing resource used to determine if "Edit" item is included in
                   3620: #     Functions.
                   3621: # (b) When displaying folder contents in course editor, used to determine if
                   3622: #     "Edit" link will be displayed alongside resource.
                   3623: #
                   3624: #  input: six args -- filename (decluttered), course number, course domain,
                   3625: #                   url, symb (if registered) and group (if this is a group
                   3626: #                   item -- e.g., bulletin board, group page etc.).
                   3627: #  output: array of five scalars --
                   3628: #          $cfile -- url for file editing if editable on current server
                   3629: #          $home -- homeserver of resource (i.e., for author if published,
                   3630: #                                           or course if uploaded.).
                   3631: #          $switchserver --  1 if server switch will be needed.
                   3632: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3633: #          $forceview -- 1 if icon/link should be to go to view mode
                   3634: #
                   3635: 
                   3636: sub can_edit_resource {
                   3637:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3638:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3639: #
                   3640: # For aboutme pages user can only edit his/her own.
                   3641: #
                   3642:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3643:         my ($sdom,$sname) = ($1,$2);
                   3644:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3645:             $home = $env{'user.home'};
                   3646:             $cfile = $resurl;
                   3647:             if ($env{'form.forceedit'}) {
                   3648:                 $forceview = 1;
                   3649:             } else {
                   3650:                 $forceedit = 1;
                   3651:             }
                   3652:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3653:         } else {
                   3654:             return;
                   3655:         }
                   3656:     }
                   3657: 
                   3658:     if ($env{'request.course.id'}) {
                   3659:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3660:         if ($group ne '') {
                   3661: # if this is a group homepage or group bulletin board, check group privs
                   3662:             my $allowed = 0;
                   3663:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3664:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3665:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3666:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3667:                     $allowed = 1;
                   3668:                 }
                   3669:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3670:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3671:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3672:                     $allowed = 1;
                   3673:                 }
                   3674:             }
                   3675:             if ($allowed) {
                   3676:                 $home=&homeserver($cnum,$cdom);
                   3677:                 if ($env{'form.forceedit'}) {
                   3678:                     $forceview = 1;
                   3679:                 } else {
                   3680:                     $forceedit = 1;
                   3681:                 }
                   3682:                 $cfile = $resurl;
                   3683:             } else {
                   3684:                 return;
                   3685:             }
                   3686:         } else {
1.1172.2.15  raeburn  3687:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3688:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3689:                     return;
                   3690:                 }
                   3691:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3692: #
                   3693: # No edit allowed where CC has switched to student role.
                   3694: #
                   3695:                 return;
                   3696:             }
                   3697:         }
                   3698:     }
                   3699: 
                   3700:     if ($file ne '') {
                   3701:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3702:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3703:                 $uploaded = 1;
                   3704:                 $incourse = 1;
                   3705:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3706:                     $cfile = &hreflocation('',$file);
                   3707:                     if ($env{'form.forceedit'}) {
                   3708:                         $forceview = 1;
                   3709:                     } else {
                   3710:                         $forceedit = 1;
                   3711:                     }
                   3712:                 }
                   3713:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3714:                 $incourse = 1;
                   3715:                 if ($env{'form.forceedit'}) {
                   3716:                     $forceview = 1;
                   3717:                 } else {
                   3718:                     $forceedit = 1;
                   3719:                 }
                   3720:                 $cfile = $resurl;
                   3721:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3722:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3723:                     $incourse = 1;
                   3724:                     if ($env{'form.forceedit'}) {
                   3725:                         $forceview = 1;
                   3726:                     } else {
                   3727:                         $forceedit = 1;
                   3728:                     }
                   3729:                     $cfile = $resurl;
                   3730:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3731:                     $incourse = 1;
                   3732:                     $cfile = $resurl.'/smpedit';
                   3733:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3734:                     $incourse = 1;
                   3735:                     if ($env{'form.forceedit'}) {
                   3736:                         $forceview = 1;
                   3737:                     } else {
                   3738:                         $forceedit = 1;
                   3739:                     }
                   3740:                     $cfile = $resurl;
1.1172.2.122  raeburn  3741:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3742:                     my ($map,$id,$res) = &decode_symb($symb);
                   3743:                     if ($map =~ /\.page$/) {
                   3744:                         $incourse = 1;
                   3745:                         if ($env{'form.forceedit'}) {
                   3746:                             $forceview = 1;
                   3747:                             $cfile = $map;
                   3748:                         } else {
                   3749:                             $forceedit = 1;
                   3750:                             $cfile =  '/adm/wrapper'.$resurl;
                   3751:                         }
                   3752:                     }
1.1172.2.146.  .1(raebu 3753:22):                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3754:22):                     $incourse = 1;
                   3755:22):                     if ($env{'form.forceedit'}) {
                   3756:22):                         $forceview = 1;
                   3757:22):                     } else {
                   3758:22):                         $forceedit = 1;
                   3759:22):                     }
                   3760:22):                     $cfile = $resurl;
1.1172.2.15  raeburn  3761:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3762:                     $incourse = 1;
                   3763:                     if ($env{'form.forceedit'}) {
                   3764:                         $forceview = 1;
                   3765:                     } else {
                   3766:                         $forceedit = 1;
                   3767:                     }
                   3768:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3769:                 }
                   3770:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3771:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3772:                 if (&is_on_map($template)) {
                   3773:                     $incourse = 1;
                   3774:                     $forceview = 1;
                   3775:                     $cfile = $template;
                   3776:                 }
                   3777:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3778:                 $incourse = 1;
                   3779:                 if ($env{'form.forceedit'}) {
                   3780:                     $forceview = 1;
                   3781:                 } else {
                   3782:                     $forceedit = 1;
                   3783:                 }
                   3784:                 $cfile = $resurl;
1.1172.2.146.  .1(raebu 3785:22):             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3786:22):                 $incourse = 1;
                   3787:22):                 if ($env{'form.forceedit'}) {
                   3788:22):                     $forceview = 1;
                   3789:22):                 } else {
                   3790:22):                     $forceedit = 1;
                   3791:22):                 }
                   3792:22):                 $cfile = $resurl;
1.1172.2.13  raeburn  3793:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3794:                 $incourse = 1;
                   3795:                 $forceview = 1;
                   3796:                 if ($symb) {
                   3797:                     my ($map,$id,$res)=&decode_symb($symb);
                   3798:                     $env{'request.symb'} = $symb;
                   3799:                     $cfile = &clutter($res);
                   3800:                 } else {
                   3801:                     $cfile = $env{'form.suppurl'};
1.1172.2.146.  .1(raebu 3802:22):                     my $escfile = &unescape($cfile);
                   3803:22):                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3804:22):                         $cfile = '/adm/wrapper'.$escfile;
                   3805:22):                     } else {
                   3806:22):                         $escfile =~ s{^http://}{};
                   3807:22):                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3808:22):                     }
1.1172.2.13  raeburn  3809:                 }
1.1172.2.31  raeburn  3810:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3811:                 if ($env{'form.forceedit'}) {
                   3812:                     $forceview = 1;
                   3813:                 } else {
                   3814:                     $forceedit = 1;
                   3815:                 }
                   3816:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3817:             }
                   3818:         }
                   3819:         if ($uploaded || $incourse) {
                   3820:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3821:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3822:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3823:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3824:             # Check that the user has permission to edit this resource
                   3825:             my $setpriv = 1;
                   3826:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3827:             if (defined($cfudom)) {
                   3828:                 $home=&homeserver($cfuname,$cfudom);
                   3829:                 $cfile=$file;
                   3830:             }
                   3831:         }
                   3832:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3833:             (($home ne '') && ($home ne 'no_host'))) {
                   3834:             my @ids=&current_machine_ids();
                   3835:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3836:                 $switchserver=1;
                   3837:             }
                   3838:         }
                   3839:     }
                   3840:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3841: }
                   3842: 
                   3843: sub is_course_upload {
                   3844:     my ($file,$cnum,$cdom) = @_;
                   3845:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3846:     $uploadpath =~ s{^\/}{};
                   3847:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3848:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3849:         return 1;
                   3850:     }
                   3851:     return;
                   3852: }
                   3853: 
                   3854: sub in_course {
                   3855:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3856:     if ($hideprivileged) {
                   3857:         my $skipuser;
1.1172.2.23  raeburn  3858:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3859:         my @possdoms = ($cdom);
                   3860:         if ($coursehash{'checkforpriv'}) {
                   3861:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3862:         }
                   3863:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3864:             $skipuser = 1;
                   3865:             if ($coursehash{'nothideprivileged'}) {
                   3866:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3867:                     my $user;
                   3868:                     if ($item =~ /:/) {
                   3869:                         $user = $item;
                   3870:                     } else {
                   3871:                         $user = join(':',split(/[\@]/,$item));
                   3872:                     }
                   3873:                     if ($user eq $uname.':'.$udom) {
                   3874:                         undef($skipuser);
                   3875:                         last;
                   3876:                     }
                   3877:                 }
                   3878:             }
                   3879:             if ($skipuser) {
                   3880:                 return 0;
                   3881:             }
                   3882:         }
                   3883:     }
                   3884:     $type ||= 'any';
                   3885:     if (!defined($cdom) || !defined($cnum)) {
                   3886:         my $cid  = $env{'request.course.id'};
                   3887:         $cdom = $env{'course.'.$cid.'.domain'};
                   3888:         $cnum = $env{'course.'.$cid.'.num'};
                   3889:     }
                   3890:     my $typesref;
                   3891:     if (($type eq 'any') || ($type eq 'all')) {
                   3892:         $typesref = ['active','previous','future'];
                   3893:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3894:         $typesref = [$type];
                   3895:     }
                   3896:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3897:                               $typesref,undef,[$cdom]);
                   3898:     my ($tmp) = keys(%roles);
                   3899:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3900:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3901:     if (@course_roles > 0) {
                   3902:         return 1;
                   3903:     }
                   3904:     return 0;
                   3905: }
                   3906: 
1.478     albertel 3907: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3908: # input: action, courseID, current domain, intended
1.637     raeburn  3909: #        path to file, source of file, instruction to parse file for objects,
                   3910: #        ref to hash for embedded objects,
                   3911: #        ref to hash for codebase of java objects.
1.1095    raeburn  3912: #        reference to scalar to accommodate mime type determined
                   3913: #          from File::MMagic if $parser = parse.
1.637     raeburn  3914: #
1.485     raeburn  3915: # output: url to file (if action was uploaddoc), 
                   3916: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3917: #
1.478     albertel 3918: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3919: # course.
1.477     raeburn  3920: #
1.478     albertel 3921: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3922: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3923: #          course's home server.
1.477     raeburn  3924: #
1.478     albertel 3925: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3926: #          be copied from $source (current location) to 
                   3927: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3928: #         and will then be copied to
                   3929: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3930: #         course's home server.
1.485     raeburn  3931: #
1.481     raeburn  3932: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3933: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3934: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3935: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3936: #         in course's home server.
1.637     raeburn  3937: #
1.477     raeburn  3938: 
                   3939: sub process_coursefile {
1.1095    raeburn  3940:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3941:         $mimetype)=@_;
1.477     raeburn  3942:     my $fetchresult;
1.638     albertel 3943:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3944:     if ($action eq 'propagate') {
1.638     albertel 3945:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3946: 			     $home);
1.481     raeburn  3947:     } else {
1.477     raeburn  3948:         my $fpath = '';
                   3949:         my $fname = $file;
1.478     albertel 3950:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3951:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3952:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3953:         if ($action eq 'copy') {
                   3954:             if ($source eq '') {
                   3955:                 $fetchresult = 'no source file';
                   3956:                 return $fetchresult;
                   3957:             } else {
                   3958:                 my $destination = $filepath.'/'.$fname;
                   3959:                 rename($source,$destination);
                   3960:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3961:                                  $home);
1.481     raeburn  3962:             }
                   3963:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3964:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3965:             print $fh $env{'form.'.$source};
1.481     raeburn  3966:             close($fh);
1.637     raeburn  3967:             if ($parser eq 'parse') {
1.1024    raeburn  3968:                 my $mm = new File::MMagic;
1.1095    raeburn  3969:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3970:                 if ($type eq 'text/html') {
1.1024    raeburn  3971:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3972:                     unless ($parse_result eq 'ok') {
                   3973:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3974:                     }
1.637     raeburn  3975:                 }
1.1095    raeburn  3976:                 if (ref($mimetype)) {
                   3977:                     $$mimetype = $type;
                   3978:                 } 
1.637     raeburn  3979:             }
1.477     raeburn  3980:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3981:                                  $home);
1.481     raeburn  3982:             if ($fetchresult eq 'ok') {
                   3983:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3984:             } else {
                   3985:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3986:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3987:                 return '/adm/notfound.html';
                   3988:             }
1.477     raeburn  3989:         }
                   3990:     }
1.485     raeburn  3991:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3992:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3993:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3994:     }
                   3995:     return $fetchresult;
                   3996: }
                   3997: 
1.637     raeburn  3998: sub build_filepath {
                   3999:     my ($fpath) = @_;
                   4000:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   4001:     unless ($fpath eq '') {
                   4002:         my @parts=split('/',$fpath);
                   4003:         foreach my $part (@parts) {
                   4004:             $filepath.= '/'.$part;
                   4005:             if ((-e $filepath)!=1) {
                   4006:                 mkdir($filepath,0777);
                   4007:             }
                   4008:         }
                   4009:     }
                   4010:     return $filepath;
                   4011: }
                   4012: 
                   4013: sub store_edited_file {
1.638     albertel 4014:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  4015:     my $file = $primary_url;
                   4016:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   4017:     my $fpath = '';
                   4018:     my $fname = $file;
                   4019:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   4020:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   4021:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  4022:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  4023:     print $fh $content;
                   4024:     close($fh);
1.638     albertel 4025:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  4026:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4027: 			  $home);
1.637     raeburn  4028:     if ($$fetchresult eq 'ok') {
                   4029:         return '/uploaded/'.$fpath.'/'.$fname;
                   4030:     } else {
1.638     albertel 4031:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   4032: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  4033:         return '/adm/notfound.html';
                   4034:     }
                   4035: }
                   4036: 
1.531     albertel 4037: sub clean_filename {
1.831     albertel 4038:     my ($fname,$args)=@_;
1.315     www      4039: # Replace Windows backslashes by forward slashes
1.257     www      4040:     $fname=~s/\\/\//g;
1.831     albertel 4041:     if (!$args->{'keep_path'}) {
                   4042:         # Get rid of everything but the actual filename
                   4043: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   4044:     }
1.315     www      4045: # Replace spaces by underscores
                   4046:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  4047: # Transliterate non-ascii text to ascii
                   4048:     my $lang = &Apache::lonlocal::current_language();
                   4049:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      4050: # Replace all other weird characters by nothing
1.831     albertel 4051:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 4052: # Replace all .\d. sequences with _\d. so they no longer look like version
                   4053: # numbers
                   4054:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.140  raeburn  4055: # Replace three or more adjacent underscores with one for consistency
                   4056: # with loncfile::filename_check() so complete url can be extracted by
                   4057: # lonnet::decode_symb()
                   4058:     $fname=~s/_{3,}/_/g;
1.531     albertel 4059:     return $fname;
                   4060: }
1.1172.2.110  raeburn  4061: 
1.1051    raeburn  4062: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   4063: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   4064: # image with the same aspect ratio as the original, but with dimensions which do 
                   4065: # not exceed $resizewidth and $resizeheight.
                   4066:  
1.984     neumanie 4067: sub resizeImage {
1.1051    raeburn  4068:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   4069:     my $ima = Image::Magick->new;
                   4070:     my $resized;
                   4071:     if (-e $img_path) {
                   4072:         $ima->Read($img_path);
                   4073:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   4074:             my $width = $ima->Get('width');
                   4075:             my $height = $ima->Get('height');
                   4076:             if ($width > $resizewidth) {
                   4077: 	        my $factor = $width/$resizewidth;
                   4078:                 my $newheight = $height/$factor;
                   4079:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   4080:                 $resized = 1;
                   4081:             }
                   4082:         }
                   4083:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   4084:             my $width = $ima->Get('width');
                   4085:             my $height = $ima->Get('height');
                   4086:             if ($height > $resizeheight) {
                   4087:                 my $factor = $height/$resizeheight;
                   4088:                 my $newwidth = $width/$factor;
                   4089:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   4090:                 $resized = 1;
                   4091:             }
                   4092:         }
                   4093:         if ($resized) {
                   4094:             $ima->Write($img_path);
                   4095:         }
                   4096:     }
                   4097:     return;
1.977     amueller 4098: }
                   4099: 
1.608     albertel 4100: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 4101: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  4102: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  4103: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.146.  .13(raeb 4104:-23): #                                    canceloverwrite, scantron, toollogo or ''. 
1.1090    raeburn  4105: #                   if 'coursedoc': upload to the current course
                   4106: #                   if 'existingfile': write file to tmp/overwrites directory 
                   4107: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   4108: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 4109: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  4110: #        $parser - instruction to parse file for objects ($parser = parse) or
                   4111: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   4112: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   4113: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  4114: #        $allfiles - reference to hash for embedded objects
                   4115: #        $codebase - reference to hash for codebase of java objects
1.1172.2.146.  .13(raeb 4116:-23): #        $destuname - username for permanent storage of uploaded file
                   4117:-23): #        $destudom - domain for permanaent storage of uploaded file
1.860     raeburn  4118: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   4119: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  4120: #        $resizewidth - width (pixels) to which to resize uploaded image
                   4121: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  4122: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  4123: #                    from File::MMagic.
1.858     raeburn  4124: # 
1.686     albertel 4125: # output: url of file in userspace, or error: <message> 
                   4126: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 4127: 
1.531     albertel 4128: sub userfileupload {
1.1090    raeburn  4129:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  4130:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 4131:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 4132:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 4133:     $fname=&clean_filename($fname);
1.1090    raeburn  4134:     # See if there is anything left
1.257     www      4135:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  4136:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   4137:     if ($fname =~ /^\./) {
                   4138:         my ($s,$usec) = &gettimeofday();
                   4139:         while (length($usec) < 6) {
                   4140:             $usec = '0'.$usec;
                   4141:         }
                   4142:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   4143:     }
1.1090    raeburn  4144:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   4145:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   4146:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   4147:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  4148:         my $now = time;
1.1090    raeburn  4149:         my $filepath;
1.1095    raeburn  4150:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  4151:              $filepath = 'tmp/helprequests/'.$now;
                   4152:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   4153:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   4154:                          '_'.$env{'user.domain'}.'/pending';
                   4155:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   4156:             my ($docuname,$docudom);
1.1172.2.96  raeburn  4157:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  4158:                 $docudom = $destudom;
                   4159:             } else {
                   4160:                 $docudom = $env{'user.domain'};
                   4161:             }
1.1172.2.96  raeburn  4162:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  4163:                 $docuname = $destuname;
                   4164:             } else {
                   4165:                 $docuname = $env{'user.name'};
                   4166:             }
                   4167:             if (exists($env{'form.group'})) {
                   4168:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4169:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4170:             }
                   4171:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   4172:             if ($context eq 'canceloverwrite') {
                   4173:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   4174:                 if (-e  $tempfile) {
                   4175:                     my @info = stat($tempfile);
                   4176:                     if ($info[9] eq $env{'form.timestamp'}) {
                   4177:                         unlink($tempfile);
                   4178:                     }
                   4179:                 }
                   4180:                 return;
1.523     raeburn  4181:             }
                   4182:         }
1.1090    raeburn  4183:         # Create the directory if not present
1.741     raeburn  4184:         my @parts=split(/\//,$filepath);
                   4185:         my $fullpath = $perlvar{'lonDaemons'};
                   4186:         for (my $i=0;$i<@parts;$i++) {
                   4187:             $fullpath .= '/'.$parts[$i];
                   4188:             if ((-e $fullpath)!=1) {
                   4189:                 mkdir($fullpath,0777);
                   4190:             }
                   4191:         }
1.1172.2.96  raeburn  4192:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  4193:         print $fh $env{'form.'.$formname};
                   4194:         close($fh);
1.1090    raeburn  4195:         if ($context eq 'existingfile') {
                   4196:             my @info = stat($fullpath.'/'.$fname);
                   4197:             return ($fullpath.'/'.$fname,$info[9]);
                   4198:         } else {
                   4199:             return $fullpath.'/'.$fname;
                   4200:         }
1.523     raeburn  4201:     }
1.995     raeburn  4202:     if ($subdir eq 'scantron') {
                   4203:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4204:     } else {
1.995     raeburn  4205:         $fname="$subdir/$fname";
                   4206:     }
1.1090    raeburn  4207:     if ($context eq 'coursedoc') {
1.638     albertel 4208: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4209: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4210:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4211:             return &finishuserfileupload($docuname,$docudom,
                   4212: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4213: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4214:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4215:         } else {
1.1172.2.21  raeburn  4216:             if ($env{'form.folder'}) {
                   4217:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4218:             }
1.638     albertel 4219:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4220: 				       $fname,$formname,$parser,
1.1095    raeburn  4221: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4222:         }
1.719     banghart 4223:     } elsif (defined($destuname)) {
                   4224:         my $docuname=$destuname;
                   4225:         my $docudom=$destudom;
1.860     raeburn  4226: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4227: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4228:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4229:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4230:     } else {
1.638     albertel 4231:         my $docuname=$env{'user.name'};
                   4232:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  4233:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4234:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4235:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4236:         }
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:     }
1.271     www      4242: }
                   4243: 
                   4244: sub finishuserfileupload {
1.860     raeburn  4245:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4246:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4247:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4248:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4249:   
1.860     raeburn  4250:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4251:     $file=$fname;
                   4252:     if ($fname=~m|/|) {
                   4253:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4254: 	$path.=$fnamepath.'/';
                   4255:     }
1.259     www      4256:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4257:     my $count;
                   4258:     for ($count=4;$count<=$#parts;$count++) {
                   4259:         $filepath.="/$parts[$count]";
                   4260:         if ((-e $filepath)!=1) {
                   4261: 	    mkdir($filepath,0777);
                   4262:         }
                   4263:     }
1.984     neumanie 4264: 
1.258     www      4265: # Save the file
                   4266:     {
1.1172.2.96  raeburn  4267: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4268: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4269: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4270: 	    return '/adm/notfound.html';
                   4271: 	}
1.1090    raeburn  4272:         if ($context eq 'overwrite') {
1.1117    foxr     4273:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4274:             my $target = $filepath.'/'.$file;
                   4275:             if (-e $source) {
                   4276:                 my @info = stat($source);
                   4277:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4278:                     unless (&File::Copy::move($source,$target)) {
                   4279:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4280:                         return "Moving from $source failed";
                   4281:                     }
                   4282:                 } else {
                   4283:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4284:                 }
                   4285:             } else {
                   4286:                 return "Temporary file: $source missing";
                   4287:             }
                   4288:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4289: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4290: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4291: 	    return '/adm/notfound.html';
                   4292: 	}
1.570     albertel 4293: 	close(FH);
1.1051    raeburn  4294:         if ($resizewidth && $resizeheight) {
                   4295:             my $mm = new File::MMagic;
                   4296:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4297:             if ($mime_type =~ m{^image/}) {
                   4298: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4299:             }  
1.977     amueller 4300: 	}
1.258     www      4301:     }
1.1152    raeburn  4302:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4303:         if (ref($mimetype)) {
                   4304:             if ($$mimetype eq '') {
                   4305:                 my $mm = new File::MMagic;
                   4306:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4307:                 $$mimetype = $type;
                   4308:             }
                   4309:         }
                   4310:     }
1.1172.2.109  raeburn  4311:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4312:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4313:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4314:                                                        $allfiles,$codebase);
                   4315:             unless ($parse_result eq 'ok') {
                   4316:                 &logthis('Failed to parse '.$filepath.$file.
                   4317: 	   	         ' for embedded media: '.$parse_result); 
                   4318:             }
1.637     raeburn  4319:         }
1.1172.2.109  raeburn  4320:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4321:         my $format = $env{'form.scantron_format'};
                   4322:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4323:     }
1.860     raeburn  4324:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4325:         my $input = $filepath.'/'.$file;
                   4326:         my $output = $filepath.'/'.'tn-'.$file;
1.1172.2.146.  .13(raeb 4327:-23):         my $makethumb;
1.860     raeburn  4328:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.146.  .13(raeb 4329:-23):         if ($context eq 'toollogo') {
                   4330:-23):             my ($fullwidth,$fullheight) = &check_dimensions($input);
                   4331:-23):             if ($fullwidth ne '' && $fullheight ne '') {
                   4332:-23):                 if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
                   4333:-23):                     $makethumb = 1;
                   4334:-23):                 }
                   4335:-23):             }
                   4336:-23):         } else {
                   4337:-23):             $makethumb = 1;
                   4338:-23):         }
                   4339:-23):         if ($makethumb) {
                   4340:-23):             my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4341:-23):             system({$args[0]} @args);
                   4342:-23):             if (-e $filepath.'/'.'tn-'.$file) {
                   4343:-23):                 $fetchthumb  = 1;
                   4344:-23):             }
1.860     raeburn  4345:         }
                   4346:     }
1.858     raeburn  4347:  
1.259     www      4348: # Notify homeserver to grep it
                   4349: #
1.984     neumanie 4350:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4351:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4352:     if ($fetchresult eq 'ok') {
1.860     raeburn  4353:         if ($fetchthumb) {
                   4354:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4355:             if ($thumbresult ne 'ok') {
                   4356:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4357:                          $docuhome.': '.$thumbresult);
                   4358:             }
                   4359:         }
1.259     www      4360: #
1.258     www      4361: # Return the URL to it
1.494     albertel 4362:         return '/uploaded/'.$path.$file;
1.263     www      4363:     } else {
1.494     albertel 4364:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4365: 		 ': '.$fetchresult);
1.263     www      4366:         return '/adm/notfound.html';
1.858     raeburn  4367:     }
1.493     albertel 4368: }
                   4369: 
1.637     raeburn  4370: sub extract_embedded_items {
1.961     raeburn  4371:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4372:     my @state = ();
1.1164    raeburn  4373:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4374:     my %javafiles = (
                   4375:                       codebase => '',
                   4376:                       code => '',
                   4377:                       archive => ''
                   4378:                     );
                   4379:     my %mediafiles = (
                   4380:                       src => '',
                   4381:                       movie => '',
                   4382:                      );
1.648     raeburn  4383:     my $p;
                   4384:     if ($content) {
                   4385:         $p = HTML::LCParser->new($content);
                   4386:     } else {
1.961     raeburn  4387:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4388:     }
1.641     albertel 4389:     while (my $t=$p->get_token()) {
1.640     albertel 4390: 	if ($t->[0] eq 'S') {
                   4391: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4392: 	    push(@state, $tagname);
1.648     raeburn  4393:             if (lc($tagname) eq 'allow') {
                   4394:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4395:             }
1.640     albertel 4396: 	    if (lc($tagname) eq 'img') {
                   4397: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4398: 	    }
1.886     albertel 4399: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4400:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4401: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4402:                 }
1.886     albertel 4403: 	    }
1.645     raeburn  4404:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4405:                 my $src;
1.645     raeburn  4406:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4407:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4408:                 } else {
1.1164    raeburn  4409:                     if ($attr->{'src'} ne '') {
                   4410:                         $src = $attr->{'src'};
                   4411:                         &add_filetype($allfiles,$src,'src');
                   4412:                     }
                   4413:                 }
                   4414:                 my $text = $p->get_trimmed_text();
                   4415:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4416:                     my @swfargs = split(/,/,$1);
                   4417:                     foreach my $item (@swfargs) {
                   4418:                         $item =~ s/["']//g;
                   4419:                         $item =~ s/^\s+//;
                   4420:                         $item =~ s/\s+$//;
                   4421:                     }
                   4422:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4423:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4424:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4425:                         } else {
                   4426:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4427:                         }
                   4428:                     }
1.645     raeburn  4429:                 }
                   4430:             }
                   4431:             if (lc($tagname) eq 'link') {
                   4432:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4433:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4434:                 }
                   4435:             }
1.640     albertel 4436: 	    if (lc($tagname) eq 'object' ||
                   4437: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4438: 		foreach my $item (keys(%javafiles)) {
                   4439: 		    $javafiles{$item} = '';
                   4440: 		}
1.1164    raeburn  4441:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4442:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4443:                 }
1.640     albertel 4444: 	    }
                   4445: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4446: 		my $name = lc($attr->{'name'});
                   4447: 		foreach my $item (keys(%javafiles)) {
                   4448: 		    if ($name eq $item) {
                   4449: 			$javafiles{$item} = $attr->{'value'};
                   4450: 			last;
                   4451: 		    }
                   4452: 		}
1.1164    raeburn  4453:                 my $pathfrom;
1.640     albertel 4454: 		foreach my $item (keys(%mediafiles)) {
                   4455: 		    if ($name eq $item) {
1.1164    raeburn  4456:                         $pathfrom = $attr->{'value'};
                   4457:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4458: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4459: 			last;
                   4460: 		    }
                   4461: 		}
1.1164    raeburn  4462:                 if ($name eq 'flashvars') {
                   4463:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4464:                 }
                   4465:                 if ($pathfrom ne '') {
                   4466:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4467:                                          $pathfrom);
                   4468:                 }
1.640     albertel 4469: 	    }
                   4470: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4471: 		foreach my $item (keys(%javafiles)) {
                   4472: 		    if ($attr->{$item}) {
                   4473: 			$javafiles{$item} = $attr->{$item};
                   4474: 			last;
                   4475: 		    }
                   4476: 		}
                   4477: 		foreach my $item (keys(%mediafiles)) {
                   4478: 		    if ($attr->{$item}) {
                   4479: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4480: 			last;
                   4481: 		    }
                   4482: 		}
1.1164    raeburn  4483:                 if (lc($tagname) eq 'embed') {
                   4484:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4485:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4486:                                              $attr->{'src'});
                   4487:                     }
                   4488:                 }
1.640     albertel 4489: 	    }
1.1172.2.35  raeburn  4490:             if (lc($tagname) eq 'iframe') {
                   4491:                 my $src = $attr->{'src'} ;
                   4492:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4493:                     &add_filetype($allfiles,$src,'src');
                   4494:                 } elsif ($src =~ m{^/}) {
                   4495:                     if ($env{'request.course.id'}) {
                   4496:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4497:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4498:                         my $url = &hreflocation('',$fullpath);
                   4499:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4500:                             my $relpath = $1;
                   4501:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4502:                                 &add_filetype($allfiles,$1,'src');
                   4503:                             }
                   4504:                         }
                   4505:                     }
                   4506:                 }
                   4507:             }
1.1164    raeburn  4508:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4509:                 pop(@state);
1.1164    raeburn  4510:             }
1.640     albertel 4511: 	} elsif ($t->[0] eq 'E') {
                   4512: 	    my ($tagname) = ($t->[1]);
                   4513: 	    if ($javafiles{'codebase'} ne '') {
                   4514: 		$javafiles{'codebase'} .= '/';
                   4515: 	    }  
                   4516: 	    if (lc($tagname) eq 'applet' ||
                   4517: 		lc($tagname) eq 'object' ||
                   4518: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4519: 		) {
                   4520: 		foreach my $item (keys(%javafiles)) {
                   4521: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4522: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4523: 			&add_filetype($allfiles,$file,$item);
                   4524: 		    }
                   4525: 		}
                   4526: 	    } 
                   4527: 	    pop @state;
                   4528: 	}
                   4529:     }
1.1164    raeburn  4530:     foreach my $id (sort(keys(%flashvars))) {
                   4531:         if ($shockwave{$id} ne '') {
                   4532:             my @pairs = split(/\&/,$flashvars{$id});
                   4533:             foreach my $pair (@pairs) {
                   4534:                 my ($key,$value) = split(/\=/,$pair);
                   4535:                 if ($key eq 'thumb') {
                   4536:                     &add_filetype($allfiles,$value,$key);
                   4537:                 } elsif ($key eq 'content') {
                   4538:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4539:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4540:                     if ($ext ne '') {
                   4541:                         &add_filetype($allfiles,$path.$value,$ext);
                   4542:                     }
                   4543:                 }
                   4544:             }
                   4545:         }
                   4546:     }
1.637     raeburn  4547:     return 'ok';
                   4548: }
                   4549: 
1.639     albertel 4550: sub add_filetype {
                   4551:     my ($allfiles,$file,$type)=@_;
                   4552:     if (exists($allfiles->{$file})) {
                   4553: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4554: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4555: 	}
                   4556:     } else {
                   4557: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4558:     }
                   4559: }
                   4560: 
1.1164    raeburn  4561: sub embedded_dependency {
                   4562:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4563:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4564:         if (($identifier ne '') &&
                   4565:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4566:             ($pathfrom ne '')) {
                   4567:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4568:             foreach my $dep (@{$related->{$identifier}}) {
                   4569:                 &add_filetype($allfiles,$path.$dep,'object');
                   4570:             }
                   4571:         }
                   4572:     }
                   4573:     return;
                   4574: }
                   4575: 
1.1172.2.146.  .13(raeb 4576:-23): sub check_dimensions {
                   4577:-23):     my ($inputfile) = @_;
                   4578:-23):     my ($fullwidth,$fullheight);
                   4579:-23):     if (($inputfile =~ m|^[/\w.\-]+$|) && (-e $inputfile)) {
                   4580:-23):         my $mm = new File::MMagic;
                   4581:-23):         my $mime_type = $mm->checktype_filename($inputfile);
                   4582:-23):         if ($mime_type =~ m{^image/}) {
                   4583:-23):             if (open(PIPE,"identify $inputfile 2>&1 |")) {
                   4584:-23):                 my $imageinfo = <PIPE>;
                   4585:-23):                 if (!close(PIPE)) {
                   4586:-23):                     &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
                   4587:-23):                 }
                   4588:-23):                 chomp($imageinfo);
                   4589:-23):                 my ($fullsize) =
                   4590:-23):                     ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
                   4591:-23):                 if ($fullsize) {
                   4592:-23):                     ($fullwidth,$fullheight) = split(/x/,$fullsize);
                   4593:-23):                 }
                   4594:-23):             }
                   4595:-23):         }
                   4596:-23):     }
                   4597:-23):     return ($fullwidth,$fullheight);
                   4598:-23): }
                   4599:-23): 
1.1172.2.109  raeburn  4600: sub bubblesheet_converter {
                   4601:     my ($cdom,$fullpath,$config,$format) = @_;
                   4602:     if ((&domain($cdom) ne '') &&
                   4603:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4604:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4605:         my (%csvcols,%csvoptions);
                   4606:         if (ref($config->{'fields'}) eq 'HASH') {
                   4607:             %csvcols = %{$config->{'fields'}};
                   4608:         }
                   4609:         if (ref($config->{'options'}) eq 'HASH') {
                   4610:             %csvoptions = %{$config->{'options'}};
                   4611:         }
                   4612:         my %csvbynum = reverse(%csvcols);
                   4613:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4614:         if (keys(%scantronconf)) {
                   4615:             my %bynum = (
                   4616:                           $scantronconf{CODEstart} => 'CODEstart',
                   4617:                           $scantronconf{IDstart}   => 'IDstart',
                   4618:                           $scantronconf{PaperID}   => 'PaperID',
                   4619:                           $scantronconf{FirstName} => 'FirstName',
                   4620:                           $scantronconf{LastName}  => 'LastName',
                   4621:                           $scantronconf{Qstart}    => 'Qstart',
                   4622:                         );
                   4623:             my @ordered;
                   4624:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4625:                 push(@ordered,$bynum{$item});
                   4626:             }
                   4627:             my %mapstart = (
                   4628:                               CODEstart => 'CODE',
                   4629:                               IDstart   => 'ID',
                   4630:                               PaperID   => 'PaperID',
                   4631:                               FirstName => 'FirstName',
                   4632:                               LastName  => 'LastName',
                   4633:                               Qstart    => 'FirstQuestion',
                   4634:                            );
                   4635:             my %maplength = (
                   4636:                               CODEstart => 'CODElength',
                   4637:                               IDstart   => 'IDlength',
                   4638:                               PaperID   => 'PaperIDlength',
                   4639:                               FirstName => 'FirstNamelength',
                   4640:                               LastName  => 'LastNamelength',
                   4641:             );
                   4642:             if (open(my $fh,'<',$fullpath)) {
                   4643:                 my $output;
                   4644:                 my %lettdig = &letter_to_digits();
                   4645:                 my %diglett = reverse(%lettdig);
                   4646:                 my $numletts = scalar(keys(%lettdig));
                   4647:                 my $num = 0;
                   4648:                 while (my $line=<$fh>) {
                   4649:                     $num ++;
                   4650:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4651:                     $line =~ s{[\r\n]+$}{};
                   4652:                     my %found;
1.1172.2.143  raeburn  4653:                     my @values = split(/,/,$line,-1);
1.1172.2.109  raeburn  4654:                     my ($qstart,$record);
                   4655:                     for (my $i=0; $i<@values; $i++) {
                   4656:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4657:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4658:                             if ($values[$i] eq '') {
                   4659:                                 $values[$i] = $scantronconf{'Qoff'};
                   4660:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4661:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4662:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4663:                                 }
                   4664:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4665:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4666:                                     $values[$i] = $diglett{$values[$i]};
                   4667:                                 }
                   4668:                             } else {
                   4669:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4670:                                     my $digit;
                   4671:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4672:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4673:                                         if ($values[$i] eq 'J') {
                   4674:                                             $digit += $numletts;
                   4675:                                         }
                   4676:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4677:                                         $digit = $values[$i]-1;
                   4678:                                         if ($values[$i] eq '0') {
                   4679:                                             $digit += $numletts;
                   4680:                                         }
                   4681:                                     }
                   4682:                                     my $qval='';
                   4683:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4684:                                         if ($j == $digit) {
                   4685:                                             $qval .= $scantronconf{'Qon'};
                   4686:                                         } else {
                   4687:                                             $qval .= $scantronconf{'Qoff'};
                   4688:                                         }
                   4689:                                     }
                   4690:                                     $values[$i] = $qval;
                   4691:                                 }
                   4692:                             }
                   4693:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4694:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4695:                             }
                   4696:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4697:                             if ($numblank > 0) {
                   4698:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4699:                             }
                   4700:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4701:                                 $qstart = $i;
                   4702:                                 $found{$csvbynum{$i}} = $values[$i];
                   4703:                             } else {
                   4704:                                 $found{'FirstQuestion'} .= $values[$i];
                   4705:                             }
                   4706:                         } elsif (exists($csvbynum{$i})) {
                   4707:                             if ($csvoptions{'rem'}) {
                   4708:                                 $values[$i] =~ s/^\s+//;
                   4709:                             }
                   4710:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4711:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4712:                                     $values[$i] = '0'.$values[$i];
                   4713:                                 }
                   4714:                             }
                   4715:                             $found{$csvbynum{$i}} = $values[$i];
                   4716:                         }
                   4717:                     }
                   4718:                     foreach my $item (@ordered) {
                   4719:                         my $currlength = 1+length($record);
                   4720:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4721:                         if ($numspaces > 0) {
                   4722:                             $record .= (' ' x $numspaces);
                   4723:                         }
                   4724:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4725:                             unless ($item eq 'Qstart') {
                   4726:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4727:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4728:                                 }
                   4729:                             }
                   4730:                             $record .= $found{$mapstart{$item}};
                   4731:                         }
                   4732:                     }
                   4733:                     $output .= "$record\n";
                   4734:                 }
                   4735:                 close($fh);
                   4736:                 if ($output) {
                   4737:                     if (open(my $fh,'>',$fullpath)) {
                   4738:                         print $fh $output;
                   4739:                         close($fh);
                   4740:                     }
                   4741:                 }
                   4742:             }
                   4743:         }
                   4744:         return;
                   4745:     }
                   4746: }
                   4747: 
                   4748: sub letter_to_digits {
                   4749:     my %lettdig = (
                   4750:                     A => 1,
                   4751:                     B => 2,
                   4752:                     C => 3,
                   4753:                     D => 4,
                   4754:                     E => 5,
                   4755:                     F => 6,
                   4756:                     G => 7,
                   4757:                     H => 8,
                   4758:                     I => 9,
                   4759:                     J => 0,
                   4760:                   );
                   4761:     return %lettdig;
                   4762: }
                   4763: 
                   4764: sub get_scantron_config {
                   4765:     my ($which,$cdom) = @_;
                   4766:     my @lines = &get_scantronformat_file($cdom);
                   4767:     my %config;
                   4768:     #FIXME probably should move to XML it has already gotten a bit much now
                   4769:     foreach my $line (@lines) {
                   4770:         my ($name,$descrip)=split(/:/,$line);
                   4771:         if ($name ne $which ) { next; }
                   4772:         chomp($line);
                   4773:         my @config=split(/:/,$line);
                   4774:         $config{'name'}=$config[0];
                   4775:         $config{'description'}=$config[1];
                   4776:         $config{'CODElocation'}=$config[2];
                   4777:         $config{'CODEstart'}=$config[3];
                   4778:         $config{'CODElength'}=$config[4];
                   4779:         $config{'IDstart'}=$config[5];
                   4780:         $config{'IDlength'}=$config[6];
                   4781:         $config{'Qstart'}=$config[7];
                   4782:         $config{'Qlength'}=$config[8];
                   4783:         $config{'Qoff'}=$config[9];
                   4784:         $config{'Qon'}=$config[10];
                   4785:         $config{'PaperID'}=$config[11];
                   4786:         $config{'PaperIDlength'}=$config[12];
                   4787:         $config{'FirstName'}=$config[13];
                   4788:         $config{'FirstNamelength'}=$config[14];
                   4789:         $config{'LastName'}=$config[15];
                   4790:         $config{'LastNamelength'}=$config[16];
                   4791:         $config{'BubblesPerRow'}=$config[17];
                   4792:         last;
                   4793:     }
                   4794:     return %config;
                   4795: }
                   4796: 
                   4797: sub get_scantronformat_file {
                   4798:     my ($cdom) = @_;
                   4799:     if ($cdom eq '') {
                   4800:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4801:     }
                   4802:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4803:     my $gottab = 0;
                   4804:     my @lines;
                   4805:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4806:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4807:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4808:             if ($formatfile ne '-1') {
                   4809:                 @lines = split("\n",$formatfile,-1);
                   4810:                 $gottab = 1;
                   4811:             }
                   4812:         }
                   4813:     }
                   4814:     if (!$gottab) {
                   4815:         my $confname = $cdom.'-domainconfig';
                   4816:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4817:         my $formatfile = &getfile($default);
                   4818:         if ($formatfile ne '-1') {
                   4819:             @lines = split("\n",$formatfile,-1);
                   4820:             $gottab = 1;
                   4821:         }
                   4822:     }
                   4823:     if (!$gottab) {
                   4824:         my @domains = &current_machine_domains();
                   4825:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4826:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4827:                 @lines = <$fh>;
                   4828:                 close($fh);
                   4829:             }
                   4830:         } else {
                   4831:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4832:                 @lines = <$fh>;
                   4833:                 close($fh);
                   4834:             }
                   4835:         }
1.1172.2.146.  .8(raebu 4836:23):         chomp(@lines);
1.1172.2.109  raeburn  4837:     }
                   4838:     return @lines;
                   4839: }
                   4840: 
1.493     albertel 4841: sub removeuploadedurl {
1.984     neumanie 4842:     my ($url)=@_;	
                   4843:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4844:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4845: }
                   4846: 
                   4847: sub removeuserfile {
                   4848:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4849:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4850:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4851:     if ($result eq 'ok') {	
1.798     raeburn  4852:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4853:             my $metafile = $fname.'.meta';
                   4854:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4855: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4856:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4857:             my $sqlresult = 
1.823     albertel 4858:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4859:                                         'portfolio_metadata',$group,
                   4860:                                         'delete');
1.798     raeburn  4861:         }
                   4862:     }
                   4863:     return $result;
1.257     www      4864: }
1.15      www      4865: 
1.530     albertel 4866: sub mkdiruserfile {
                   4867:     my ($docuname,$docudom,$dir)=@_;
                   4868:     my $home=&homeserver($docuname,$docudom);
                   4869:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4870: }
                   4871: 
1.531     albertel 4872: sub renameuserfile {
                   4873:     my ($docuname,$docudom,$old,$new)=@_;
                   4874:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4875:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4876:                         &escape("$old").':'.&escape("$new"),$home);
                   4877:     if ($result eq 'ok') {
                   4878:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4879:             my $oldmeta = $old.'.meta';
                   4880:             my $newmeta = $new.'.meta';
                   4881:             my $metaresult = 
                   4882:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4883: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4884:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4885:             my $sqlresult = 
1.823     albertel 4886:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4887:                                         'portfolio_metadata',$group,
                   4888:                                         'delete');
1.798     raeburn  4889:         }
                   4890:     }
                   4891:     return $result;
1.531     albertel 4892: }
                   4893: 
1.14      www      4894: # ------------------------------------------------------------------------- Log
                   4895: 
                   4896: sub log {
                   4897:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4898:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4899: }
                   4900: 
                   4901: # ------------------------------------------------------------------ Course Log
1.352     www      4902: #
                   4903: # This routine flushes several buffers of non-mission-critical nature
                   4904: #
1.157     www      4905: 
                   4906: sub flushcourselogs {
1.352     www      4907:     &logthis('Flushing log buffers');
                   4908: #
                   4909: # course logs
                   4910: # This is a log of all transactions in a course, which can be used
                   4911: # for data mining purposes
                   4912: #
                   4913: # It also collects the courseid database, which lists last transaction
                   4914: # times and course titles for all courseids
                   4915: #
                   4916:     my %courseidbuffer=();
1.921     raeburn  4917:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4918:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4919: 		          &escape($courselogs{$crsid}),
                   4920: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4921: 	    delete $courselogs{$crsid};
                   4922:         } else {
                   4923:             &logthis('Failed to flush log buffer for '.$crsid);
                   4924:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4925:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4926:                         " exceeded maximum size, deleting.</font>");
                   4927:                delete $courselogs{$crsid};
                   4928:             }
1.352     www      4929:         }
1.920     raeburn  4930:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4931:             'description' => $coursedescrbuf{$crsid},
                   4932:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4933:             'type'        => $coursetypebuf{$crsid},
                   4934:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4935:         };
1.191     harris41 4936:     }
1.352     www      4937: #
                   4938: # Write course id database (reverse lookup) to homeserver of courses 
                   4939: # Is used in pickcourse
                   4940: #
1.840     albertel 4941:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4942:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4943:                                     $courseidbuffer{$crs_home},
                   4944:                                     $crs_home,'timeonly');
1.352     www      4945:     }
                   4946: #
                   4947: # File accesses
                   4948: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4949: #
1.449     matthew  4950:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4951:         if ($entry =~ /___count$/) {
                   4952:             my ($dom,$name);
1.807     albertel 4953:             ($dom,$name,undef)=
1.811     albertel 4954: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4955:             if (! defined($dom) || $dom eq '' || 
                   4956:                 ! defined($name) || $name eq '') {
1.620     albertel 4957:                 my $cid = $env{'request.course.id'};
1.1172.2.142  raeburn  4958: #
                   4959: # FIXME 11/29/2021
                   4960: # Typo in rev. 1.458 (2003/12/09)??
                   4961: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
                   4962: #
1.1172.2.146.  .13(raeb 4963:-23): # While these remain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
1.1172.2.142  raeburn  4964: # $dom and $name will always be null, so the &inc() call will default to storing this data
                   4965: # in a nohist_accesscount.db file for the user rather than the course.
                   4966: #
                   4967: # That said there is a lot of noise in the data being stored.
                   4968: # So counts for prtspool/  and adm/ etc. are recorded.
                   4969: #
                   4970: # A review of which items ending '___count' are written to %accesshash should likely be
                   4971: # made before deciding whether to set these to 'course.' instead of 'request.'
                   4972: #
                   4973: # Under the current scheme each user receives a nohist_accesscount.db file listing
                   4974: # accesses for things which are not published resources, regardless of course, and
                   4975: # there is not a nohist_accesscount.db file in a course, which might log accesses from
                   4976: # anyone in the course for things which are not published resources.
                   4977: #
                   4978: # For an author, nohist_accesscount.db ends up having records for other items
                   4979: # mixed up with the legitimate access counts for the author's published resources.
                   4980: #
1.620     albertel 4981:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4982:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4983:             }
1.450     matthew  4984:             my $value = $accesshash{$entry};
                   4985:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4986:             my %temphash=($url => $value);
1.449     matthew  4987:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4988:             if ($result eq 'ok') {
                   4989:                 delete $accesshash{$entry};
                   4990:             }
                   4991:         } else {
1.811     albertel 4992:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4993:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4994:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4995:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4996:                 delete $accesshash{$entry};
                   4997:             }
1.185     www      4998:         }
1.191     harris41 4999:     }
1.352     www      5000: #
                   5001: # Roles
                   5002: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   5003: #
1.800     albertel 5004:     foreach my $entry (keys(%userrolehash)) {
1.351     www      5005:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      5006: 	    split(/\:/,$entry);
                   5007:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      5008:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      5009:                 $rudom,$runame) eq 'ok') {
                   5010: 	    delete $userrolehash{$entry};
                   5011:         }
                   5012:     }
1.662     raeburn  5013: #
1.1172.2.90  raeburn  5014: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  5015: #
                   5016:     my %domrolebuffer = ();
1.1000    raeburn  5017:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 5018:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  5019:         if ($domrolebuffer{$rudom}) {
                   5020:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   5021:                       '='.&escape($domainrolehash{$entry});
                   5022:         } else {
                   5023:             $domrolebuffer{$rudom}.=&escape($entry).
                   5024:                       '='.&escape($domainrolehash{$entry});
                   5025:         }
                   5026:         delete $domainrolehash{$entry};
                   5027:     }
                   5028:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  5029:         my %servers;
                   5030:         if (defined(&domain($dom,'primary'))) {
                   5031:             my $primary=&domain($dom,'primary');
                   5032:             my $hostname=&hostname($primary);
                   5033:             $servers{$primary} = $hostname;
                   5034:         } else {
                   5035:             %servers = &get_servers($dom,'library');
                   5036:         }
1.841     albertel 5037: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  5038: 	    if (&reply('domroleput:'.$dom.':'.
                   5039: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   5040: 	        last;
                   5041: 	    } else {
1.841     albertel 5042: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   5043: 	    }
1.662     raeburn  5044:         }
                   5045:     }
1.186     www      5046:     $dumpcount++;
1.157     www      5047: }
                   5048: 
                   5049: sub courselog {
                   5050:     my $what=shift;
1.158     www      5051:     $what=time.':'.$what;
1.620     albertel 5052:     unless ($env{'request.course.id'}) { return ''; }
                   5053:     $coursedombuf{$env{'request.course.id'}}=
                   5054:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5055:     $coursenumbuf{$env{'request.course.id'}}=
                   5056:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   5057:     $coursehombuf{$env{'request.course.id'}}=
                   5058:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   5059:     $coursedescrbuf{$env{'request.course.id'}}=
                   5060:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   5061:     $courseinstcodebuf{$env{'request.course.id'}}=
                   5062:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   5063:     $courseownerbuf{$env{'request.course.id'}}=
                   5064:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  5065:     $coursetypebuf{$env{'request.course.id'}}=
                   5066:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 5067:     if (defined $courselogs{$env{'request.course.id'}}) {
                   5068: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      5069:     } else {
1.620     albertel 5070: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      5071:     }
1.620     albertel 5072:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      5073: 	&flushcourselogs();
                   5074:     }
1.158     www      5075: }
                   5076: 
                   5077: sub courseacclog {
                   5078:     my $fnsymb=shift;
1.620     albertel 5079:     unless ($env{'request.course.id'}) { return ''; }
                   5080:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      5081:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      5082:         $what.=':POST';
1.583     matthew  5083:         # FIXME: Probably ought to escape things....
1.800     albertel 5084: 	foreach my $key (keys(%env)) {
                   5085:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  5086:                 my $formitem = $1;
                   5087:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   5088:                     $what.=':'.$formitem.'='.$env{$key};
                   5089:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131  raeburn  5090:                     if ($formitem eq 'proctorpassword') {
1.1172.2.132  raeburn  5091:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131  raeburn  5092:                     } else {
                   5093:                         $what.=':'.$formitem.'='.$env{$key};
                   5094:                     }
1.975     raeburn  5095:                 }
1.158     www      5096:             }
1.191     harris41 5097:         }
1.583     matthew  5098:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   5099:         # FIXME: We should not be depending on a form parameter that someone
                   5100:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 5101:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  5102:             $what.= ':POST';
                   5103:             # FIXME: Probably ought to escape things....
                   5104:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   5105:                                  'crsdiscuss') {
1.620     albertel 5106:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  5107:             }
                   5108:         }
1.158     www      5109:     }
                   5110:     &courselog($what);
1.149     www      5111: }
                   5112: 
1.185     www      5113: sub countacc {
                   5114:     my $url=&declutter(shift);
1.458     matthew  5115:     return if (! defined($url) || $url eq '');
1.620     albertel 5116:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      5117: #
                   5118: # Mark that this url was used in this course
                   5119: #
1.620     albertel 5120:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      5121: #
                   5122: # Increase the access count for this resource in this child process
                   5123: #
1.281     www      5124:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  5125:     $accesshash{$key}++;
1.185     www      5126: }
1.349     www      5127: 
1.361     www      5128: sub linklog {
                   5129:     my ($from,$to)=@_;
                   5130:     $from=&declutter($from);
                   5131:     $to=&declutter($to);
                   5132:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   5133:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   5134: }
1.1160    www      5135: 
                   5136: sub statslog {
                   5137:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   5138:     if ($users<2) { return; }
                   5139:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   5140:             'course'       => $env{'request.course.id'},
                   5141:             'sections'     => '"all"',
                   5142:             'num_students' => $users,
                   5143:             'part'         => $part,
                   5144:             'symb'         => $symb,
                   5145:             'mean_tries'   => $av_attempts,
                   5146:             'deg_of_diff'  => $degdiff});
                   5147:     foreach my $key (keys(%dynstore)) {
                   5148:         $accesshash{$key}=$dynstore{$key};
                   5149:     }
                   5150: }
1.361     www      5151:   
1.349     www      5152: sub userrolelog {
                   5153:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 5154:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      5155:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5156:        $userrolehash
                   5157:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      5158:                     =$tend.':'.$tstart;
1.662     raeburn  5159:     }
1.1169    droeschl 5160:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 5161:        $userrolehash
                   5162:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   5163:                     =$tend.':'.$tstart;
                   5164:     }
1.1172.2.90  raeburn  5165:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  5166:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5167:        $domainrolehash
                   5168:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   5169:                     = $tend.':'.$tstart;
                   5170:     }
1.351     www      5171: }
                   5172: 
1.957     raeburn  5173: sub courserolelog {
                   5174:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  5175:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   5176:         my $cdom = $1;
                   5177:         my $cnum = $2;
                   5178:         my $sec = $3;
                   5179:         my $namespace = 'rolelog';
                   5180:         my %storehash = (
                   5181:                            role    => $trole,
                   5182:                            start   => $tstart,
                   5183:                            end     => $tend,
                   5184:                            selfenroll => $selfenroll,
                   5185:                            context    => $context,
                   5186:                         );
                   5187:         if ($trole eq 'gr') {
                   5188:             $namespace = 'groupslog';
                   5189:             $storehash{'group'} = $sec;
                   5190:         } else {
                   5191:             $storehash{'section'} = $sec;
1.1172.2.146.  .16(raeb 5192:-23):             my ($curruserdomstr,$newuserdomstr);
                   5193:-23):             if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'})) {
                   5194:-23):                 $curruserdomstr = $env{'course.'.$env{'request.course.id'}.'.internal.userdomains'};
                   5195:-23):             } else {
                   5196:-23):                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
                   5197:-23):                 $curruserdomstr = $courseinfo{'internal.userdomains'};
                   5198:-23):             }
                   5199:-23):             if ($curruserdomstr ne '') {
                   5200:-23):                 my @udoms = split(/,/,$curruserdomstr);
                   5201:-23):                 unless (grep(/^\Q$domain\E/,@udoms)) {
                   5202:-23):                     push(@udoms,$domain);
                   5203:-23):                     $newuserdomstr = join(',',sort(@udoms));
                   5204:-23):                 }
                   5205:-23):             } else {
                   5206:-23):                 $newuserdomstr = $domain;
                   5207:-23):             }
                   5208:-23):             if ($newuserdomstr ne '') {
                   5209:-23):                 my $putresult = &put('environment',{ 'internal.userdomains' => $newuserdomstr },
                   5210:-23):                                      $cdom,$cnum);
                   5211:-23):                 if ($putresult eq 'ok') {
                   5212:-23):                     unless (($selfenroll) || ($context eq 'selfenroll')) {
                   5213:-23):                         if (($context eq 'createcourse') || ($context eq 'requestcourses') ||
                   5214:-23):                             ($context eq 'automated') || ($context eq 'domain')) {
                   5215:-23):                             $env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'} = $newuserdomstr;
                   5216:-23):                         } elsif ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   5217:-23):                             &appenv({'course.'.$cdom.'_'.$cnum.'.internal.userdomains' => $newuserdomstr});
                   5218:-23):                         }
                   5219:-23):                     }
                   5220:-23):                 }
                   5221:-23):             }
1.1172.2.9  raeburn  5222:         }
                   5223:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   5224:                    $domain,$cnum,$cdom);
                   5225:         if (($trole ne 'st') || ($sec ne '')) {
                   5226:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  5227:         }
                   5228:     }
                   5229:     return;
                   5230: }
                   5231: 
1.1172.2.9  raeburn  5232: sub domainrolelog {
                   5233:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5234:     if ($area =~ m{^/($match_domain)/$}) {
                   5235:         my $cdom = $1;
                   5236:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   5237:         my $namespace = 'rolelog';
                   5238:         my %storehash = (
                   5239:                            role    => $trole,
                   5240:                            start   => $tstart,
                   5241:                            end     => $tend,
                   5242:                            context => $context,
                   5243:                         );
                   5244:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5245:                    $domain,$domconfiguser,$cdom);
                   5246:     }
                   5247:     return;
                   5248: 
                   5249: }
                   5250: 
                   5251: sub coauthorrolelog {
                   5252:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5253:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5254:         my $audom = $1;
                   5255:         my $auname = $2;
                   5256:         my $namespace = 'rolelog';
                   5257:         my %storehash = (
                   5258:                            role    => $trole,
                   5259:                            start   => $tstart,
                   5260:                            end     => $tend,
                   5261:                            context => $context,
                   5262:                         );
                   5263:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5264:                    $domain,$auname,$audom);
                   5265:     }
                   5266:     return;
                   5267: }
                   5268: 
1.351     www      5269: sub get_course_adv_roles {
1.948     raeburn  5270:     my ($cid,$codes) = @_;
1.620     albertel 5271:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5272:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5273:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5274:     my %nothide=();
1.800     albertel 5275:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5276:         if ($user !~ /:/) {
                   5277: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5278:         } else {
                   5279:             $nothide{$user}=1;
                   5280:         }
1.470     www      5281:     }
1.1172.2.23  raeburn  5282:     my @possdoms = ($coursehash{'domain'});
                   5283:     if ($coursehash{'checkforpriv'}) {
                   5284:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5285:     }
1.351     www      5286:     my %returnhash=();
                   5287:     my %dumphash=
                   5288:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5289:     my $now=time;
1.997     raeburn  5290:     my %privileged;
1.1000    raeburn  5291:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5292: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5293:         if (($tstart) && ($tstart<0)) { next; }
                   5294:         if (($tend) && ($tend<$now)) { next; }
                   5295:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5296:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5297: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  5298:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5299:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5300: 	if ($role eq 'cr') { next; }
1.948     raeburn  5301:         if ($codes) {
                   5302:             if ($section) { $role .= ':'.$section; }
                   5303:             if ($returnhash{$role}) {
                   5304:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5305:             } else {
                   5306:                 $returnhash{$role}=$username.':'.$domain;
                   5307:             }
1.351     www      5308:         } else {
1.988     raeburn  5309:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5310:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5311:             if ($returnhash{$key}) {
                   5312: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5313:             } else {
                   5314:                 $returnhash{$key}=$username.':'.$domain;
                   5315:             }
1.351     www      5316:         }
1.948     raeburn  5317:     }
1.400     www      5318:     return %returnhash;
                   5319: }
                   5320: 
                   5321: sub get_my_roles {
1.937     raeburn  5322:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5323:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5324:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5325:     my (%dumphash,%nothide);
1.1086    raeburn  5326:     if ($context eq 'userroles') {
1.1166    raeburn  5327:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5328:     } else {
1.1172.2.23  raeburn  5329:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5330:         if ($hidepriv) {
                   5331:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5332:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5333:                 if ($user !~ /:/) {
                   5334:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5335:                 } else {
                   5336:                     $nothide{$user} = 1;
                   5337:                 }
                   5338:             }
                   5339:         }
1.858     raeburn  5340:     }
1.400     www      5341:     my %returnhash=();
                   5342:     my $now=time;
1.999     raeburn  5343:     my %privileged;
1.800     albertel 5344:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5345:         my ($role,$tend,$tstart);
                   5346:         if ($context eq 'userroles') {
1.1149    raeburn  5347:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5348: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5349:         } else {
                   5350:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5351:         }
1.400     www      5352:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5353:         my $status = 'active';
1.939     raeburn  5354:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5355:             $status = 'previous';
                   5356:         } 
                   5357:         if (($tstart) && ($now<$tstart)) {
                   5358:             $status = 'future';
                   5359:         }
                   5360:         if (ref($types) eq 'ARRAY') {
                   5361:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5362:                 next;
                   5363:             } 
                   5364:         } else {
                   5365:             if ($status ne 'active') {
                   5366:                 next;
                   5367:             }
                   5368:         }
1.867     raeburn  5369:         my ($rolecode,$username,$domain,$section,$area);
                   5370:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  5371:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5372:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5373:         } else {
                   5374:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5375:         }
1.832     raeburn  5376:         if (ref($roledoms) eq 'ARRAY') {
                   5377:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5378:                 next;
                   5379:             }
                   5380:         }
                   5381:         if (ref($roles) eq 'ARRAY') {
                   5382:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5383:                 if ($role =~ /^cr\//) {
                   5384:                     if (!grep(/^cr$/,@{$roles})) {
                   5385:                         next;
                   5386:                     }
1.1104    raeburn  5387:                 } elsif ($role =~ /^gr\//) {
                   5388:                     if (!grep(/^gr$/,@{$roles})) {
                   5389:                         next;
                   5390:                     }
1.922     raeburn  5391:                 } else {
                   5392:                     next;
                   5393:                 }
1.832     raeburn  5394:             }
1.867     raeburn  5395:         }
1.937     raeburn  5396:         if ($hidepriv) {
1.1172.2.23  raeburn  5397:             my @privroles = ('dc','su');
1.999     raeburn  5398:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  5399:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5400:             } else {
1.1172.2.23  raeburn  5401:                 my $possdoms = [$domain];
                   5402:                 if (ref($roledoms) eq 'ARRAY') {
                   5403:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5404:                 }
1.1172.2.23  raeburn  5405:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5406:                     if (!$nothide{$username.':'.$domain}) {
                   5407:                         next;
                   5408:                     }
                   5409:                 }
1.937     raeburn  5410:             }
                   5411:         }
1.933     raeburn  5412:         if ($withsec) {
                   5413:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5414:                 $tstart.':'.$tend;
                   5415:         } else {
                   5416:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5417:         }
1.832     raeburn  5418:     }
1.373     www      5419:     return %returnhash;
1.399     www      5420: }
                   5421: 
1.1172.2.89  raeburn  5422: sub get_all_adhocroles {
                   5423:     my ($dom) = @_;
                   5424:     my @roles_by_num = ();
                   5425:     my %domdefaults = &get_domain_defaults($dom);
                   5426:     my (%description,%access_in_dom,%access_info);
                   5427:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5428:         my $count = 0;
                   5429:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5430:         my %ordered;
                   5431:         foreach my $role (sort(keys(%domcurrent))) {
                   5432:             my ($order,$desc,$access_in_dom);
                   5433:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5434:                 $order = $domcurrent{$role}{'order'};
                   5435:                 $desc = $domcurrent{$role}{'desc'};
                   5436:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5437:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5438:             }
                   5439:             if ($order eq '') {
                   5440:                 $order = $count;
                   5441:             }
                   5442:             $ordered{$order} = $role;
                   5443:             if ($desc ne '') {
                   5444:                 $description{$role} = $desc;
                   5445:             } else {
                   5446:                 $description{$role}= $role;
                   5447:             }
                   5448:             $count++;
                   5449:         }
                   5450:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5451:             push(@roles_by_num,$ordered{$item});
                   5452:         }
                   5453:     }
                   5454:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5455: }
                   5456: 
                   5457: sub get_my_adhocroles {
                   5458:     my ($cid,$checkreg) = @_;
                   5459:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5460:     if ($env{'request.course.id'} eq $cid) {
                   5461:         $cdom = $env{'course.'.$cid.'.domain'};
                   5462:         $cnum = $env{'course.'.$cid.'.num'};
                   5463:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5464:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5465:         $cdom = $1;
                   5466:         $cnum = $2;
                   5467:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5468:                                      $cdom,$cnum);
                   5469:     }
                   5470:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5471:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5472:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5473:         if ($rosterhash{$user} ne '') {
                   5474:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5475:             return ([],{}) if ($type eq 'auto');
                   5476:         }
                   5477:     }
                   5478:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5479:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5480:             my $then=$env{'user.login.time'};
                   5481:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5482:             if (!$update) {
                   5483:                 $update = $then;
                   5484:             }
                   5485:             my @liveroles;
                   5486:             foreach my $role ('dh','da') {
                   5487:                 if ($env{"user.role.$role./$cdom/"}) {
                   5488:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5489:                     my $limit = $update;
                   5490:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5491:                         $limit = $then;
                   5492:                     }
                   5493:                     my $activerole = 1;
                   5494:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5495:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5496:                     if ($activerole) {
                   5497:                         push(@liveroles,$role);
                   5498:                     }
                   5499:                 }
                   5500:             }
                   5501:             if (@liveroles) {
1.1172.2.89  raeburn  5502:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5503:                     my ($accessref,$accessinfo,%access_in_dom);
                   5504:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5505:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5506:                         if (@{$roles_by_num}) {
                   5507:                             my %settings;
                   5508:                             if ($env{'request.course.id'} eq $cid) {
                   5509:                                 foreach my $envkey (keys(%env)) {
                   5510:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5511:                                         $settings{$1} = $env{$envkey};
                   5512:                                     }
                   5513:                                 }
                   5514:                             } else {
                   5515:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5516:                             }
                   5517:                             my %setincrs;
                   5518:                             if ($settings{'internal.adhocaccess'}) {
                   5519:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5520:                             }
                   5521:                             my @statuses;
                   5522:                             if ($env{'environment.inststatus'}) {
                   5523:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5524:                             }
                   5525:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5526:                             if (ref($accessref) eq 'HASH') {
                   5527:                                 %access_in_dom = %{$accessref};
                   5528:                             }
                   5529:                             foreach my $role (@{$roles_by_num}) {
                   5530:                                 my ($curraccess,@okstatus,@personnel);
                   5531:                                 if ($setincrs{$role}) {
                   5532:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5533:                                     if ($curraccess eq 'status') {
                   5534:                                         @okstatus = split(/\&/,$rest);
                   5535:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5536:                                         @personnel = split(/\&/,$rest);
                   5537:                                     }
                   5538:                                 } else {
                   5539:                                     $curraccess = $access_in_dom{$role};
                   5540:                                     if (ref($accessinfo) eq 'HASH') {
                   5541:                                         if ($curraccess eq 'status') {
                   5542:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5543:                                                 @okstatus = @{$accessinfo->{$role}};
                   5544:                                             }
                   5545:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5546:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5547:                                                 @personnel = @{$accessinfo->{$role}};
                   5548:                                             }
                   5549:                                         }
                   5550:                                     }
                   5551:                                 }
                   5552:                                 if ($curraccess eq 'none') {
                   5553:                                     next;
                   5554:                                 } elsif ($curraccess eq 'all') {
                   5555:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5556:                                 } elsif ($curraccess eq 'dh') {
                   5557:                                     if (grep(/^dh$/,@liveroles)) {
                   5558:                                         push(@possroles,$role);
                   5559:                                     } else {
                   5560:                                         next;
                   5561:                                     }
                   5562:                                 } elsif ($curraccess eq 'da') {
                   5563:                                     if (grep(/^da$/,@liveroles)) {
                   5564:                                         push(@possroles,$role);
                   5565:                                     } else {
                   5566:                                         next;
                   5567:                                     }
1.1172.2.89  raeburn  5568:                                 } elsif ($curraccess eq 'status') {
                   5569:                                     if (@okstatus) {
                   5570:                                         if (!@statuses) {
                   5571:                                             if (grep(/^default$/,@okstatus)) {
                   5572:                                                 push(@possroles,$role);
                   5573:                                             }
                   5574:                                         } else {
                   5575:                                             foreach my $status (@okstatus) {
                   5576:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5577:                                                     push(@possroles,$role);
                   5578:                                                     last;
                   5579:                                                 }
                   5580:                                             }
                   5581:                                         }
                   5582:                                     }
                   5583:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5584:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5585:                                         if ($curraccess eq 'exc') {
                   5586:                                             push(@possroles,$role);
                   5587:                                         }
                   5588:                                     } elsif ($curraccess eq 'inc') {
                   5589:                                         push(@possroles,$role);
                   5590:                                     }
                   5591:                                 }
                   5592:                             }
                   5593:                         }
                   5594:                     }
                   5595:                 }
                   5596:             }
                   5597:         }
                   5598:     }
                   5599:     unless (ref($description) eq 'HASH') {
                   5600:         if (ref($roles_by_num) eq 'ARRAY') {
                   5601:             my %desc;
                   5602:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5603:             $description = \%desc;
                   5604:         } else {
                   5605:             $description = {};
                   5606:         }
                   5607:     }
                   5608:     return (\@possroles,$description);
                   5609: }
                   5610: 
1.399     www      5611: # ----------------------------------------------------- Frontpage Announcements
                   5612: #
                   5613: #
                   5614: 
                   5615: sub postannounce {
                   5616:     my ($server,$text)=@_;
1.844     albertel 5617:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5618:     unless ($text=~/\w/) { $text=''; }
                   5619:     return &reply('setannounce:'.&escape($text),$server);
                   5620: }
                   5621: 
                   5622: sub getannounce {
1.448     albertel 5623: 
1.1172.2.96  raeburn  5624:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5625: 	my $announcement='';
1.800     albertel 5626: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5627: 	close($fh);
1.399     www      5628: 	if ($announcement=~/\w/) { 
                   5629: 	    return 
                   5630:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5631:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5632: 	} else {
                   5633: 	    return '';
                   5634: 	}
                   5635:     } else {
                   5636: 	return '';
                   5637:     }
1.351     www      5638: }
1.353     www      5639: 
                   5640: # ---------------------------------------------------------- Course ID routines
                   5641: # Deal with domain's nohist_courseid.db files
                   5642: #
                   5643: 
                   5644: sub courseidput {
1.921     raeburn  5645:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5646:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5647:     my $outcome;
                   5648:     if ($caller eq 'timeonly') {
                   5649:         my $cids = '';
                   5650:         foreach my $item (keys(%$storehash)) {
                   5651:             $cids.=&escape($item).'&';
                   5652:         }
                   5653:         $cids=~s/\&$//;
                   5654:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5655:                           $coursehome);       
                   5656:     } else {
                   5657:         my $items = '';
                   5658:         foreach my $item (keys(%$storehash)) {
                   5659:             $items.= &escape($item).'='.
                   5660:                      &freeze_escape($$storehash{$item}).'&';
                   5661:         }
                   5662:         $items=~s/\&$//;
                   5663:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5664:                           $coursehome);
1.918     raeburn  5665:     }
                   5666:     if ($outcome eq 'unknown_cmd') {
                   5667:         my $what;
                   5668:         foreach my $cid (keys(%$storehash)) {
                   5669:             $what .= &escape($cid).'=';
1.921     raeburn  5670:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5671:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5672:             }
                   5673:             $what =~ s/\:$/&/;
                   5674:         }
                   5675:         $what =~ s/\&$//;  
                   5676:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5677:     } else {
                   5678:         return $outcome;
                   5679:     }
1.353     www      5680: }
                   5681: 
                   5682: sub courseiddump {
1.921     raeburn  5683:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5684:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5685:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5686:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5687:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5688:     my $as_hash = 1;
                   5689:     my %returnhash;
                   5690:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5691:     my %libserv = &all_library();
                   5692:     foreach my $tryserver (keys(%libserv)) {
                   5693:         if ( (  $hostidflag == 1 
                   5694: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5695: 	     || (!defined($hostidflag)) ) {
                   5696: 
1.918     raeburn  5697: 	    if (($domfilter eq '') ||
                   5698: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5699:                 my $rep;
                   5700:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5701:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5702:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5703:                                 &escape($descfilter), &escape($instcodefilter),
                   5704:                                 &escape($ownerfilter), &escape($coursefilter),
                   5705:                                 &escape($typefilter), &escape($regexp_ok),
                   5706:                                 $as_hash, &escape($selfenrollonly),
                   5707:                                 &escape($catfilter), $showhidden, $caller,
                   5708:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5709:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5710:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5711:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5712:                 } else {
                   5713:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5714:                              $sincefilter.':'.&escape($descfilter).':'.
                   5715:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5716:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5717:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5718:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5719:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5720:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5721:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5722:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5723:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5724:                 }
                   5725: 
1.918     raeburn  5726:                 my @pairs=split(/\&/,$rep);
                   5727:                 foreach my $item (@pairs) {
                   5728:                     my ($key,$value)=split(/\=/,$item,2);
                   5729:                     $key = &unescape($key);
                   5730:                     next if ($key =~ /^error: 2 /);
                   5731:                     my $result = &thaw_unescape($value);
                   5732:                     if (ref($result) eq 'HASH') {
                   5733:                         $returnhash{$key}=$result;
                   5734:                     } else {
1.921     raeburn  5735:                         my @responses = split(/:/,$value);
                   5736:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5737:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5738:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5739:                         }
1.1008    raeburn  5740:                     }
1.353     www      5741:                 }
                   5742:             }
                   5743:         }
                   5744:     }
                   5745:     return %returnhash;
                   5746: }
                   5747: 
1.1055    raeburn  5748: sub courselastaccess {
                   5749:     my ($cdom,$cnum,$hostidref) = @_;
                   5750:     my %returnhash;
                   5751:     if ($cdom && $cnum) {
                   5752:         my $chome = &homeserver($cnum,$cdom);
                   5753:         if ($chome ne 'no_host') {
                   5754:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5755:             &extract_lastaccess(\%returnhash,$rep);
                   5756:         }
                   5757:     } else {
                   5758:         if (!$cdom) { $cdom=''; }
                   5759:         my %libserv = &all_library();
                   5760:         foreach my $tryserver (keys(%libserv)) {
                   5761:             if (ref($hostidref) eq 'ARRAY') {
                   5762:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5763:             } 
                   5764:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5765:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5766:                 &extract_lastaccess(\%returnhash,$rep);
                   5767:             }
                   5768:         }
                   5769:     }
                   5770:     return %returnhash;
                   5771: }
                   5772: 
                   5773: sub extract_lastaccess {
                   5774:     my ($returnhash,$rep) = @_;
                   5775:     if (ref($returnhash) eq 'HASH') {
                   5776:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5777:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5778:                  $rep eq '') {
                   5779:             my @pairs=split(/\&/,$rep);
                   5780:             foreach my $item (@pairs) {
                   5781:                 my ($key,$value)=split(/\=/,$item,2);
                   5782:                 $key = &unescape($key);
                   5783:                 next if ($key =~ /^error: 2 /);
                   5784:                 $returnhash->{$key} = &thaw_unescape($value);
                   5785:             }
                   5786:         }
                   5787:     }
                   5788:     return;
                   5789: }
                   5790: 
1.658     raeburn  5791: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5792: 
                   5793: sub dcmailput {
1.685     raeburn  5794:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5795:     my $status = &Apache::lonnet::critical(
1.740     www      5796:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5797:        &escape($message),$server);
1.662     raeburn  5798:     return $status;
                   5799: }
                   5800: 
1.658     raeburn  5801: sub dcmaildump {
                   5802:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5803:     my %returnhash=();
1.846     albertel 5804: 
                   5805:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5806:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5807:                                                          &escape($enddate).':';
                   5808: 	my @esc_senders=map { &escape($_)} @$senders;
                   5809: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5810: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5811:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5812:             if (($key) && ($value)) {
                   5813:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5814:             }
                   5815:         }
                   5816:     }
                   5817:     return %returnhash;
                   5818: }
1.662     raeburn  5819: # ---------------------------------------------------------- Domain roles
                   5820: 
                   5821: sub get_domain_roles {
                   5822:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5823:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5824:         $startdate = '.';
                   5825:     }
1.1018    raeburn  5826:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5827:         $enddate = '.';
                   5828:     }
1.922     raeburn  5829:     my $rolelist;
                   5830:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5831:         $rolelist = join('&',@{$roles});
1.922     raeburn  5832:     }
1.662     raeburn  5833:     my %personnel = ();
1.841     albertel 5834: 
                   5835:     my %servers = &get_servers($dom,'library');
                   5836:     foreach my $tryserver (keys(%servers)) {
                   5837: 	%{$personnel{$tryserver}}=();
                   5838: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5839: 					    &escape($startdate).':'.
                   5840: 					    &escape($enddate).':'.
                   5841: 					    &escape($rolelist), $tryserver))) {
                   5842: 	    my ($key,$value) = split(/\=/,$line,2);
                   5843: 	    if (($key) && ($value)) {
                   5844: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5845: 	    }
                   5846: 	}
1.662     raeburn  5847:     }
                   5848:     return %personnel;
                   5849: }
1.658     raeburn  5850: 
1.1172.2.89  raeburn  5851: sub get_active_domroles {
                   5852:     my ($dom,$roles) = @_;
                   5853:     return () unless (ref($roles) eq 'ARRAY');
                   5854:     my $now = time;
                   5855:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5856:     my %domroles;
                   5857:     foreach my $server (keys(%dompersonnel)) {
                   5858:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5859:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5860:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5861:         }
                   5862:     }
                   5863:     return %domroles;
                   5864: }
                   5865: 
1.1057    www      5866: # ----------------------------------------------------------- Interval timing 
1.149     www      5867: 
1.1153    www      5868: {
                   5869: # Caches needed for speedup of navmaps
                   5870: # We don't want to cache this for very long at all (5 seconds at most)
                   5871: # 
                   5872: # The user for whom we cache
                   5873: my $cachedkey='';
                   5874: # The cached times for this user
                   5875: my %cachedtimes=();
                   5876: # When this was last done
1.1172.2.66  raeburn  5877: my $cachedtime='';
1.1153    www      5878: 
                   5879: sub load_all_first_access {
1.1172.2.146.  .1(raebu 5880:22):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5881:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.146.  .1(raebu 5882:22):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5883:22):         (!$ignorecache)) {
1.1154    raeburn  5884:         return;
                   5885:     }
                   5886:     $cachedtime=time;
                   5887:     $cachedkey=$uname.':'.$udom;
                   5888:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5889: }
                   5890: 
1.504     albertel 5891: sub get_first_access {
1.1172.2.146.  .1(raebu 5892:22):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5893:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5894:     if ($argsymb) { $symb=$argsymb; }
                   5895:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5896:     if ($argmap) { $map = $argmap; }
1.926     albertel 5897:     if ($type eq 'course') {
                   5898: 	$res='course';
                   5899:     } elsif ($type eq 'map') {
1.588     albertel 5900: 	$res=&symbread($map);
                   5901:     } else {
                   5902: 	$res=$symb;
                   5903:     }
1.1172.2.146.  .1(raebu 5904:22):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5905:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5906: }
                   5907: 
                   5908: sub set_first_access {
1.1162    raeburn  5909:     my ($type,$interval)=@_;
1.790     albertel 5910:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5911:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5912:     if ($type eq 'course') {
                   5913: 	$res='course';
                   5914:     } elsif ($type eq 'map') {
1.588     albertel 5915: 	$res=&symbread($map);
                   5916:     } else {
                   5917: 	$res=$symb;
                   5918:     }
1.1153    www      5919:     $cachedkey='';
1.1162    raeburn  5920:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5921:     if ($firstaccess) {
                   5922:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5923:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5924:                  "in $courseid");
                   5925:         return 'already_set';
                   5926:     } else {
1.1162    raeburn  5927:         my $start = time;
                   5928: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5929:                           $udom,$uname);
                   5930:         if ($putres eq 'ok') {
                   5931:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5932:                  $udom,$uname); 
                   5933:             &appenv(
                   5934:                      {
                   5935:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5936:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5937:                      }
                   5938:                   );
1.1172.2.97  raeburn  5939:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5940:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5941:             }
1.1172.2.102  raeburn  5942:         } elsif ($putres ne 'refused') {
                   5943:             &logthis("Result: $putres when attempting to set first access time ".
                   5944:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5945:         }
                   5946:         return $putres;
1.505     albertel 5947:     }
                   5948:     return 'already_set';
1.504     albertel 5949: }
1.1153    www      5950: }
1.1172.2.32  raeburn  5951: 
                   5952: sub checkout {
                   5953:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5954:     my $now=time;
                   5955:     my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134  raeburn  5956:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5957:     my $infostr=&escape(
                   5958:                  'CHECKOUTTOKEN&'.
                   5959:                  $tuname.'&'.
                   5960:                  $tudom.'&'.
                   5961:                  $tcrsid.'&'.
                   5962:                  $symb.'&'.
1.1172.2.134  raeburn  5963:                  $now.'&'.$ip);
1.1172.2.32  raeburn  5964:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5965:     if ($token=~/^error\:/) {
                   5966:         &logthis("<font color=\"blue\">WARNING: ".
                   5967:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5968:                  "</font>");
                   5969:         return '';
                   5970:     }
                   5971: 
                   5972:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5973:     $token=~tr/a-z/A-Z/;
                   5974: 
                   5975:     my %infohash=('resource.0.outtoken' => $token,
                   5976:                   'resource.0.checkouttime' => $now,
1.1172.2.134  raeburn  5977:                   'resource.0.outremote' => $ip);
1.1172.2.32  raeburn  5978: 
                   5979:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5980:        return '';
                   5981:     } else {
                   5982:         &logthis("<font color=\"blue\">WARNING: ".
                   5983:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5984:                  "</font>");
                   5985:     }
                   5986: 
                   5987:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5988:                          &escape('Checkout '.$infostr.' - '.
                   5989:                                                  $token)) ne 'ok') {
                   5990:         return '';
                   5991:     } else {
                   5992:         &logthis("<font color=\"blue\">WARNING: ".
                   5993:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5994:                  "</font>");
                   5995:     }
                   5996:     return $token;
                   5997: }
                   5998: 
                   5999: # ------------------------------------------------------------ Check in an item
                   6000: 
                   6001: sub checkin {
                   6002:     my $token=shift;
                   6003:     my $now=time;
                   6004:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   6005:     $lonhost=~tr/A-Z/a-z/;
                   6006:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   6007:     $dtoken=~s/\W/\_/g;
1.1172.2.134  raeburn  6008:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  6009:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   6010:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   6011: 
                   6012:     unless (($tuname) && ($tudom)) {
                   6013:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   6014:         return '';
                   6015:     }
                   6016: 
                   6017:     unless (&allowed('mgr',$tcrsid)) {
                   6018:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   6019:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   6020:         return '';
                   6021:     }
                   6022: 
                   6023:     my %infohash=('resource.0.intoken' => $token,
                   6024:                   'resource.0.checkintime' => $now,
1.1172.2.134  raeburn  6025:                   'resource.0.inremote' => $ip);
1.1172.2.32  raeburn  6026: 
                   6027:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   6028:        return '';
                   6029:     }
                   6030: 
                   6031:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   6032:                          &escape('Checkin - '.$token)) ne 'ok') {
                   6033:         return '';
                   6034:     }
                   6035: 
                   6036:     return ($symb,$tuname,$tudom,$tcrsid);
                   6037: }
                   6038: 
1.110     www      6039: # --------------------------------------------- Set Expire Date for Spreadsheet
                   6040: 
                   6041: sub expirespread {
                   6042:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 6043:     my $cid=$env{'request.course.id'}; 
1.110     www      6044:     if ($cid) {
                   6045:        my $now=time;
                   6046:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 6047:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   6048:                             $env{'course.'.$cid.'.num'}.
1.110     www      6049: 	        	    ':nohist_expirationdates:'.
                   6050:                             &escape($key).'='.$now,
1.620     albertel 6051:                             $env{'course.'.$cid.'.home'})
1.110     www      6052:     }
                   6053:     return 'ok';
1.14      www      6054: }
                   6055: 
1.109     www      6056: # ----------------------------------------------------- Devalidate Spreadsheets
                   6057: 
                   6058: sub devalidate {
1.325     www      6059:     my ($symb,$uname,$udom)=@_;
1.620     albertel 6060:     my $cid=$env{'request.course.id'}; 
1.109     www      6061:     if ($cid) {
1.391     matthew  6062:         # delete the stored spreadsheets for
                   6063:         # - the student level sheet of this user in course's homespace
                   6064:         # - the assessment level sheet for this resource 
                   6065:         #   for this user in user's homespace
1.553     albertel 6066: 	# - current conditional state info
1.325     www      6067: 	my $key=$uname.':'.$udom.':';
1.109     www      6068:         my $status=
1.299     matthew  6069: 	    &del('nohist_calculatedsheets',
1.391     matthew  6070: 		 [$key.'studentcalc:'],
1.620     albertel 6071: 		 $env{'course.'.$cid.'.domain'},
                   6072: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 6073: 		.' '.
                   6074: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  6075: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      6076:         unless ($status eq 'ok ok') {
                   6077:            &logthis('Could not devalidate spreadsheet '.
1.325     www      6078:                     $uname.' at '.$udom.' for '.
1.109     www      6079: 		    $symb.': '.$status);
1.133     albertel 6080:         }
1.553     albertel 6081: 	&delenv('user.state.'.$cid);
1.109     www      6082:     }
                   6083: }
                   6084: 
1.265     albertel 6085: sub get_scalar {
                   6086:     my ($string,$end) = @_;
                   6087:     my $value;
                   6088:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   6089: 	$value = $1;
                   6090:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   6091: 	$value = $1;
                   6092:     }
                   6093:     return &unescape($value);
                   6094: }
                   6095: 
                   6096: sub array2str {
                   6097:   my (@array) = @_;
                   6098:   my $result=&arrayref2str(\@array);
                   6099:   $result=~s/^__ARRAY_REF__//;
                   6100:   $result=~s/__END_ARRAY_REF__$//;
                   6101:   return $result;
                   6102: }
                   6103: 
1.204     albertel 6104: sub arrayref2str {
                   6105:   my ($arrayref) = @_;
1.265     albertel 6106:   my $result='__ARRAY_REF__';
1.204     albertel 6107:   foreach my $elem (@$arrayref) {
1.265     albertel 6108:     if(ref($elem) eq 'ARRAY') {
                   6109:       $result.=&arrayref2str($elem).'&';
                   6110:     } elsif(ref($elem) eq 'HASH') {
                   6111:       $result.=&hashref2str($elem).'&';
                   6112:     } elsif(ref($elem)) {
                   6113:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 6114:     } else {
                   6115:       $result.=&escape($elem).'&';
                   6116:     }
                   6117:   }
                   6118:   $result=~s/\&$//;
1.265     albertel 6119:   $result .= '__END_ARRAY_REF__';
1.204     albertel 6120:   return $result;
                   6121: }
                   6122: 
1.168     albertel 6123: sub hash2str {
1.204     albertel 6124:   my (%hash) = @_;
                   6125:   my $result=&hashref2str(\%hash);
1.265     albertel 6126:   $result=~s/^__HASH_REF__//;
                   6127:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 6128:   return $result;
                   6129: }
                   6130: 
                   6131: sub hashref2str {
                   6132:   my ($hashref)=@_;
1.265     albertel 6133:   my $result='__HASH_REF__';
1.800     albertel 6134:   foreach my $key (sort(keys(%$hashref))) {
                   6135:     if (ref($key) eq 'ARRAY') {
                   6136:       $result.=&arrayref2str($key).'=';
                   6137:     } elsif (ref($key) eq 'HASH') {
                   6138:       $result.=&hashref2str($key).'=';
                   6139:     } elsif (ref($key)) {
1.265     albertel 6140:       $result.='=';
1.800     albertel 6141:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 6142:     } else {
1.1132    raeburn  6143: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 6144:     }
                   6145: 
1.800     albertel 6146:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   6147:       $result.=&arrayref2str($hashref->{$key}).'&';
                   6148:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   6149:       $result.=&hashref2str($hashref->{$key}).'&';
                   6150:     } elsif(ref($hashref->{$key})) {
1.265     albertel 6151:        $result.='&';
1.800     albertel 6152:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 6153:     } else {
1.800     albertel 6154:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 6155:     }
                   6156:   }
1.168     albertel 6157:   $result=~s/\&$//;
1.265     albertel 6158:   $result .= '__END_HASH_REF__';
1.168     albertel 6159:   return $result;
                   6160: }
                   6161: 
                   6162: sub str2hash {
1.265     albertel 6163:     my ($string)=@_;
                   6164:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   6165:     return %$hash;
                   6166: }
                   6167: 
                   6168: sub str2hashref {
1.168     albertel 6169:   my ($string) = @_;
1.265     albertel 6170: 
                   6171:   my %hash;
                   6172: 
                   6173:   if($string !~ /^__HASH_REF__/) {
                   6174:       if (! ($string eq '' || !defined($string))) {
                   6175: 	  $hash{'error'}='Not hash reference';
                   6176:       }
                   6177:       return (\%hash, $string);
                   6178:   }
                   6179: 
                   6180:   $string =~ s/^__HASH_REF__//;
                   6181: 
                   6182:   while($string !~ /^__END_HASH_REF__/) {
                   6183:       #key
                   6184:       my $key='';
                   6185:       if($string =~ /^__HASH_REF__/) {
                   6186:           ($key, $string)=&str2hashref($string);
                   6187:           if(defined($key->{'error'})) {
                   6188:               $hash{'error'}='Bad data';
                   6189:               return (\%hash, $string);
                   6190:           }
                   6191:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6192:           ($key, $string)=&str2arrayref($string);
                   6193:           if($key->[0] eq 'Array reference error') {
                   6194:               $hash{'error'}='Bad data';
                   6195:               return (\%hash, $string);
                   6196:           }
                   6197:       } else {
                   6198:           $string =~ s/^(.*?)=//;
1.267     albertel 6199: 	  $key=&unescape($1);
1.265     albertel 6200:       }
                   6201:       $string =~ s/^=//;
                   6202: 
                   6203:       #value
                   6204:       my $value='';
                   6205:       if($string =~ /^__HASH_REF__/) {
                   6206:           ($value, $string)=&str2hashref($string);
                   6207:           if(defined($value->{'error'})) {
                   6208:               $hash{'error'}='Bad data';
                   6209:               return (\%hash, $string);
                   6210:           }
                   6211:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6212:           ($value, $string)=&str2arrayref($string);
                   6213:           if($value->[0] eq 'Array reference error') {
                   6214:               $hash{'error'}='Bad data';
                   6215:               return (\%hash, $string);
                   6216:           }
                   6217:       } else {
                   6218: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   6219:       }
                   6220:       $string =~ s/^&//;
                   6221: 
                   6222:       $hash{$key}=$value;
1.204     albertel 6223:   }
1.265     albertel 6224: 
                   6225:   $string =~ s/^__END_HASH_REF__//;
                   6226: 
                   6227:   return (\%hash, $string);
1.204     albertel 6228: }
                   6229: 
                   6230: sub str2array {
1.265     albertel 6231:     my ($string)=@_;
                   6232:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   6233:     return @$array;
                   6234: }
                   6235: 
                   6236: sub str2arrayref {
1.204     albertel 6237:   my ($string) = @_;
1.265     albertel 6238:   my @array;
                   6239: 
                   6240:   if($string !~ /^__ARRAY_REF__/) {
                   6241:       if (! ($string eq '' || !defined($string))) {
                   6242: 	  $array[0]='Array reference error';
                   6243:       }
                   6244:       return (\@array, $string);
                   6245:   }
                   6246: 
                   6247:   $string =~ s/^__ARRAY_REF__//;
                   6248: 
                   6249:   while($string !~ /^__END_ARRAY_REF__/) {
                   6250:       my $value='';
                   6251:       if($string =~ /^__HASH_REF__/) {
                   6252:           ($value, $string)=&str2hashref($string);
                   6253:           if(defined($value->{'error'})) {
                   6254:               $array[0] ='Array reference error';
                   6255:               return (\@array, $string);
                   6256:           }
                   6257:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6258:           ($value, $string)=&str2arrayref($string);
                   6259:           if($value->[0] eq 'Array reference error') {
                   6260:               $array[0] ='Array reference error';
                   6261:               return (\@array, $string);
                   6262:           }
                   6263:       } else {
                   6264: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   6265:       }
                   6266:       $string =~ s/^&//;
                   6267: 
                   6268:       push(@array, $value);
1.191     harris41 6269:   }
1.265     albertel 6270: 
                   6271:   $string =~ s/^__END_ARRAY_REF__//;
                   6272: 
                   6273:   return (\@array, $string);
1.168     albertel 6274: }
                   6275: 
1.167     albertel 6276: # -------------------------------------------------------------------Temp Store
                   6277: 
1.168     albertel 6278: sub tmpreset {
                   6279:   my ($symb,$namespace,$domain,$stuname) = @_;
                   6280:   if (!$symb) {
                   6281:     $symb=&symbread();
1.620     albertel 6282:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6283:   }
                   6284:   $symb=escape($symb);
                   6285: 
1.620     albertel 6286:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 6287:   $namespace=~s/\//\_/g;
                   6288:   $namespace=~s/\W//g;
                   6289: 
1.620     albertel 6290:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6291:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6292:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6293:       $stuname=&get_requestor_ip();
1.591     albertel 6294:   }
1.1117    foxr     6295:   my $path=LONCAPA::tempdir();
1.168     albertel 6296:   my %hash;
                   6297:   if (tie(%hash,'GDBM_File',
                   6298: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6299: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6300:     foreach my $key (keys(%hash)) {
1.180     albertel 6301:       if ($key=~ /:$symb/) {
1.168     albertel 6302: 	delete($hash{$key});
                   6303:       }
                   6304:     }
                   6305:   }
                   6306: }
                   6307: 
1.167     albertel 6308: sub tmpstore {
1.168     albertel 6309:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6310: 
                   6311:   if (!$symb) {
                   6312:     $symb=&symbread();
1.620     albertel 6313:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6314:   }
                   6315:   $symb=escape($symb);
                   6316: 
                   6317:   if (!$namespace) {
                   6318:     # I don't think we would ever want to store this for a course.
                   6319:     # it seems this will only be used if we don't have a course.
1.620     albertel 6320:     #$namespace=$env{'request.course.id'};
1.168     albertel 6321:     #if (!$namespace) {
1.620     albertel 6322:       $namespace=$env{'request.state'};
1.168     albertel 6323:     #}
                   6324:   }
                   6325:   $namespace=~s/\//\_/g;
                   6326:   $namespace=~s/\W//g;
1.620     albertel 6327:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6328:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6329:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6330:       $stuname=&get_requestor_ip();
1.591     albertel 6331:   }
1.168     albertel 6332:   my $now=time;
                   6333:   my %hash;
1.1117    foxr     6334:   my $path=LONCAPA::tempdir();
1.168     albertel 6335:   if (tie(%hash,'GDBM_File',
                   6336: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6337: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6338:     $hash{"version:$symb"}++;
                   6339:     my $version=$hash{"version:$symb"};
                   6340:     my $allkeys=''; 
                   6341:     foreach my $key (keys(%$storehash)) {
                   6342:       $allkeys.=$key.':';
1.591     albertel 6343:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6344:     }
                   6345:     $hash{"$version:$symb:timestamp"}=$now;
                   6346:     $allkeys.='timestamp';
                   6347:     $hash{"$version:keys:$symb"}=$allkeys;
                   6348:     if (untie(%hash)) {
                   6349:       return 'ok';
                   6350:     } else {
                   6351:       return "error:$!";
                   6352:     }
                   6353:   } else {
                   6354:     return "error:$!";
                   6355:   }
                   6356: }
1.167     albertel 6357: 
1.168     albertel 6358: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6359: 
1.168     albertel 6360: sub tmprestore {
                   6361:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6362: 
1.168     albertel 6363:   if (!$symb) {
                   6364:     $symb=&symbread();
1.620     albertel 6365:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6366:   }
                   6367:   $symb=escape($symb);
                   6368: 
1.620     albertel 6369:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6370: 
1.620     albertel 6371:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6372:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6373:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6374:       $stuname=&get_requestor_ip();
1.591     albertel 6375:   }
1.168     albertel 6376:   my %returnhash;
                   6377:   $namespace=~s/\//\_/g;
                   6378:   $namespace=~s/\W//g;
                   6379:   my %hash;
1.1117    foxr     6380:   my $path=LONCAPA::tempdir();
1.168     albertel 6381:   if (tie(%hash,'GDBM_File',
                   6382: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6383: 	  &GDBM_READER(),0640)) {
1.168     albertel 6384:     my $version=$hash{"version:$symb"};
                   6385:     $returnhash{'version'}=$version;
                   6386:     my $scope;
                   6387:     for ($scope=1;$scope<=$version;$scope++) {
                   6388:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6389:       my @keys=split(/:/,$vkeys);
                   6390:       my $key;
                   6391:       $returnhash{"$scope:keys"}=$vkeys;
                   6392:       foreach $key (@keys) {
1.591     albertel 6393: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6394: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6395:       }
                   6396:     }
1.168     albertel 6397:     if (!(untie(%hash))) {
                   6398:       return "error:$!";
                   6399:     }
                   6400:   } else {
                   6401:     return "error:$!";
                   6402:   }
                   6403:   return %returnhash;
1.167     albertel 6404: }
                   6405: 
1.9       www      6406: # ----------------------------------------------------------------------- Store
                   6407: 
                   6408: sub store {
1.1172.2.64  raeburn  6409:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6410:     my $home='';
                   6411: 
1.168     albertel 6412:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6413: 
1.213     www      6414:     $symb=&symbclean($symb);
1.122     albertel 6415:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6416: 
1.620     albertel 6417:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6418:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6419: 
                   6420:     &devalidate($symb,$stuname,$domain);
1.109     www      6421: 
                   6422:     $symb=escape($symb);
1.187     www      6423:     if (!$namespace) { 
1.620     albertel 6424:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6425:           return ''; 
                   6426:        } 
                   6427:     }
1.620     albertel 6428:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6429: 
1.1172.2.138  raeburn  6430:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6431:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6432: 
1.12      www      6433:     my $namevalue='';
1.800     albertel 6434:     foreach my $key (keys(%$storehash)) {
                   6435:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6436:     }
1.12      www      6437:     $namevalue=~s/\&$//;
1.187     www      6438:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6439:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6440: }
                   6441: 
1.47      www      6442: # -------------------------------------------------------------- Critical Store
                   6443: 
                   6444: sub cstore {
1.1172.2.64  raeburn  6445:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6446:     my $home='';
                   6447: 
1.168     albertel 6448:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6449: 
1.213     www      6450:     $symb=&symbclean($symb);
1.122     albertel 6451:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6452: 
1.620     albertel 6453:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6454:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6455: 
                   6456:     &devalidate($symb,$stuname,$domain);
1.109     www      6457: 
                   6458:     $symb=escape($symb);
1.187     www      6459:     if (!$namespace) { 
1.620     albertel 6460:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6461:           return ''; 
                   6462:        } 
                   6463:     }
1.620     albertel 6464:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6465: 
1.1172.2.138  raeburn  6466:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6467:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6468: 
1.47      www      6469:     my $namevalue='';
1.800     albertel 6470:     foreach my $key (keys(%$storehash)) {
                   6471:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6472:     }
1.47      www      6473:     $namevalue=~s/\&$//;
1.187     www      6474:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6475:     return critical
1.1172.2.64  raeburn  6476:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6477: }
                   6478: 
1.9       www      6479: # --------------------------------------------------------------------- Restore
                   6480: 
                   6481: sub restore {
1.124     www      6482:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6483:     my $home='';
                   6484: 
1.168     albertel 6485:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6486: 
1.122     albertel 6487:     if (!$symb) {
1.1172.2.26  raeburn  6488:         return if ($namespace eq 'courserequests');
                   6489:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6490:     } else {
1.1172.2.26  raeburn  6491:         unless ($namespace eq 'courserequests') {
                   6492:             $symb=&escape(&symbclean($symb));
                   6493:         }
1.122     albertel 6494:     }
1.188     www      6495:     if (!$namespace) { 
1.620     albertel 6496:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6497:           return ''; 
                   6498:        } 
                   6499:     }
1.620     albertel 6500:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6501:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6502:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6503:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6504: 
1.12      www      6505:     my %returnhash=();
1.800     albertel 6506:     foreach my $line (split(/\&/,$answer)) {
                   6507: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6508:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6509:     }
1.75      www      6510:     my $version;
                   6511:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6512:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6513:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6514:        }
1.75      www      6515:     }
1.13      www      6516:     return %returnhash;
1.34      www      6517: }
                   6518: 
                   6519: # ---------------------------------------------------------- Course Description
1.1118    foxr     6520: #
                   6521: #  
1.34      www      6522: 
                   6523: sub coursedescription {
1.731     albertel 6524:     my ($courseid,$args)=@_;
1.34      www      6525:     $courseid=~s/^\///;
1.49      www      6526:     $courseid=~s/\_/\//g;
1.34      www      6527:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6528:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6529:     my $normalid=$cdomain.'_'.$cnum;
                   6530:     # need to always cache even if we get errors otherwise we keep 
                   6531:     # trying and trying and trying to get the course description.
                   6532:     my %envhash=();
                   6533:     my %returnhash=();
1.731     albertel 6534:     
                   6535:     my $expiretime=600;
                   6536:     if ($env{'request.course.id'} eq $normalid) {
                   6537: 	$expiretime=120;
                   6538:     }
                   6539: 
                   6540:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6541:     if (!$args->{'freshen_cache'}
                   6542: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6543: 	foreach my $key (keys(%env)) {
                   6544: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6545: 	    my ($setting) = $1;
                   6546: 	    $returnhash{$setting} = $env{$key};
                   6547: 	}
                   6548: 	return %returnhash;
                   6549:     }
                   6550: 
1.1118    foxr     6551:     # get the data again
                   6552: 
1.731     albertel 6553:     if (!$args->{'one_time'}) {
                   6554: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6555:     }
1.811     albertel 6556: 
1.34      www      6557:     if ($chome ne 'no_host') {
1.302     albertel 6558:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6559:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6560: 	   my $username = $env{'user.name'}; # Defult username
                   6561: 	   if(defined $args->{'user'}) {
                   6562: 	       $username = $args->{'user'};
                   6563: 	   }
1.129     albertel 6564:            $returnhash{'home'}= $chome;
                   6565: 	   $returnhash{'domain'} = $cdomain;
                   6566: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6567:            if (!defined($returnhash{'type'})) {
                   6568:                $returnhash{'type'} = 'Course';
                   6569:            }
1.130     albertel 6570:            while (my ($name,$value) = each %returnhash) {
1.53      www      6571:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6572:            }
1.270     www      6573:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6574:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6575: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6576:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6577:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6578:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6579:        }
                   6580:     }
1.731     albertel 6581:     if (!$args->{'one_time'}) {
1.949     raeburn  6582: 	&appenv(\%envhash);
1.731     albertel 6583:     }
1.302     albertel 6584:     return %returnhash;
1.461     www      6585: }
                   6586: 
1.1080    raeburn  6587: sub update_released_required {
                   6588:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6589:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6590:         $cid = $env{'request.course.id'};
                   6591:         $cdom = $env{'course.'.$cid.'.domain'};
                   6592:         $cnum = $env{'course.'.$cid.'.num'};
                   6593:         $chome = $env{'course.'.$cid.'.home'};
                   6594:     }
                   6595:     if ($needsrelease) {
                   6596:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6597:         my $needsupdate;
                   6598:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6599:             $needsupdate = 1;
                   6600:         } else {
                   6601:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6602:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6603:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6604:                 $needsupdate = 1;
                   6605:             }
                   6606:         }
                   6607:         if ($needsupdate) {
                   6608:             my %needshash = (
                   6609:                              'internal.releaserequired' => $needsrelease,
                   6610:                             );
                   6611:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6612:             if ($putresult eq 'ok') {
                   6613:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6614:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6615:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6616:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6617:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6618:                 }
                   6619:             }
                   6620:         }
                   6621:     }
                   6622:     return;
                   6623: }
                   6624: 
1.461     www      6625: # -------------------------------------------------See if a user is privileged
                   6626: 
                   6627: sub privileged {
1.1172.2.23  raeburn  6628:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6629:     my $now = time;
1.1172.2.23  raeburn  6630:     my $roles;
                   6631:     if (ref($possroles) eq 'ARRAY') {
                   6632:         $roles = $possroles;
                   6633:     } else {
                   6634:         $roles = ['dc','su'];
                   6635:     }
                   6636:     if (ref($possdomains) eq 'ARRAY') {
                   6637:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6638:         foreach my $dom (@{$possdomains}) {
                   6639:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6640:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6641:                 foreach my $role (@{$roles}) {
                   6642:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6643:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6644:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6645:                             return 1 unless (($end && $end < $now) ||
                   6646:                                              ($start && $start > $now));
                   6647:                         }
                   6648:                     }
                   6649:                 }
                   6650:             }
                   6651:         }
                   6652:     } else {
                   6653:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6654:         my $now = time;
1.1170    droeschl 6655: 
1.1172.2.58  raeburn  6656:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6657:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6658:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6659:                 return 1 unless ($tend && $tend < $now)
                   6660:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6661:             }
1.1172.2.23  raeburn  6662:         }
                   6663:     }
1.461     www      6664:     return 0;
1.9       www      6665: }
1.1       albertel 6666: 
1.1172.2.23  raeburn  6667: sub privileged_by_domain {
                   6668:     my ($domains,$roles) = @_;
                   6669:     my %privileged = ();
                   6670:     my $cachetime = 60*60*24;
                   6671:     my $now = time;
                   6672:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6673:         return %privileged;
                   6674:     }
                   6675:     foreach my $dom (@{$domains}) {
                   6676:         next if (ref($privileged{$dom}) eq 'HASH');
                   6677:         my $needroles;
                   6678:         foreach my $role (@{$roles}) {
                   6679:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6680:             if (defined($cached)) {
                   6681:                 if (ref($result) eq 'HASH') {
                   6682:                     $privileged{$dom}{$role} = $result;
                   6683:                 }
                   6684:             } else {
                   6685:                 $needroles = 1;
                   6686:             }
                   6687:         }
                   6688:         if ($needroles) {
                   6689:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6690:             $privileged{$dom} = {};
                   6691:             foreach my $server (keys(%dompersonnel)) {
                   6692:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6693:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6694:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6695:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6696:                         next if ($end && $end < $now);
                   6697:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6698:                             $dompersonnel{$server}{$item};
                   6699:                     }
                   6700:                 }
                   6701:             }
                   6702:             if (ref($privileged{$dom}) eq 'HASH') {
                   6703:                 foreach my $role (@{$roles}) {
                   6704:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6705:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6706:                     } else {
                   6707:                         my %hash = ();
                   6708:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6709:                     }
                   6710:                 }
                   6711:             }
                   6712:         }
                   6713:     }
                   6714:     return %privileged;
                   6715: }
                   6716: 
1.103     harris41 6717: # -------------------------------------------------------- Get user privileges
1.11      www      6718: 
                   6719: sub rolesinit {
1.1169    droeschl 6720:     my ($domain, $username) = @_;
                   6721:     my %userroles = ('user.login.time' => time);
                   6722:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6723: 
                   6724:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6725:     # also, blocking can be triggered by an activating timer
                   6726:     # it's saved in the user's %env.
                   6727:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6728:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6729:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6730:         %timerintchk, %timerintenv);
                   6731: 
1.1162    raeburn  6732:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6733:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6734:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6735:     }
1.1169    droeschl 6736: 
1.1162    raeburn  6737:     foreach my $key (keys(%timerinterval)) {
                   6738:         my ($cid,$rest) = split(/\0/,$key);
                   6739:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6740:     }
1.1169    droeschl 6741: 
1.11      www      6742:     my %allroles=();
1.1162    raeburn  6743:     my %allgroups=();
1.11      www      6744: 
1.1172.2.58  raeburn  6745:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6746:         my $role = $rolesdump{$area};
                   6747:         $area =~ s/\_\w\w$//;
                   6748: 
                   6749:         my ($trole, $tend, $tstart, $group_privs);
                   6750: 
                   6751:         if ($role =~ /^cr/) {
                   6752:         # Custom role, defined by a user 
                   6753:         # e.g., user.role.cr/msu/smith/mynewrole
                   6754:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6755:                 $trole = $1;
                   6756:                 ($tend, $tstart) = split('_', $2);
                   6757:             } else {
                   6758:                 $trole = $role;
                   6759:             }
                   6760:         } elsif ($role =~ m|^gr/|) {
                   6761:         # Role of member in a group, defined within a course/community
                   6762:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6763:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6764:             next if $tstart eq '-1';
                   6765:             ($trole, $group_privs) = split(/\//, $trole);
                   6766:             $group_privs = &unescape($group_privs);
                   6767:         } else {
                   6768:         # Just a normal role, defined in roles.tab
                   6769:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6770:         }
                   6771: 
                   6772:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6773:                  $username);
                   6774:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6775: 
                   6776:         # role expired or not available yet?
                   6777:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6778:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6779: 
                   6780:         next if $area eq '' or $trole eq '';
                   6781: 
                   6782:         my $spec = "$trole.$area";
                   6783:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6784: 
                   6785:         if ($trole =~ /^cr\//) {
                   6786:         # Custom role, defined by a user
                   6787:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6788:         } elsif ($trole eq 'gr') {
                   6789:         # Role of a member in a group, defined within a course/community
                   6790:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6791:             next;
                   6792:         } else {
                   6793:         # Normal role, defined in roles.tab
                   6794:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6795:         }
                   6796: 
                   6797:         my $cid = $tdomain.'_'.$trest;
                   6798:         unless ($firstaccchk{$cid}) {
                   6799:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6800:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6801:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6802:                         $coursetimerstarts{$cid}{$item}; 
                   6803:                 }
                   6804:             }
                   6805:             $firstaccchk{$cid} = 1;
                   6806:         }
                   6807:         unless ($timerintchk{$cid}) {
                   6808:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6809:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6810:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6811:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6812:                 }
1.12      www      6813:             }
1.1169    droeschl 6814:             $timerintchk{$cid} = 1;
1.191     harris41 6815:         }
1.11      www      6816:     }
1.1169    droeschl 6817: 
1.1172.2.91  raeburn  6818:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6819:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6820:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6821:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6822: 
1.1162    raeburn  6823:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6824: }
                   6825: 
1.567     raeburn  6826: sub set_arearole {
1.1172.2.19  raeburn  6827:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6828:     unless ($nolog) {
1.567     raeburn  6829: # log the associated role with the area
1.1172.2.19  raeburn  6830:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6831:     }
1.743     albertel 6832:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6833: }
                   6834: 
                   6835: sub custom_roleprivs {
                   6836:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6837:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6838:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6839:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6840:         my ($rdummy,$roledef)=
                   6841:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6842:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6843:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6844:             if (defined($syspriv)) {
1.1043    raeburn  6845:                 if ($trest =~ /^$match_community$/) {
                   6846:                     $syspriv =~ s/bre\&S//; 
                   6847:                 }
1.567     raeburn  6848:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6849:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6850:             }
                   6851:             if ($tdomain ne '') {
                   6852:                 if (defined($dompriv)) {
                   6853:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6854:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6855:                 }
                   6856:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6857:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6858:                         my $rolename = $1;
                   6859:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6860:                     }
1.567     raeburn  6861:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6862:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6863:                 }
                   6864:             }
                   6865:         }
                   6866:     }
                   6867: }
                   6868: 
1.1172.2.89  raeburn  6869: sub course_adhocrole_privs {
                   6870:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6871:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6872:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6873:         my (%currprivs,%storeprivs);
                   6874:         foreach my $item (split(/:/,$coursepriv)) {
                   6875:             my ($priv,$restrict) = split(/\&/,$item);
                   6876:             $currprivs{$priv} = $restrict;
                   6877:         }
                   6878:         my (%possadd,%possremove,%full);
                   6879:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6880:             my ($priv,$restrict)=split(/\&/,$item);
                   6881:             $full{$priv} = $restrict;
                   6882:         }
                   6883:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
1.1172.2.146.  .6(raebu 6884:22):             next if ($item eq '');
                   6885:22):             my ($rule,$rest) = split(/=/,$item);
                   6886:22):             next unless (($rule eq 'off') || ($rule eq 'on'));
                   6887:22):             foreach my $priv (split(/:/,$rest)) {
                   6888:22):                 if ($priv ne '') {
                   6889:22):                     if ($rule eq 'off') {
                   6890:22):                         $possremove{$priv} = 1;
                   6891:22):                     } else {
                   6892:22):                         $possadd{$priv} = 1;
                   6893:22):                     }
                   6894:22):                 }
                   6895:22):             }
                   6896:22):         }
                   6897:22):         foreach my $priv (sort(keys(%full))) {
                   6898:22):             if (exists($currprivs{$priv})) {
                   6899:22):                 unless (exists($possremove{$priv})) {
                   6900:22):                     $storeprivs{$priv} = $currprivs{$priv};
                   6901:22):                 }
                   6902:22):             } elsif (exists($possadd{$priv})) {
                   6903:22):                 $storeprivs{$priv} = $full{$priv};
                   6904:22):             }
                   6905:22):         }
                   6906:22):         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6907:22):     }
                   6908:22):     return $coursepriv;
1.1172.2.89  raeburn  6909: }
                   6910: 
1.678     raeburn  6911: sub group_roleprivs {
                   6912:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6913:     my $access = 1;
                   6914:     my $now = time;
                   6915:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6916:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6917:     if ($access) {
1.811     albertel 6918:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6919:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6920:     }
                   6921: }
1.567     raeburn  6922: 
                   6923: sub standard_roleprivs {
                   6924:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6925:     if (defined($pr{$trole.':s'})) {
                   6926:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6927:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6928:     }
                   6929:     if ($tdomain ne '') {
                   6930:         if (defined($pr{$trole.':d'})) {
                   6931:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6932:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6933:         }
                   6934:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6935:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6936:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6937:         }
                   6938:     }
                   6939: }
                   6940: 
                   6941: sub set_userprivs {
1.1064    raeburn  6942:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6943:     my $author=0;
                   6944:     my $adv=0;
1.1172.2.91  raeburn  6945:     my $rar=0;
1.678     raeburn  6946:     my %grouproles = ();
                   6947:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6948:         my @groupkeys; 
1.1000    raeburn  6949:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6950:             push(@groupkeys,$role);
                   6951:         }
                   6952:         if (ref($groups_roles) eq 'HASH') {
                   6953:             foreach my $key (keys(%{$groups_roles})) {
                   6954:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6955:                     push(@groupkeys,$key);
                   6956:                 }
                   6957:             }
                   6958:         }
                   6959:         if (@groupkeys > 0) {
                   6960:             foreach my $role (@groupkeys) {
                   6961:                 my ($trole,$area,$sec,$extendedarea);
                   6962:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6963:                     $trole = $1;
                   6964:                     $area = $2;
                   6965:                     $sec = $3;
                   6966:                     $extendedarea = $area.$sec;
                   6967:                     if (exists($$allgroups{$area})) {
                   6968:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6969:                             my $spec = $trole.'.'.$extendedarea;
                   6970:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6971:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6972:                         }
1.678     raeburn  6973:                     }
                   6974:                 }
                   6975:             }
                   6976:         }
                   6977:     }
1.800     albertel 6978:     foreach my $group (keys(%grouproles)) {
                   6979:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6980:     }
1.800     albertel 6981:     foreach my $role (keys(%{$allroles})) {
                   6982:         my %thesepriv;
1.941     raeburn  6983:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6984:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6985:             if ($item ne '') {
                   6986:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6987:                 if ($restrictions eq '') {
                   6988:                     $thesepriv{$privilege}='F';
                   6989:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6990:                     $thesepriv{$privilege}.=$restrictions;
                   6991:                 }
                   6992:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6993:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6994:             }
                   6995:         }
                   6996:         my $thesestr='';
1.1104    raeburn  6997:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6998: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6999: 	}
                   7000:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  7001:     }
1.1172.2.91  raeburn  7002:     return ($author,$adv,$rar);
1.567     raeburn  7003: }
                   7004: 
1.994     raeburn  7005: sub role_status {
1.1104    raeburn  7006:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  7007:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  7008:         my ($one,$two) = split(m{\./},$rolekey,2);
                   7009:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  7010:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  7011:             $$where = '/'.$two;
1.994     raeburn  7012:             $$trolecode=$$role.'.'.$$where;
                   7013:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   7014:             $$tstatus='is';
1.1104    raeburn  7015:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  7016:                 $$tstatus='future';
1.1034    raeburn  7017:                 if ($$tstart<$now) {
                   7018:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  7019:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  7020:                             my (%allroles,%allgroups,$group_privs,
                   7021:                                 %groups_roles,@rolecodes);
1.1002    raeburn  7022:                             my %userroles = (
                   7023:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   7024:                             );
1.1064    raeburn  7025:                             @rolecodes = ('cm'); 
1.1002    raeburn  7026:                             my $spec=$$role.'.'.$$where;
                   7027:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   7028:                             if ($$role =~ /^cr\//) {
                   7029:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  7030:                                 push(@rolecodes,'cr');
1.1002    raeburn  7031:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  7032:                                 push(@rolecodes,$$role);
1.1002    raeburn  7033:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   7034:                                                     $env{'user.name'});
1.1064    raeburn  7035:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  7036:                                 (undef,my $group_privs) = split(/\//,$trole);
                   7037:                                 $group_privs = &unescape($group_privs);
                   7038:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  7039:                                 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  7040:                                 &get_groups_roles($tdomain,$trest,
                   7041:                                                   \%course_roles,\@rolecodes,
                   7042:                                                   \%groups_roles);
1.1002    raeburn  7043:                             } else {
1.1064    raeburn  7044:                                 push(@rolecodes,$$role);
1.1002    raeburn  7045:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   7046:                             }
1.1172.2.91  raeburn  7047:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   7048:                                                                    \%groups_roles);
1.1064    raeburn  7049:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  7050:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  7051:                         }
                   7052:                     }
1.1034    raeburn  7053:                     $$tstatus = 'is';
1.1002    raeburn  7054:                 }
1.994     raeburn  7055:             }
                   7056:             if ($$tend) {
1.1104    raeburn  7057:                 if ($$tend<$update) {
1.994     raeburn  7058:                     $$tstatus='expired';
                   7059:                 } elsif ($$tend<$now) {
                   7060:                     $$tstatus='will_not';
                   7061:                 }
                   7062:             }
                   7063:         }
                   7064:     }
                   7065: }
                   7066: 
1.1104    raeburn  7067: sub get_groups_roles {
                   7068:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   7069:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   7070:                   (ref($rolecodes) eq 'ARRAY') && 
                   7071:                   (ref($groups_roles) eq 'HASH')); 
                   7072:     if (keys(%{$cdom_courseroles}) > 0) {
                   7073:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   7074:         if ($cdom ne '' && $cnum ne '') {
                   7075:             foreach my $key (keys(%{$cdom_courseroles})) {
                   7076:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   7077:                     my $crsrole = $1;
                   7078:                     my $crssec = $2;
                   7079:                     if ($crsrole =~ /^cr/) {
                   7080:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   7081:                             push(@{$rolecodes},'cr');
                   7082:                         }
                   7083:                     } else {
                   7084:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   7085:                             push(@{$rolecodes},$crsrole);
                   7086:                         }
                   7087:                     }
                   7088:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   7089:                     if ($crssec ne '') {
                   7090:                         $rolekey .= "/$crssec";
                   7091:                     }
                   7092:                     $rolekey .= './';
                   7093:                     $groups_roles->{$rolekey} = $rolecodes;
                   7094:                 }
                   7095:             }
                   7096:         }
                   7097:     }
                   7098:     return;
                   7099: }
                   7100: 
                   7101: sub delete_env_groupprivs {
                   7102:     my ($where,$courseroles,$possroles) = @_;
                   7103:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   7104:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   7105:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   7106:         %{$courseroles->{$udom}} =
                   7107:             &get_my_roles('','','userroles',['active'],
                   7108:                           $possroles,[$udom],1);
                   7109:     }
                   7110:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   7111:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   7112:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   7113:             my $area = '/'.$cdom.'/'.$cnum;
                   7114:             my $privkey = "user.priv.$crsrole.$area";
                   7115:             if ($crssec ne '') {
                   7116:                 $privkey .= '/'.$crssec;
                   7117:             }
                   7118:             $privkey .= ".$area/$group";
                   7119:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   7120:         }
                   7121:     }
                   7122:     return;
                   7123: }
                   7124: 
1.994     raeburn  7125: sub check_adhoc_privs {
1.1172.2.86  raeburn  7126:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  7127:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  7128:     if ($sec) {
                   7129:         $cckey .= '/'.$sec;
                   7130:     }
1.1172.2.9  raeburn  7131:     my $setprivs;
1.994     raeburn  7132:     if ($env{$cckey}) {
                   7133:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  7134:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  7135:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  7136:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  7137:             $setprivs = 1;
1.994     raeburn  7138:         }
                   7139:     } else {
1.1172.2.87  raeburn  7140:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  7141:         $setprivs = 1;
1.994     raeburn  7142:     }
1.1172.2.9  raeburn  7143:     return $setprivs;
1.994     raeburn  7144: }
                   7145: 
                   7146: sub set_adhoc_privileges {
1.1172.2.84  raeburn  7147: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  7148:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  7149:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  7150:     if ($sec ne '') {
                   7151:         $area .= '/'.$sec;
                   7152:     }
1.994     raeburn  7153:     my $spec = $role.'.'.$area;
                   7154:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  7155:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  7156:     my %rolehash = ();
1.1172.2.89  raeburn  7157:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   7158:         my $rolename = $1;
1.1172.2.84  raeburn  7159:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  7160:         my %domdef = &get_domain_defaults($dcdom);
                   7161:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   7162:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   7163:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   7164:             }
                   7165:         }
1.1172.2.84  raeburn  7166:     } else {
                   7167:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   7168:     }
1.1172.2.91  raeburn  7169:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  7170:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  7171:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1172.2.146.  .1(raebu 7172:22):     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   7173:22):             ($caller eq 'tiny')) {
1.1088    raeburn  7174:         &appenv( {'request.role'        => $spec,
                   7175:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  7176:                   'request.course.sec'  => $sec, 
1.1088    raeburn  7177:                  }
                   7178:                );
                   7179:         my $tadv=0;
                   7180:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   7181:         &appenv({'request.role.adv'    => $tadv});
                   7182:     }
1.994     raeburn  7183: }
                   7184: 
1.12      www      7185: # --------------------------------------------------------------- get interface
                   7186: 
                   7187: sub get {
1.131     albertel 7188:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7189:    my $items='';
1.800     albertel 7190:    foreach my $item (@$storearr) {
                   7191:        $items.=&escape($item).'&';
1.191     harris41 7192:    }
1.12      www      7193:    $items=~s/\&$//;
1.620     albertel 7194:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7195:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 7196:    my $uhome=&homeserver($uname,$udomain);
                   7197: 
1.133     albertel 7198:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7199:    my @pairs=split(/\&/,$rep);
1.273     albertel 7200:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   7201:      return @pairs;
                   7202:    }
1.15      www      7203:    my %returnhash=();
1.42      www      7204:    my $i=0;
1.800     albertel 7205:    foreach my $item (@$storearr) {
                   7206:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7207:       $i++;
1.191     harris41 7208:    }
1.15      www      7209:    return %returnhash;
1.27      www      7210: }
                   7211: 
                   7212: # --------------------------------------------------------------- del interface
                   7213: 
                   7214: sub del {
1.133     albertel 7215:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      7216:    my $items='';
1.800     albertel 7217:    foreach my $item (@$storearr) {
                   7218:        $items.=&escape($item).'&';
1.191     harris41 7219:    }
1.984     neumanie 7220: 
1.27      www      7221:    $items=~s/\&$//;
1.620     albertel 7222:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7223:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7224:    my $uhome=&homeserver($uname,$udomain);
                   7225:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7226: }
                   7227: 
                   7228: # -------------------------------------------------------------- dump interface
                   7229: 
1.1172.2.22  raeburn  7230: sub unserialize {
                   7231:     my ($rep, $escapedkeys) = @_;
                   7232: 
                   7233:     return {} if $rep =~ /^error/;
                   7234: 
                   7235:     my %returnhash=();
                   7236:     foreach my $item (split(/\&/,$rep)) {
                   7237:         my ($key, $value) = split(/=/, $item, 2);
                   7238:         $key = unescape($key) unless $escapedkeys;
                   7239:         next if $key =~ /^error: 2 /;
                   7240:         $returnhash{$key} = &thaw_unescape($value);
                   7241:     }
                   7242:     return \%returnhash;
                   7243: }
                   7244: 
                   7245: # see Lond::dump_with_regexp
                   7246: # if $escapedkeys hash keys won't get unescaped.
1.15      www      7247: sub dump {
1.1172.2.146.  .1(raebu 7248:22):     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755     albertel 7249:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7250:     if (!$uname) { $uname=$env{'user.name'}; }
                   7251:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 7252: 
1.1172.2.55  raeburn  7253:     if ($regexp) {
                   7254:         $regexp=&escape($regexp);
                   7255:     } else {
                   7256:         $regexp='.';
                   7257:     }
1.1172.2.22  raeburn  7258:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   7259:         # user is hosted on this machine
1.1172.2.55  raeburn  7260:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  7261:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  7262:         return %{&unserialize($reply, $escapedkeys)};
                   7263:     }
1.1172.2.146.  .1(raebu 7264:22):     my $rep;
                   7265:22):     if ($encrypt) {
                   7266:22):         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7267:22):     } else {
                   7268:22):         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7269:22):     }
1.755     albertel 7270:     my @pairs=split(/\&/,$rep);
                   7271:     my %returnhash=();
1.1098    foxr     7272:     if (!($rep =~ /^error/ )) {
                   7273: 	foreach my $item (@pairs) {
                   7274: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  7275:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     7276: 	    next if ($key =~ /^error: 2 /);
                   7277: 	    $returnhash{$key}=&thaw_unescape($value);
                   7278: 	}
1.755     albertel 7279:     }
                   7280:     return %returnhash;
1.407     www      7281: }
                   7282: 
1.1098    foxr     7283: 
1.717     albertel 7284: # --------------------------------------------------------- dumpstore interface
                   7285: 
                   7286: sub dumpstore {
                   7287:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  7288:    # same as dump but keys must be escaped. They may contain colon separated
                   7289:    # lists of values that may themself contain colons (e.g. symbs).
                   7290:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7291: }
                   7292: 
1.407     www      7293: # -------------------------------------------------------------- keys interface
                   7294: 
                   7295: sub getkeys {
                   7296:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7297:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7298:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7299:    my $uhome=&homeserver($uname,$udomain);
                   7300:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7301:    my @keyarray=();
1.800     albertel 7302:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7303:       next if ($key =~ /^error: 2 /);
1.800     albertel 7304:       push(@keyarray,&unescape($key));
1.407     www      7305:    }
                   7306:    return @keyarray;
1.318     matthew  7307: }
                   7308: 
1.319     matthew  7309: # --------------------------------------------------------------- currentdump
                   7310: sub currentdump {
1.328     matthew  7311:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7312:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7313:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7314:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7315:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  7316:    my $rep;
                   7317: 
                   7318:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7319:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   7320:                    $courseid)));
                   7321:    } else {
                   7322:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7323:    }
                   7324: 
1.318     matthew  7325:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7326:    #
1.318     matthew  7327:    my %returnhash=();
1.319     matthew  7328:    #
                   7329:    if ($rep eq "unknown_cmd") { 
                   7330:        # an old lond will not know currentdump
                   7331:        # Do a dump and make it look like a currentdump
1.822     albertel 7332:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7333:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7334:        my %hash = @tmp;
                   7335:        @tmp=();
1.424     matthew  7336:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7337:    } else {
                   7338:        my @pairs=split(/\&/,$rep);
1.800     albertel 7339:        foreach my $pair (@pairs) {
                   7340:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7341:            my ($symb,$param) = split(/:/,$key);
                   7342:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7343:                                                         &thaw_unescape($value);
1.319     matthew  7344:        }
1.191     harris41 7345:    }
1.12      www      7346:    return %returnhash;
1.424     matthew  7347: }
                   7348: 
                   7349: sub convert_dump_to_currentdump{
                   7350:     my %hash = %{shift()};
                   7351:     my %returnhash;
                   7352:     # Code ripped from lond, essentially.  The only difference
                   7353:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7354:     # we might run in to problems with parameter names =~ /^v\./
                   7355:     while (my ($key,$value) = each(%hash)) {
                   7356:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7357: 	$symb  = &unescape($symb);
                   7358: 	$param = &unescape($param);
1.424     matthew  7359:         next if ($v eq 'version' || $symb eq 'keys');
                   7360:         next if (exists($returnhash{$symb}) &&
                   7361:                  exists($returnhash{$symb}->{$param}) &&
                   7362:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7363:         $returnhash{$symb}->{$param}=$value;
                   7364:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7365:     }
                   7366:     #
                   7367:     # Remove all of the keys in the hashes which keep track of
                   7368:     # the version of the parameter.
                   7369:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7370:         # use a foreach because we are going to delete from the hash.
                   7371:         foreach my $key (keys(%$param_hash)) {
                   7372:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7373:         }
                   7374:     }
                   7375:     return \%returnhash;
1.12      www      7376: }
                   7377: 
1.627     albertel 7378: # ------------------------------------------------------ critical inc interface
                   7379: 
                   7380: sub cinc {
                   7381:     return &inc(@_,'critical');
                   7382: }
                   7383: 
1.449     matthew  7384: # --------------------------------------------------------------- inc interface
                   7385: 
                   7386: sub inc {
1.627     albertel 7387:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7388:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7389:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7390:     my $uhome=&homeserver($uname,$udomain);
                   7391:     my $items='';
                   7392:     if (! ref($store)) {
                   7393:         # got a single value, so use that instead
                   7394:         $items = &escape($store).'=&';
                   7395:     } elsif (ref($store) eq 'SCALAR') {
                   7396:         $items = &escape($$store).'=&';        
                   7397:     } elsif (ref($store) eq 'ARRAY') {
                   7398:         $items = join('=&',map {&escape($_);} @{$store});
                   7399:     } elsif (ref($store) eq 'HASH') {
                   7400:         while (my($key,$value) = each(%{$store})) {
                   7401:             $items.= &escape($key).'='.&escape($value).'&';
                   7402:         }
                   7403:     }
                   7404:     $items=~s/\&$//;
1.627     albertel 7405:     if ($critical) {
                   7406: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7407:     } else {
                   7408: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7409:     }
1.449     matthew  7410: }
                   7411: 
1.12      www      7412: # --------------------------------------------------------------- put interface
                   7413: 
                   7414: sub put {
1.1172.2.146.  .1(raebu 7415:22):    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620     albertel 7416:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7417:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7418:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7419:    my $items='';
1.800     albertel 7420:    foreach my $item (keys(%$storehash)) {
                   7421:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7422:    }
1.12      www      7423:    $items=~s/\&$//;
1.1172.2.146.  .1(raebu 7424:22):    if ($encrypt) {
                   7425:22):        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
                   7426:22):    } else {
                   7427:22):        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   7428:22):    }
1.47      www      7429: }
                   7430: 
1.631     albertel 7431: # ------------------------------------------------------------ newput interface
                   7432: 
                   7433: sub newput {
                   7434:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7435:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7436:    if (!$uname) { $uname=$env{'user.name'}; }
                   7437:    my $uhome=&homeserver($uname,$udomain);
                   7438:    my $items='';
                   7439:    foreach my $key (keys(%$storehash)) {
                   7440:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7441:    }
                   7442:    $items=~s/\&$//;
                   7443:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7444: }
                   7445: 
                   7446: # ---------------------------------------------------------  putstore interface
                   7447: 
1.524     raeburn  7448: sub putstore {
1.1172.2.59  raeburn  7449:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7450:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7451:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7452:    my $uhome=&homeserver($uname,$udomain);
                   7453:    my $items='';
1.715     albertel 7454:    foreach my $key (keys(%$storehash)) {
                   7455:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7456:    }
1.715     albertel 7457:    $items=~s/\&$//;
1.716     albertel 7458:    my $esc_symb=&escape($symb);
                   7459:    my $esc_v=&escape($version);
1.715     albertel 7460:    my $reply =
1.716     albertel 7461:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7462: 	      $uhome);
1.1172.2.59  raeburn  7463:    if (($tolog) && ($reply eq 'ok')) {
                   7464:        my $namevalue='';
                   7465:        foreach my $key (keys(%{$storehash})) {
                   7466:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7467:        }
1.1172.2.134  raeburn  7468:        my $ip = &get_requestor_ip();
1.1172.2.135  raeburn  7469:        $namevalue .= 'ip='.&escape($ip).
1.1172.2.59  raeburn  7470:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7471:                      '&version='.$esc_v.
                   7472:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7473:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7474:    }
1.715     albertel 7475:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7476:        # gfall back to way things use to be done
1.715     albertel 7477:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7478: 			    $uname);
1.524     raeburn  7479:    }
1.715     albertel 7480:    return $reply;
                   7481: }
                   7482: 
                   7483: sub old_putstore {
1.716     albertel 7484:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7485:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7486:     if (!$uname) { $uname=$env{'user.name'}; }
                   7487:     my $uhome=&homeserver($uname,$udomain);
                   7488:     my %newstorehash;
1.800     albertel 7489:     foreach my $item (keys(%$storehash)) {
                   7490: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7491: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7492:     }
                   7493:     my $items='';
                   7494:     my %allitems = ();
1.800     albertel 7495:     foreach my $item (keys(%newstorehash)) {
                   7496: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7497: 	    my $key = $1.':keys:'.$2;
                   7498: 	    $allitems{$key} .= $3.':';
                   7499: 	}
1.800     albertel 7500: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7501:     }
1.800     albertel 7502:     foreach my $item (keys(%allitems)) {
                   7503: 	$allitems{$item} =~ s/\:$//;
                   7504: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7505:     }
                   7506:     $items=~s/\&$//;
                   7507:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7508: }
                   7509: 
1.47      www      7510: # ------------------------------------------------------ critical put interface
                   7511: 
                   7512: sub cput {
1.134     albertel 7513:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7514:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7515:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7516:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7517:    my $items='';
1.800     albertel 7518:    foreach my $item (keys(%$storehash)) {
                   7519:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7520:    }
1.47      www      7521:    $items=~s/\&$//;
1.134     albertel 7522:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7523: }
                   7524: 
                   7525: # -------------------------------------------------------------- eget interface
                   7526: 
                   7527: sub eget {
1.133     albertel 7528:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7529:    my $items='';
1.800     albertel 7530:    foreach my $item (@$storearr) {
                   7531:        $items.=&escape($item).'&';
1.191     harris41 7532:    }
1.12      www      7533:    $items=~s/\&$//;
1.620     albertel 7534:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7535:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7536:    my $uhome=&homeserver($uname,$udomain);
                   7537:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7538:    my @pairs=split(/\&/,$rep);
                   7539:    my %returnhash=();
1.42      www      7540:    my $i=0;
1.800     albertel 7541:    foreach my $item (@$storearr) {
                   7542:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7543:       $i++;
1.191     harris41 7544:    }
1.12      www      7545:    return %returnhash;
                   7546: }
                   7547: 
1.667     albertel 7548: # ------------------------------------------------------------ tmpput interface
                   7549: sub tmpput {
1.802     raeburn  7550:     my ($storehash,$server,$context)=@_;
1.667     albertel 7551:     my $items='';
1.800     albertel 7552:     foreach my $item (keys(%$storehash)) {
                   7553: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7554:     }
                   7555:     $items=~s/\&$//;
1.802     raeburn  7556:     if (defined($context)) {
                   7557:         $items .= ':'.&escape($context);
                   7558:     }
1.667     albertel 7559:     return &reply("tmpput:$items",$server);
                   7560: }
                   7561: 
                   7562: # ------------------------------------------------------------ tmpget interface
                   7563: sub tmpget {
1.688     albertel 7564:     my ($token,$server)=@_;
                   7565:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7566:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7567:     my %returnhash;
1.1172.2.85  raeburn  7568:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7569:         return %returnhash;
                   7570:     }
1.667     albertel 7571:     foreach my $item (split(/\&/,$rep)) {
                   7572: 	my ($key,$value)=split(/=/,$item);
                   7573: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7574:     }
                   7575:     return %returnhash;
                   7576: }
                   7577: 
1.1113    raeburn  7578: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7579: sub tmpdel {
                   7580:     my ($token,$server)=@_;
                   7581:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7582:     return &reply("tmpdel:$token",$server);
                   7583: }
                   7584: 
1.1172.2.13  raeburn  7585: # ------------------------------------------------------------ get_timebased_id
                   7586: 
                   7587: sub get_timebased_id {
                   7588:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7589:         $maxtries) = @_;
                   7590:     my ($newid,$error,$dellock);
                   7591:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7592:         return ('','ok','invalid call to get suffix');
                   7593:     }
                   7594: 
                   7595: # set defaults for any optional args for which values were not supplied
                   7596:     if ($who eq '') {
                   7597:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7598:     }
                   7599:     if (!$locktries) {
                   7600:         $locktries = 3;
                   7601:     }
                   7602:     if (!$maxtries) {
                   7603:         $maxtries = 10;
                   7604:     }
                   7605: 
                   7606:     if (($cdom eq '') || ($cnum eq '')) {
                   7607:         if ($env{'request.course.id'}) {
                   7608:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7609:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7610:         }
                   7611:         if (($cdom eq '') || ($cnum eq '')) {
                   7612:             return ('','ok','call to get suffix not in course context');
                   7613:         }
                   7614:     }
                   7615: 
                   7616: # construct locking item
                   7617:     my $lockhash = {
                   7618:                       $prefix."\0".'locked_'.$keyid => $who,
                   7619:                    };
                   7620:     my $tries = 0;
                   7621: 
                   7622: # attempt to get lock on nohist_$namespace file
                   7623:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7624:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7625:         $tries ++;
                   7626:         sleep 1;
                   7627:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7628:     }
                   7629: 
                   7630: # attempt to get unique identifier, based on current timestamp
                   7631:     if ($gotlock eq 'ok') {
                   7632:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7633:         my $id = time;
                   7634:         $newid = $id;
1.1172.2.56  raeburn  7635:         if ($idtype eq 'addcode') {
                   7636:             $newid .= &sixnum_code();
                   7637:         }
1.1172.2.13  raeburn  7638:         my $idtries = 0;
                   7639:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7640:             if ($idtype eq 'concat') {
                   7641:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7642:             } elsif ($idtype eq 'addcode') {
                   7643:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7644:             } else {
                   7645:                 $newid ++;
                   7646:             }
                   7647:             $idtries ++;
                   7648:         }
                   7649:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7650:             my %new_item =  (
                   7651:                               $prefix."\0".$newid => $who,
                   7652:                             );
                   7653:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7654:                                                  $cdom,$cnum);
                   7655:             if ($putresult ne 'ok') {
                   7656:                 undef($newid);
                   7657:                 $error = 'error saving new item: '.$putresult;
                   7658:             }
                   7659:         } else {
1.1172.2.56  raeburn  7660:              undef($newid);
1.1172.2.13  raeburn  7661:              $error = ('error: no unique suffix available for the new item ');
                   7662:         }
                   7663: #  remove lock
                   7664:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7665:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7666:     } else {
                   7667:         $error = "error: could not obtain lockfile\n";
                   7668:         $dellock = 'ok';
1.1172.2.58  raeburn  7669:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7670:             $dellock = 'nolock';
                   7671:         }
1.1172.2.13  raeburn  7672:     }
                   7673:     return ($newid,$dellock,$error);
                   7674: }
                   7675: 
1.1172.2.56  raeburn  7676: sub sixnum_code {
                   7677:     my $code;
                   7678:     for (0..6) {
                   7679:         $code .= int( rand(9) );
                   7680:     }
                   7681:     return $code;
                   7682: }
                   7683: 
1.765     albertel 7684: # -------------------------------------------------- portfolio access checking
                   7685: 
                   7686: sub portfolio_access {
1.1172.2.77  raeburn  7687:     my ($requrl,$clientip) = @_;
1.765     albertel 7688:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7689:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7690:     if ($result) {
                   7691:         my %setters;
                   7692:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142  raeburn  7693:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7694:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
                   7695:             if (($startblock && $endblock) || ($by_ip))  {
1.814     raeburn  7696:                 return 'B';
                   7697:             }
                   7698:         } else {
1.1172.2.142  raeburn  7699:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
                   7700:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7701:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7702:                 return 'B';
                   7703:             }
                   7704:         }
                   7705:     }
1.765     albertel 7706:     if ($result eq 'ok') {
1.766     albertel 7707:        return 'F';
1.765     albertel 7708:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7709:        return 'A';
1.765     albertel 7710:     }
1.766     albertel 7711:     return '';
1.765     albertel 7712: }
                   7713: 
                   7714: sub get_portfolio_access {
1.1172.2.77  raeburn  7715:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7716: 
                   7717:     if (!ref($access_hash)) {
                   7718: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7719: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7720: 						   $file_name);
                   7721: 	$access_hash = $access_controls{$file_name};
                   7722:     }
                   7723: 
1.1172.2.77  raeburn  7724:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7725:     my $now = time;
                   7726:     if (ref($access_hash) eq 'HASH') {
                   7727:         foreach my $key (keys(%{$access_hash})) {
                   7728:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7729:             if ($start > $now) {
                   7730:                 next;
                   7731:             }
                   7732:             if ($end && $end<$now) {
                   7733:                 next;
                   7734:             }
                   7735:             if ($scope eq 'public') {
                   7736:                 $public = $key;
                   7737:                 last;
                   7738:             } elsif ($scope eq 'guest') {
                   7739:                 $guest = $key;
                   7740:             } elsif ($scope eq 'domains') {
                   7741:                 push(@domains,$key);
                   7742:             } elsif ($scope eq 'users') {
                   7743:                 push(@users,$key);
                   7744:             } elsif ($scope eq 'course') {
                   7745:                 push(@courses,$key);
                   7746:             } elsif ($scope eq 'group') {
                   7747:                 push(@groups,$key);
1.1172.2.77  raeburn  7748:             } elsif ($scope eq 'ip') {
                   7749:                 push(@ips,$key);
1.765     albertel 7750:             }
                   7751:         }
                   7752:         if ($public) {
                   7753:             return 'ok';
1.1172.2.77  raeburn  7754:         } elsif (@ips > 0) {
                   7755:             my $allowed;
                   7756:             foreach my $ipkey (@ips) {
                   7757:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7758:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7759:                         $allowed = 1;
                   7760:                         last;
                   7761:                     }
                   7762:                 }
                   7763:             }
                   7764:             if ($allowed) {
                   7765:                 return 'ok';
                   7766:             }
1.765     albertel 7767:         }
                   7768:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7769:             if ($guest) {
                   7770:                 return $guest;
                   7771:             }
                   7772:         } else {
                   7773:             if (@domains > 0) {
                   7774:                 foreach my $domkey (@domains) {
                   7775:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7776:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7777:                             return 'ok';
                   7778:                         }
                   7779:                     }
                   7780:                 }
                   7781:             }
                   7782:             if (@users > 0) {
                   7783:                 foreach my $userkey (@users) {
1.865     raeburn  7784:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7785:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7786:                             if (ref($item) eq 'HASH') {
                   7787:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7788:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7789:                                     return 'ok';
                   7790:                                 }
                   7791:                             }
                   7792:                         }
                   7793:                     } 
1.765     albertel 7794:                 }
                   7795:             }
                   7796:             my %roleshash;
                   7797:             my @courses_and_groups = @courses;
                   7798:             push(@courses_and_groups,@groups); 
                   7799:             if (@courses_and_groups > 0) {
                   7800:                 my (%allgroups,%allroles); 
                   7801:                 my ($start,$end,$role,$sec,$group);
                   7802:                 foreach my $envkey (%env) {
1.1060    raeburn  7803:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7804:                         my $cid = $2.'_'.$3; 
                   7805:                         if ($1 eq 'gr') {
                   7806:                             $group = $4;
                   7807:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7808:                         } else {
                   7809:                             if ($4 eq '') {
                   7810:                                 $sec = 'none';
                   7811:                             } else {
                   7812:                                 $sec = $4;
                   7813:                             }
                   7814:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7815:                         }
1.811     albertel 7816:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7817:                         my $cid = $2.'_'.$3;
                   7818:                         if ($4 eq '') {
                   7819:                             $sec = 'none';
                   7820:                         } else {
                   7821:                             $sec = $4;
                   7822:                         }
                   7823:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7824:                     }
                   7825:                 }
                   7826:                 if (keys(%allroles) == 0) {
                   7827:                     return;
                   7828:                 }
                   7829:                 foreach my $key (@courses_and_groups) {
                   7830:                     my %content = %{$$access_hash{$key}};
                   7831:                     my $cnum = $content{'number'};
                   7832:                     my $cdom = $content{'domain'};
                   7833:                     my $cid = $cdom.'_'.$cnum;
                   7834:                     if (!exists($allroles{$cid})) {
                   7835:                         next;
                   7836:                     }    
                   7837:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7838:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7839:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7840:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7841:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7842:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7843:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7844:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7845:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7846:                                         if (grep/^all$/,@sections) {
                   7847:                                             return 'ok';
                   7848:                                         } else {
                   7849:                                             if (grep/^$sec$/,@sections) {
                   7850:                                                 return 'ok';
                   7851:                                             }
                   7852:                                         }
                   7853:                                     }
                   7854:                                 }
                   7855:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7856:                                     if (grep/^none$/,@groups) {
                   7857:                                         return 'ok';
                   7858:                                     }
                   7859:                                 } else {
                   7860:                                     if (grep/^all$/,@groups) {
                   7861:                                         return 'ok';
                   7862:                                     } 
                   7863:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7864:                                         if (grep/^$group$/,@groups) {
                   7865:                                             return 'ok';
                   7866:                                         }
                   7867:                                     }
                   7868:                                 } 
                   7869:                             }
                   7870:                         }
                   7871:                     }
                   7872:                 }
                   7873:             }
                   7874:             if ($guest) {
                   7875:                 return $guest;
                   7876:             }
                   7877:         }
                   7878:     }
                   7879:     return;
                   7880: }
                   7881: 
                   7882: sub course_group_datechecker {
                   7883:     my ($dates,$now,$status) = @_;
                   7884:     my ($start,$end) = split(/\./,$dates);
                   7885:     if (!$start && !$end) {
                   7886:         return 'ok';
                   7887:     }
                   7888:     if (grep/^active$/,@{$status}) {
                   7889:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7890:             return 'ok';
                   7891:         }
                   7892:     }
                   7893:     if (grep/^previous$/,@{$status}) {
                   7894:         if ($end > $now ) {
                   7895:             return 'ok';
                   7896:         }
                   7897:     }
                   7898:     if (grep/^future$/,@{$status}) {
                   7899:         if ($start > $now) {
                   7900:             return 'ok';
                   7901:         }
                   7902:     }
                   7903:     return; 
                   7904: }
                   7905: 
                   7906: sub parse_portfolio_url {
                   7907:     my ($url) = @_;
                   7908: 
                   7909:     my ($type,$udom,$unum,$group,$file_name);
                   7910:     
1.823     albertel 7911:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7912: 	$type = 1;
                   7913:         $udom = $1;
                   7914:         $unum = $2;
                   7915:         $file_name = $3;
1.823     albertel 7916:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7917: 	$type = 2;
                   7918:         $udom = $1;
                   7919:         $unum = $2;
                   7920:         $group = $3;
                   7921:         $file_name = $3.'/'.$4;
                   7922:     }
                   7923:     if (wantarray) {
                   7924: 	return ($type,$udom,$unum,$file_name,$group);
                   7925:     }
                   7926:     return $type;
                   7927: }
                   7928: 
                   7929: sub is_portfolio_url {
                   7930:     my ($url) = @_;
                   7931:     return scalar(&parse_portfolio_url($url));
                   7932: }
                   7933: 
1.798     raeburn  7934: sub is_portfolio_file {
                   7935:     my ($file) = @_;
1.820     raeburn  7936:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7937:         return 1;
                   7938:     }
                   7939:     return;
                   7940: }
                   7941: 
1.1172.2.146.  .13(raeb 7942:-23): sub is_coursetool_logo {
                   7943:-23):     my ($uri) = @_;
                   7944:-23):     if ($env{'request.course.id'}) {
                   7945:-23):         my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   7946:-23):         if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
                   7947:-23):             return 1;
                   7948:-23):         }
                   7949:-23):     }
                   7950:-23):     return;
                   7951:-23): }
                   7952:-23): 
1.976     raeburn  7953: sub usertools_access {
1.1084    raeburn  7954:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7955:     my ($access,%tools);
                   7956:     if ($context eq '') {
                   7957:         $context = 'tools';
                   7958:     }
                   7959:     if ($context eq 'requestcourses') {
                   7960:         %tools = (
                   7961:                       official   => 1,
                   7962:                       unofficial => 1,
1.1006    raeburn  7963:                       community  => 1,
1.1172.2.37  raeburn  7964:                       textbook   => 1,
1.1172.2.146.  .13(raeb 7965:-23):                       lti        => 1,
1.985     raeburn  7966:                  );
1.1172.2.9  raeburn  7967:     } elsif ($context eq 'requestauthor') {
                   7968:         %tools = (
                   7969:                       requestauthor => 1,
                   7970:                  );
1.985     raeburn  7971:     } else {
                   7972:         %tools = (
                   7973:                       aboutme   => 1,
                   7974:                       blog      => 1,
1.1172.2.6  raeburn  7975:                       webdav    => 1,
1.985     raeburn  7976:                       portfolio => 1,
1.1172.2.146.  .6(raebu 7977:22):                       timezone  => 1,
1.985     raeburn  7978:                  );
                   7979:     }
1.976     raeburn  7980:     return if (!defined($tools{$tool}));
                   7981: 
1.1172.2.35  raeburn  7982:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7983:         $udom = $env{'user.domain'};
                   7984:         $uname = $env{'user.name'};
                   7985:     }
                   7986: 
1.978     raeburn  7987:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7988:         if ($action ne 'reload') {
1.985     raeburn  7989:             if ($context eq 'requestcourses') {
                   7990:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7991:             } elsif ($context eq 'requestauthor') {
                   7992:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7993:             } else {
                   7994:                 return $env{'environment.availabletools.'.$tool};
                   7995:             }
                   7996:         }
1.976     raeburn  7997:     }
                   7998: 
1.1172.2.9  raeburn  7999:     my ($toolstatus,$inststatus,$envkey);
                   8000:     if ($context eq 'requestauthor') {
                   8001:         $envkey = $context;
                   8002:     } else {
                   8003:         $envkey = $context.'.'.$tool;
                   8004:     }
1.976     raeburn  8005: 
1.985     raeburn  8006:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8007:          ($action ne 'reload')) {
1.1172.2.9  raeburn  8008:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  8009:         $inststatus = $env{'environment.inststatus'};
                   8010:     } else {
1.1084    raeburn  8011:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  8012:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  8013:             $inststatus = $userenvref->{'inststatus'};
                   8014:         } else {
1.1172.2.9  raeburn  8015:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   8016:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  8017:             $inststatus = $userenv{'inststatus'};
                   8018:         }
1.976     raeburn  8019:     }
                   8020: 
                   8021:     if ($toolstatus ne '') {
                   8022:         if ($toolstatus) {
                   8023:             $access = 1;
                   8024:         } else {
                   8025:             $access = 0;
                   8026:         }
                   8027:         return $access;
                   8028:     }
                   8029: 
1.1084    raeburn  8030:     my ($is_adv,%domdef);
                   8031:     if (ref($is_advref) eq 'HASH') {
                   8032:         $is_adv = $is_advref->{'is_adv'};
                   8033:     } else {
                   8034:         $is_adv = &is_advanced_user($udom,$uname);
                   8035:     }
                   8036:     if (ref($domdefref) eq 'HASH') {
                   8037:         %domdef = %{$domdefref};
                   8038:     } else {
                   8039:         %domdef = &get_domain_defaults($udom);
                   8040:     }
1.976     raeburn  8041:     if (ref($domdef{$tool}) eq 'HASH') {
                   8042:         if ($is_adv) {
                   8043:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   8044:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   8045:                     $access = 1;
                   8046:                 } else {
                   8047:                     $access = 0;
                   8048:                 }
                   8049:                 return $access;
                   8050:             }
                   8051:         }
                   8052:         if ($inststatus ne '') {
                   8053:             my ($hasaccess,$hasnoaccess);
                   8054:             foreach my $affiliation (split(/:/,$inststatus)) {
                   8055:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   8056:                     if ($domdef{$tool}{$affiliation}) {
                   8057:                         $hasaccess = 1;
                   8058:                     } else {
                   8059:                         $hasnoaccess = 1;
                   8060:                     }
                   8061:                 }
                   8062:             }
                   8063:             if ($hasaccess || $hasnoaccess) {
                   8064:                 if ($hasaccess) {
                   8065:                     $access = 1;
                   8066:                 } elsif ($hasnoaccess) {
                   8067:                     $access = 0; 
                   8068:                 }
                   8069:                 return $access;
                   8070:             }
                   8071:         } else {
                   8072:             if ($domdef{$tool}{'default'} ne '') {
                   8073:                 if ($domdef{$tool}{'default'}) {
                   8074:                     $access = 1;
                   8075:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   8076:                     $access = 0;
                   8077:                 }
                   8078:                 return $access;
                   8079:             }
                   8080:         }
                   8081:     } else {
1.1172.2.6  raeburn  8082:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  8083:             $access = 1;
                   8084:         } else {
                   8085:             $access = 0;
                   8086:         }
1.976     raeburn  8087:         return $access;
                   8088:     }
                   8089: }
                   8090: 
1.1050    raeburn  8091: sub is_course_owner {
                   8092:     my ($cdom,$cnum,$udom,$uname) = @_;
                   8093:     if (($udom eq '') || ($uname eq '')) {
                   8094:         $udom = $env{'user.domain'};
                   8095:         $uname = $env{'user.name'};
                   8096:     }
                   8097:     unless (($udom eq '') || ($uname eq '')) {
                   8098:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   8099:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   8100:                 return 1;
                   8101:             } else {
                   8102:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   8103:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   8104:                     return 1;
                   8105:                 }
                   8106:             }
                   8107:         }
                   8108:     }
                   8109:     return;
                   8110: }
                   8111: 
1.976     raeburn  8112: sub is_advanced_user {
                   8113:     my ($udom,$uname) = @_;
1.1085    raeburn  8114:     if ($udom ne '' && $uname ne '') {
                   8115:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  8116:             if (wantarray) {
                   8117:                 return ($env{'user.adv'},$env{'user.author'});
                   8118:             } else {
                   8119:                 return $env{'user.adv'};
                   8120:             }
1.1085    raeburn  8121:         }
                   8122:     }
1.976     raeburn  8123:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   8124:     my %allroles;
1.1128    raeburn  8125:     my ($is_adv,$is_author);
1.976     raeburn  8126:     foreach my $role (keys(%roleshash)) {
                   8127:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   8128:         my $area = '/'.$tdomain.'/'.$trest;
                   8129:         if ($sec ne '') {
                   8130:             $area .= '/'.$sec;
                   8131:         }
                   8132:         if (($area ne '') && ($trole ne '')) {
                   8133:             my $spec=$trole.'.'.$area;
                   8134:             if ($trole =~ /^cr\//) {
                   8135:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   8136:             } elsif ($trole ne 'gr') {
                   8137:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   8138:             }
1.1128    raeburn  8139:             if ($trole eq 'au') {
                   8140:                 $is_author = 1;
                   8141:             }
1.976     raeburn  8142:         }
                   8143:     }
                   8144:     foreach my $role (keys(%allroles)) {
                   8145:         last if ($is_adv);
                   8146:         foreach my $item (split(/:/,$allroles{$role})) {
                   8147:             if ($item ne '') {
                   8148:                 my ($privilege,$restrictions)=split(/&/,$item);
                   8149:                 if ($privilege eq 'adv') {
                   8150:                     $is_adv = 1;
                   8151:                     last;
                   8152:                 }
                   8153:             }
                   8154:         }
                   8155:     }
1.1128    raeburn  8156:     if (wantarray) {
                   8157:         return ($is_adv,$is_author);
                   8158:     }
1.976     raeburn  8159:     return $is_adv;
                   8160: }
1.798     raeburn  8161: 
1.1035    raeburn  8162: sub check_can_request {
1.1172.2.146.  .13(raeb 8163:-23):     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  8164:     my $canreq = 0;
1.1172.2.146.  .13(raeb 8165:-23):     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8166:-23):         $uname = $env{'user.name'};
                   8167:-23):         $udom = $env{'user.domain'};
                   8168:-23):     }
1.1035    raeburn  8169:     my ($types,$typename) = &Apache::loncommon::course_types();
                   8170:     my @options = ('approval','validate','autolimit');
                   8171:     my $optregex = join('|',@options);
                   8172:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   8173:         foreach my $type (@{$types}) {
1.1172.2.146.  .13(raeb 8174:-23):             if (&usertools_access($uname,$udom,$type,undef,
                   8175:-23):                                   'requestcourses')) {
1.1035    raeburn  8176:                 $canreq ++;
1.1036    raeburn  8177:                 if (ref($request_domains) eq 'HASH') {
1.1172.2.146.  .13(raeb 8178:-23):                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  8179:                 }
1.1172.2.146.  .13(raeb 8180:-23):                 if ($dom eq $udom) {
1.1035    raeburn  8181:                     $can_request->{$type} = 1;
                   8182:                 }
                   8183:             }
1.1172.2.146.  .13(raeb 8184:-23):             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   8185:-23):                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  8186:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   8187:                 if (@curr > 0) {
1.1036    raeburn  8188:                     foreach my $item (@curr) {
                   8189:                         if (ref($request_domains) eq 'HASH') {
                   8190:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   8191:                             if ($otherdom ne '') {
                   8192:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   8193:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   8194:                                         push(@{$request_domains->{$type}},$otherdom);
                   8195:                                     }
                   8196:                                 } else {
                   8197:                                     push(@{$request_domains->{$type}},$otherdom);
                   8198:                                 }
                   8199:                             }
                   8200:                         }
                   8201:                     }
1.1172.2.146.  .13(raeb 8202:-23):                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  8203:                         $canreq ++;
1.1035    raeburn  8204:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   8205:                             $can_request->{$type} = 1;
                   8206:                         }
                   8207:                     }
                   8208:                 }
                   8209:             }
                   8210:         }
                   8211:     }
                   8212:     return $canreq;
                   8213: }
                   8214: 
1.341     www      8215: # ---------------------------------------------- Custom access rule evaluation
                   8216: 
                   8217: sub customaccess {
                   8218:     my ($priv,$uri)=@_;
1.807     albertel 8219:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      8220:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 8221:     $udom = &LONCAPA::clean_domain($udom);
                   8222:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      8223:     my $access=0;
1.800     albertel 8224:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 8225: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   8226: 	if ($type eq 'user') {
                   8227: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 8228: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 8229: 		if ($tdom) {
                   8230: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   8231: 		}
1.896     albertel 8232: 		if ($tuname) {
                   8233: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 8234: 		}
                   8235: 		$access=($effect eq 'allow');
                   8236: 		last;
                   8237: 	    }
                   8238: 	} else {
                   8239: 	    if ($role) {
                   8240: 		if ($role ne $urole) { next; }
                   8241: 	    }
                   8242: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   8243: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   8244: 		if ($tdom) {
                   8245: 		    if ($tdom ne $udom) { next; }
                   8246: 		}
                   8247: 		if ($tcrs) {
                   8248: 		    if ($tcrs ne $ucrs) { next; }
                   8249: 		}
                   8250: 		if ($tsec) {
                   8251: 		    if ($tsec ne $usec) { next; }
                   8252: 		}
                   8253: 		$access=($effect eq 'allow');
                   8254: 		last;
                   8255: 	    }
                   8256: 	    if ($realm eq '' && $role eq '') {
                   8257: 		$access=($effect eq 'allow');
                   8258: 	    }
1.402     bowersj2 8259: 	}
1.341     www      8260:     }
                   8261:     return $access;
                   8262: }
                   8263: 
1.103     harris41 8264: # ------------------------------------------------- Check for a user privilege
1.12      www      8265: 
                   8266: sub allowed {
1.1172.2.146.  .1(raebu 8267:22):     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705     albertel 8268:     my $ver_orguri=$uri;
1.439     www      8269:     $uri=&deversion($uri);
1.152     www      8270:     my $orguri=$uri;
1.52      www      8271:     $uri=&declutter($uri);
1.809     raeburn  8272: 
1.810     raeburn  8273:     if ($priv eq 'evb') {
1.1172.2.146.  .3(raebu 8274:22): # Evade communication block restrictions for specified role in a course or domain
1.810     raeburn  8275:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   8276:             return $1;
                   8277:         } else {
                   8278:             return;
                   8279:         }
                   8280:     }
                   8281: 
1.620     albertel 8282:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      8283: # Free bre access to adm and meta resources
1.1172.2.146.  .1(raebu 8284:22):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 8285: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   8286: 	&& ($priv eq 'bre')) {
1.14      www      8287: 	return 'F';
1.159     www      8288:     }
                   8289: 
1.545     banghart 8290: # Free bre access to user's own portfolio contents
1.714     raeburn  8291:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  8292:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  8293: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8294:         my %setters;
1.1172.2.142  raeburn  8295:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   8296:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   8297:         if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  8298:             return 'B';
                   8299:         } else {
                   8300:             return 'F';
                   8301:         }
1.545     banghart 8302:     }
                   8303: 
1.762     raeburn  8304: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8305:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8306:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8307:         if (exists($env{'request.course.id'})) {
                   8308:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8309:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8310:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8311:                 my $courseprivid=$env{'request.course.id'};
                   8312:                 $courseprivid=~s/\_/\//;
                   8313:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8314:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8315:                     return $1; 
1.762     raeburn  8316:                 } else {
                   8317:                     if ($env{'request.course.sec'}) {
                   8318:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8319:                     }
                   8320:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8321:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8322:                         return $2;
                   8323:                     }
1.714     raeburn  8324:                 }
                   8325:             }
                   8326:         }
                   8327:     }
                   8328: 
1.159     www      8329: # Free bre to public access
                   8330: 
                   8331:     if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8332:22):         my $copyright;
                   8333:22):         unless ($uri =~ /ext\.tool/) {
                   8334:22):             $copyright=&metadata($uri,'copyright');
                   8335:22):         }
1.620     albertel 8336: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8337:            return 'F'; 
                   8338:         }
1.238     www      8339:         if ($copyright eq 'priv') {
                   8340:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8341: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8342: 		return '';
                   8343:             }
                   8344:         }
                   8345:         if ($copyright eq 'domain') {
                   8346:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8347: 	    unless (($env{'user.domain'} eq $1) ||
                   8348:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8349: 		return '';
                   8350:             }
1.262     matthew  8351:         }
1.620     albertel 8352:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8353:             # Library role, so allow browsing of resources in this domain.
                   8354:             return 'F';
1.238     www      8355:         }
1.341     www      8356:         if ($copyright eq 'custom') {
                   8357: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8358:         }
1.14      www      8359:     }
1.264     matthew  8360:     # Domain coordinator is trying to create a course
1.620     albertel 8361:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8362:         # uri is the requested domain in this case.
                   8363:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8364:         # a role of dc for the domain in question.
1.620     albertel 8365:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8366:     }
1.29      www      8367: 
1.52      www      8368:     my $thisallowed='';
                   8369:     my $statecond=0;
                   8370:     my $courseprivid='';
                   8371: 
1.1039    raeburn  8372:     my $ownaccess;
1.1043    raeburn  8373:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8374:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8375:         if ($uri eq '') {
                   8376:             $ownaccess = 1;
                   8377:         } else {
                   8378:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8379:                 my $udom = $env{'user.domain'};
                   8380:                 my $uname = $env{'user.name'};
                   8381:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8382:                     $ownaccess = 1;
1.1040    raeburn  8383:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8384:                     unless ($uri =~ m{\.\./}) {
                   8385:                         $ownaccess = 1;
                   8386:                     }
                   8387:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8388:                     my $now = time;
                   8389:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8390:                         my $adom = $1;
                   8391:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8392:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142  raeburn  8393:                                 my ($start,$end) = split(/\./,$env{$key});
                   8394:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  8395:                                     $ownaccess = 1;
                   8396:                                     last;
                   8397:                                 }
                   8398:                             }
                   8399:                         }
                   8400:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8401:                         my $adom = $1;
                   8402:                         my $aname = $2;
1.1042    raeburn  8403:                         foreach my $role ('ca','aa') { 
                   8404:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8405:                                 my ($start,$end) =
1.1172.2.142  raeburn  8406:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8407:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8408:                                     $ownaccess = 1;
                   8409:                                     last;
                   8410:                                 }
1.1039    raeburn  8411:                             }
                   8412:                         }
                   8413:                     }
                   8414:                 }
                   8415:             }
                   8416:         }
                   8417:     }
                   8418: 
1.52      www      8419: # Course
                   8420: 
1.620     albertel 8421:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8422:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8423:             $thisallowed.=$1;
                   8424:         }
1.52      www      8425:     }
1.29      www      8426: 
1.52      www      8427: # Domain
                   8428: 
1.620     albertel 8429:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8430:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8431:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8432:             $thisallowed.=$1;
                   8433:         }
1.12      www      8434:     }
1.52      www      8435: 
1.1141    raeburn  8436: # User who is not author or co-author might still be able to edit
                   8437: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8438:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8439:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8440:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8441:             $thisallowed.=$1;
                   8442:         }
                   8443:     }
                   8444: 
1.52      www      8445: # Course: uri itself is a course
1.66      www      8446:     my $courseuri=$uri;
                   8447:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8448:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8449: 
1.620     albertel 8450:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8451:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8452:         if ($priv eq 'mip') {
                   8453:             my $rem = $1;
                   8454:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8455:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8456:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8457:                 if ($cdom ne '') {
                   8458:                     my %passwdconf = &get_passwdconf($cdom);
                   8459:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8460:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8461:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8462:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8463:                                 unless (@inststatuses) {
                   8464:                                     @inststatuses = ('default');
                   8465:                                 }
                   8466:                                 foreach my $status (@inststatuses) {
                   8467:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8468:                                         $thisallowed.=$rem;
                   8469:                                     }
                   8470:                                 }
                   8471:                             }
                   8472:                         }
                   8473:                     }
                   8474:                 }
                   8475:             }
                   8476:         } else {
                   8477:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8478:                 $thisallowed.=$1;
                   8479:             }
1.1039    raeburn  8480:         }
1.12      www      8481:     }
1.29      www      8482: 
1.665     albertel 8483: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8484: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8485:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8486: 	$thisallowed='';
1.671     raeburn  8487:         my ($match)=&is_on_map($uri);
                   8488:         if ($match) {
                   8489:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8490:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8491:                 my $value = $1;
1.1172.2.146.  .1(raebu 8492:22):                 my $deeplinkblock;
                   8493:22):                 unless ($nodeeplinkcheck) {
                   8494:22):                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8495:22):                 }
                   8496:22):                 if ($deeplinkblock) {
                   8497:22):                     $thisallowed='D';
                   8498:22):                 } elsif ($noblockcheck) {
1.1172.2.65  raeburn  8499:                     $thisallowed.=$value;
1.1162    raeburn  8500:                 } else {
1.1172.2.126  raeburn  8501:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8502:                     if (@blockers > 0) {
                   8503:                         $thisallowed = 'B';
                   8504:                     } else {
                   8505:                         $thisallowed.=$value;
                   8506:                     }
1.1162    raeburn  8507:                 }
1.671     raeburn  8508:             }
                   8509:         } else {
1.705     albertel 8510:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8511:             if ($refuri) {
                   8512:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8513:                     $thisallowed='F';
1.671     raeburn  8514:                 } else {
                   8515:                     $refuri=&declutter($refuri);
                   8516:                     my ($match) = &is_on_map($refuri);
                   8517:                     if ($match) {
1.1172.2.146.  .1(raebu 8518:22):                         my $deeplinkblock;
                   8519:22):                         unless ($nodeeplinkcheck) {
                   8520:22):                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8521:22):                         }
                   8522:22):                         if ($deeplinkblock) {
                   8523:22):                             $thisallowed='D';
                   8524:22):                         } elsif ($noblockcheck) {
1.1162    raeburn  8525:                             $thisallowed='F';
1.1172.2.65  raeburn  8526:                         } else {
1.1172.2.127  raeburn  8527:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8528:                             if (@blockers > 0) {
                   8529:                                 $thisallowed = 'B';
                   8530:                             } else {
                   8531:                                 $thisallowed='F';
                   8532:                             }
1.1162    raeburn  8533:                         }
1.671     raeburn  8534:                     }
1.669     raeburn  8535:                 }
1.671     raeburn  8536:             }
                   8537:         }
1.314     www      8538:     }
1.492     albertel 8539: 
1.766     albertel 8540:     if ($priv eq 'bre'
                   8541: 	&& $thisallowed ne 'F' 
                   8542: 	&& $thisallowed ne '2'
                   8543: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8544: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8545:     }
                   8546:     
1.52      www      8547: # Full access at system, domain or course-wide level? Exit.
1.29      www      8548:     if ($thisallowed=~/F/) {
                   8549: 	return 'F';
                   8550:     }
                   8551: 
1.52      www      8552: # If this is generating or modifying users, exit with special codes
1.29      www      8553: 
1.643     www      8554:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8555: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8556: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8557: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8558: 	    unless ($auname) { return $thisallowed; }
                   8559: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8560: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8561: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8562: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8563: 	}
1.52      www      8564: 	return $thisallowed;
                   8565:     }
                   8566: #
1.103     harris41 8567: # Gathered so far: system, domain and course wide privileges
1.52      www      8568: #
                   8569: # Course: See if uri or referer is an individual resource that is part of 
                   8570: # the course
                   8571: 
1.620     albertel 8572:     if ($env{'request.course.id'}) {
1.232     www      8573: 
1.1172.2.146.  .13(raeb 8574:-23):         if ($priv eq 'bre') {
                   8575:-23):             if (&is_coursetool_logo($uri)) {
                   8576:-23):                 return 'F';
                   8577:-23):             }
                   8578:-23):         }
                   8579:-23): 
1.1172.2.115  raeburn  8580: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8581: 
                   8582:         if ($priv eq 'mip') {
                   8583:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8584:                 return $thisallowed;
                   8585:             } else {
                   8586:                 return '';
                   8587:             }
                   8588:         }
                   8589: 
1.620     albertel 8590:        $courseprivid=$env{'request.course.id'};
                   8591:        if ($env{'request.course.sec'}) {
                   8592:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8593:        }
                   8594:        $courseprivid=~s/\_/\//;
                   8595:        my $checkreferer=1;
1.232     www      8596:        my ($match,$cond)=&is_on_map($uri);
                   8597:        if ($match) {
                   8598:            $statecond=$cond;
1.620     albertel 8599:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8600:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8601:                my $value = $1;
                   8602:                if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8603:22):                    my $deeplinkblock;
                   8604:22):                    unless ($nodeeplinkcheck) {
                   8605:22):                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8606:22):                    }
                   8607:22):                    if ($deeplinkblock) {
                   8608:22):                        $thisallowed = 'D';
                   8609:22):                    } elsif ($noblockcheck) {
1.1162    raeburn  8610:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8611:                    } else {
1.1172.2.126  raeburn  8612:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8613:                        if (@blockers > 0) {
                   8614:                            $thisallowed = 'B';
                   8615:                        } else {
                   8616:                            $thisallowed.=$value;
                   8617:                        }
1.1162    raeburn  8618:                    }
                   8619:                } else {
                   8620:                    $thisallowed.=$value;
                   8621:                }
1.52      www      8622:                $checkreferer=0;
                   8623:            }
1.29      www      8624:        }
1.1172.2.126  raeburn  8625: 
1.148     www      8626:        if ($checkreferer) {
1.620     albertel 8627: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8628:             unless ($refuri) {
1.800     albertel 8629:                 foreach my $key (keys(%env)) {
                   8630: 		    if ($key=~/^httpref\..*\*/) {
                   8631: 			my $pattern=$key;
1.156     www      8632:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8633:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8634:                         $pattern=~s/\//\\\//g;
1.152     www      8635:                         if ($orguri=~/$pattern/) {
1.800     albertel 8636: 			    $refuri=$env{$key};
1.148     www      8637:                         }
                   8638:                     }
1.191     harris41 8639:                 }
1.148     www      8640:             }
1.232     www      8641: 
1.148     www      8642:          if ($refuri) { 
1.152     www      8643: 	  $refuri=&declutter($refuri);
1.232     www      8644:           my ($match,$cond)=&is_on_map($refuri);
                   8645:             if ($match) {
                   8646:               my $refstatecond=$cond;
1.620     albertel 8647:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8648:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8649:                   my $value = $1;
                   8650:                   if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8651:22):                       my $deeplinkblock;
                   8652:22):                       unless ($nodeeplinkcheck) {
                   8653:22):                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8654:22):                       }
                   8655:22):                       if ($deeplinkblock) {
                   8656:22):                           $thisallowed = 'D';
                   8657:22):                       } elsif ($noblockcheck) {
1.1162    raeburn  8658:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8659:                       } else {
1.1172.2.127  raeburn  8660:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8661:                           if (@blockers > 0) {
                   8662:                               $thisallowed = 'B';
                   8663:                           } else {
                   8664:                               $thisallowed.=$value;
                   8665:                           }
1.1162    raeburn  8666:                       }
                   8667:                   } else {
                   8668:                       $thisallowed.=$value;
                   8669:                   }
1.53      www      8670:                   $uri=$refuri;
                   8671:                   $statecond=$refstatecond;
1.52      www      8672:               }
                   8673:           }
1.148     www      8674:         }
1.29      www      8675:        }
1.52      www      8676:    }
1.29      www      8677: 
1.52      www      8678: #
1.103     harris41 8679: # Gathered now: all privileges that could apply, and condition number
1.52      www      8680: # 
                   8681: #
                   8682: # Full or no access?
                   8683: #
1.29      www      8684: 
1.52      www      8685:     if ($thisallowed=~/F/) {
                   8686: 	return 'F';
                   8687:     }
1.29      www      8688: 
1.52      www      8689:     unless ($thisallowed) {
                   8690:         return '';
                   8691:     }
1.29      www      8692: 
1.52      www      8693: # Restrictions exist, deal with them
                   8694: #
                   8695: #   C:according to course preferences
                   8696: #   R:according to resource settings
                   8697: #   L:unless locked
                   8698: #   X:according to user session state
                   8699: #
                   8700: 
                   8701: # Possibly locked functionality, check all courses
1.1172.2.142  raeburn  8702: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      8703: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142  raeburn  8704: # courses, and 2 minutes for current course, in which user has st or ta role
                   8705: # which is neither expired nor a future role (unless current course).
1.52      www      8706: 
1.1172.2.142  raeburn  8707:     my ($needlockcheck,$now,$crsonly);
1.52      www      8708:     if ($thisallowed=~/L/) {
1.1172.2.142  raeburn  8709:         $now = time;
                   8710:         if ($priv eq 'bre') {
                   8711:             if ($uri ne '') {
                   8712:                 if ($orguri =~ m{^/+res/}) {
                   8713:                     if ($uri =~ m{^lib/templates/}) {
                   8714:                         if ($env{'request.course.id'}) {
                   8715:                             $crsonly = 1;
                   8716:                             $needlockcheck = 1;
                   8717:                         }
                   8718:                     } else {
                   8719:                         $needlockcheck = 1;
                   8720:                     }
                   8721:                 } elsif ($env{'request.course.id'}) {
                   8722:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   8723:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   8724:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   8725:                         $crsonly = 1;
                   8726:                     }
                   8727:                     $needlockcheck = 1;
                   8728:                 }
                   8729:             }
                   8730:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   8731:             $needlockcheck = 1;
                   8732:         }
                   8733:     }
                   8734:     if ($needlockcheck) {
                   8735:         foreach my $envkey (keys(%env)) {
1.54      www      8736:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8737:                my $courseid=$2;
                   8738:                my $roleid=$1.'.'.$2;
1.92      www      8739:                $courseid=~s/^\///;
1.1172.2.142  raeburn  8740:                unless ($env{'request.role'} eq $roleid) {
                   8741:                    my ($start,$end) = split(/\./,$env{$envkey});
                   8742:                    next unless (($now >= $start) && (!$end || $end > $now));
                   8743:                }
1.54      www      8744:                my $expiretime=600;
1.620     albertel 8745:                if ($env{'request.role'} eq $roleid) {
1.54      www      8746: 		  $expiretime=120;
                   8747:                }
                   8748: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8749:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8750:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8751: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8752:                }
1.620     albertel 8753:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8754:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8755: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8756:                        &log($env{'user.domain'},$env{'user.name'},
                   8757:                             $env{'user.home'},
1.57      www      8758:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8759:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8760:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8761: 		       return '';
                   8762:                    }
                   8763:                }
1.620     albertel 8764:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8765:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142  raeburn  8766: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 8767:                        &log($env{'user.domain'},$env{'user.name'},
                   8768:                             $env{'user.home'},
1.57      www      8769:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8770:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8771:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8772: 		       return '';
                   8773:                    }
                   8774:                }
                   8775: 	   }
1.29      www      8776:        }
1.52      www      8777:     }
1.1172.2.126  raeburn  8778: 
1.52      www      8779: #
                   8780: # Rest of the restrictions depend on selected course
                   8781: #
                   8782: 
1.620     albertel 8783:     unless ($env{'request.course.id'}) {
1.766     albertel 8784: 	if ($thisallowed eq 'A') {
                   8785: 	    return 'A';
1.814     raeburn  8786:         } elsif ($thisallowed eq 'B') {
                   8787:             return 'B';
1.766     albertel 8788: 	} else {
                   8789: 	    return '1';
                   8790: 	}
1.52      www      8791:     }
1.29      www      8792: 
1.52      www      8793: #
                   8794: # Now user is definitely in a course
                   8795: #
1.53      www      8796: 
                   8797: 
                   8798: # Course preferences
                   8799: 
                   8800:    if ($thisallowed=~/C/) {
1.620     albertel 8801:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8802:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8803:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8804: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8805: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8806: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8807: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8808: 			$env{'request.course.id'});
                   8809: 	   }
1.237     www      8810:            return '';
                   8811:        }
                   8812: 
1.620     albertel 8813:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8814: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8815: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8816: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8817: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8818: 			$env{'request.course.id'});
                   8819: 	   }
1.54      www      8820:            return '';
                   8821:        }
1.53      www      8822:    }
                   8823: 
                   8824: # Resource preferences
                   8825: 
                   8826:    if ($thisallowed=~/R/) {
1.620     albertel 8827:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8828:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8829: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8830: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8831: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8832: 	   }
                   8833: 	   return '';
1.54      www      8834:        }
1.53      www      8835:    }
1.30      www      8836: 
1.1172.2.146.  .1(raebu 8837:22): # Restricted for deeplinked session?
                   8838:22): 
                   8839:22):     if ($env{'request.deeplink.login'}) {
                   8840:22):         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
                   8841:22):             if (!$symb) { $symb=&symbread($uri,1); }
                   8842:22):             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
                   8843:22):                 return '';
                   8844:22):             }
                   8845:22):         }
                   8846:22):     }
                   8847:22): 
1.246     www      8848: # Restricted by state or randomout?
1.30      www      8849: 
1.52      www      8850:    if ($thisallowed=~/X/) {
1.620     albertel 8851:       if ($env{'acc.randomout'}) {
1.579     albertel 8852: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8853:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8854:             return ''; 
                   8855:          }
1.247     www      8856:       }
                   8857:       if (&condval($statecond)) {
1.52      www      8858: 	 return '2';
                   8859:       } else {
                   8860:          return '';
                   8861:       }
                   8862:    }
1.30      www      8863: 
1.766     albertel 8864:     if ($thisallowed eq 'A') {
                   8865: 	return 'A';
1.814     raeburn  8866:     } elsif ($thisallowed eq 'B') {
                   8867:         return 'B';
1.1172.2.146.  .1(raebu 8868:22):     } elsif ($thisallowed eq 'D') {
                   8869:22):         return 'D';
1.766     albertel 8870:     }
1.52      www      8871:    return 'F';
1.232     www      8872: }
1.1162    raeburn  8873: 
1.1172.2.13  raeburn  8874: # ------------------------------------------- Check construction space access
                   8875: 
                   8876: sub constructaccess {
                   8877:     my ($url,$setpriv)=@_;
                   8878: 
                   8879: # We do not allow editing of previous versions of files
                   8880:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8881: 
                   8882: # Get username and domain from URL
                   8883:     my ($ownername,$ownerdomain,$ownerhome);
                   8884: 
                   8885:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8886:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8887: 
                   8888: # The URL does not really point to any authorspace, forget it
                   8889:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8890: 
                   8891: # Now we need to see if the user has access to the authorspace of
                   8892: # $ownername at $ownerdomain
                   8893: 
                   8894:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8895: # Real author for this?
                   8896:        $ownerhome = $env{'user.home'};
                   8897:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8898:           return ($ownername,$ownerdomain,$ownerhome);
                   8899:        }
                   8900:     } else {
                   8901: # Co-author for this?
                   8902:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8903:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8904:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8905:             return ($ownername,$ownerdomain,$ownerhome);
                   8906:         }
                   8907:     }
                   8908: 
                   8909: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8910: # we might as well leave
                   8911:    unless ($setpriv) { return ''; }
                   8912: 
                   8913: # Backdoor access?
                   8914:     my $allowed=&allowed('eco',$ownerdomain);
                   8915: # Nope
                   8916:     unless ($allowed) { return ''; }
                   8917: # Looks like we may have access, but could be locked by the owner of the construction space
                   8918:     if ($allowed eq 'U') {
                   8919:         my %blocked=&get('environment',['domcoord.author'],
                   8920:                          $ownerdomain,$ownername);
                   8921: # Is blocked by owner
                   8922:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8923:     }
                   8924:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8925: # Grant temporary access
                   8926:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8927:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8928:         if (!$update) { $update = $then; }
                   8929:         my $refresh=$env{'user.refresh.time'};
                   8930:         if (!$refresh) { $refresh = $update; }
                   8931:         my $now = time;
                   8932:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8933:                            $now,'ca','constructaccess');
                   8934:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8935:         return($ownername,$ownerdomain,$ownerhome);
                   8936:     }
                   8937: # No business here
                   8938:     return '';
                   8939: }
                   8940: 
1.1172.2.66  raeburn  8941: # ----------------------------------------------------------- Content Blocking
                   8942: 
                   8943: {
                   8944: # Caches for faster Course Contents display where content blocking
                   8945: # is in operation (i.e., interval param set) for timed quiz.
                   8946: #
                   8947: # User for whom data are being temporarily cached.
                   8948: my $cacheduser='';
1.1172.2.126  raeburn  8949: # Course for which data are being temporarily cached.
                   8950: my $cachedcid='';
1.1172.2.66  raeburn  8951: # Cached blockers for this user (a hash of blocking items).
                   8952: my %cachedblockers=();
                   8953: # When the data were last cached.
                   8954: my $cachedlast='';
                   8955: 
                   8956: sub load_all_blockers {
1.1172.2.128  raeburn  8957:     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8958:     if (($uname ne '') && ($udom ne '')) {
                   8959:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126  raeburn  8960:             ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128  raeburn  8961:             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8962:             return;
                   8963:         }
                   8964:     }
                   8965:     $cachedlast=time;
                   8966:     $cacheduser=$uname.':'.$udom;
1.1172.2.126  raeburn  8967:     $cachedcid=$env{'request.course.id'};
1.1172.2.128  raeburn  8968:     %cachedblockers = &get_commblock_resources();
1.1172.2.126  raeburn  8969:     return;
1.1172.2.66  raeburn  8970: }
                   8971: 
1.1162    raeburn  8972: sub get_comm_blocks {
                   8973:     my ($cdom,$cnum) = @_;
                   8974:     if ($cdom eq '' || $cnum eq '') {
                   8975:         return unless ($env{'request.course.id'});
                   8976:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8977:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8978:     }
                   8979:     my %commblocks;
                   8980:     my $hashid=$cdom.'_'.$cnum;
                   8981:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8982:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8983:         %commblocks = %{$blocksref};
                   8984:     } else {
                   8985:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8986:         my $cachetime = 600;
                   8987:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8988:     }
                   8989:     return %commblocks;
                   8990: }
                   8991: 
1.1172.2.66  raeburn  8992: sub get_commblock_resources {
                   8993:     my ($blocks) = @_;
                   8994:     my %blockers = ();
                   8995:     return %blockers unless ($env{'request.course.id'});
1.1172.2.142  raeburn  8996:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8997:     if ($env{'request.course.sec'}) {
                   8998:         $courseurl .= '/'.$env{'request.course.sec'};
                   8999:     }
                   9000:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  9001:     my %commblocks;
                   9002:     if (ref($blocks) eq 'HASH') {
                   9003:         %commblocks = %{$blocks};
                   9004:     } else {
                   9005:         %commblocks = &get_comm_blocks();
                   9006:     }
1.1172.2.66  raeburn  9007:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  9008:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  9009:     return %blockers unless (ref($navmap));
                   9010:     my $now = time;
1.1162    raeburn  9011:     foreach my $block (keys(%commblocks)) {
                   9012:         if ($block =~ /^(\d+)____(\d+)$/) {
                   9013:             my ($start,$end) = ($1,$2);
                   9014:             if ($start <= $now && $end >= $now) {
                   9015:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   9016:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   9017:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  9018:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   9019:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  9020:                             }
                   9021:                         }
                   9022:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  9023:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   9024:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  9025:                             }
                   9026:                         }
                   9027:                     }
                   9028:                 }
                   9029:             }
                   9030:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   9031:             my $item = $1;
                   9032:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   9033:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142  raeburn  9034:                     my (@interval,$mapname);
1.1172.2.66  raeburn  9035:                     my $type = 'map';
                   9036:                     if ($item eq 'course') {
                   9037:                         $type = 'course';
                   9038:                         @interval=&EXT("resource.0.interval");
                   9039:                     } else {
                   9040:                         if ($item =~ /___\d+___/) {
                   9041:                             $type = 'resource';
                   9042:                             @interval=&EXT("resource.0.interval",$item);
1.1162    raeburn  9043:                         } else {
1.1172.2.142  raeburn  9044:                             $mapname = &deversion($item);
                   9045:                             if (ref($navmap)) {
                   9046:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
                   9047:                                 @interval = ($timelimit,'map');
1.1162    raeburn  9048:                             }
                   9049:                         }
1.1172.2.66  raeburn  9050:                     }
1.1172.2.146.  .1(raebu 9051:22):                     if ($interval[0] =~ /^(\d+)/) {
                   9052:22):                         my $timelimit = $1;
1.1172.2.66  raeburn  9053:                         my $first_access;
                   9054:                         if ($type eq 'resource') {
                   9055:                             $first_access=&get_first_access($interval[1],$item);
                   9056:                         } elsif ($type eq 'map') {
                   9057:                             $first_access=&get_first_access($interval[1],undef,$item);
                   9058:                         } else {
                   9059:                             $first_access=&get_first_access($interval[1]);
                   9060:                         }
                   9061:                         if ($first_access) {
1.1172.2.146.  .1(raebu 9062:22):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  9063:                             if ($timesup > $now) {
                   9064:                                 my $activeblock;
1.1172.2.142  raeburn  9065:                                 if ($type eq 'resource') {
                   9066:                                     if (ref($navmap)) {
                   9067:                                         my $res = $navmap->getBySymb($item);
                   9068:                                         if ($res->answerable()) {
                   9069:                                             $activeblock = 1;
                   9070:                                         }
                   9071:                                     }
                   9072:                                 } elsif ($type eq 'map') {
                   9073:                                     my $mapsymb = &symbread($mapname,1);
                   9074:                                     if (($mapsymb) && (ref($navmap))) {
                   9075:                                         my $mapres = $navmap->getBySymb($mapsymb);
                   9076:                                         if (ref($mapres)) {
                   9077:                                             my $first = $mapres->map_start();
                   9078:                                             my $finish = $mapres->map_finish();
                   9079:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   9080:                                             if (ref($it)) {
                   9081:                                                 my $res;
                   9082:                                                 while ($res = $it->next(undef,1)) {
                   9083:                                                     next unless (ref($res));
                   9084:                                                     my $symb = $res->symb();
                   9085:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
                   9086:                                                     @interval=&EXT("resource.0.interval",$symb);
                   9087:                                                     if ($interval[1] eq 'map') {
                   9088:                                                         if ($res->answerable()) {
                   9089:                                                             $activeblock = 1;
                   9090:                                                             last;
                   9091:                                                         }
                   9092:                                                     }
                   9093:                                                 }
                   9094:                                             }
                   9095:                                         }
1.1172.2.66  raeburn  9096:                                     }
                   9097:                                 }
                   9098:                                 if ($activeblock) {
                   9099:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   9100:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   9101:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   9102:                                          }
                   9103:                                     }
                   9104:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   9105:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   9106:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  9107:                                         }
1.1162    raeburn  9108:                                     }
                   9109:                                 }
                   9110:                             }
                   9111:                         }
                   9112:                     }
                   9113:                 }
                   9114:             }
                   9115:         }
                   9116:     }
1.1172.2.66  raeburn  9117:     return %blockers;
1.1162    raeburn  9118: }
                   9119: 
1.1172.2.66  raeburn  9120: sub has_comm_blocking {
1.1172.2.128  raeburn  9121:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  9122:     my @blockers;
                   9123:     return unless ($env{'request.course.id'});
                   9124:     return unless ($priv eq 'bre');
                   9125:     return if ($env{'request.state'} eq 'construct');
1.1172.2.142  raeburn  9126:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   9127:     if ($env{'request.course.sec'}) {
                   9128:         $courseurl .= '/'.$env{'request.course.sec'};
                   9129:     }
                   9130:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128  raeburn  9131:     my %blockinfo;
                   9132:     if (ref($blocks) eq 'HASH') {
                   9133:         %blockinfo = &get_commblock_resources($blocks);
                   9134:     } else {
                   9135:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   9136:         %blockinfo = %cachedblockers;
                   9137:     }
                   9138:     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  9139:     my (%possibles,@symbs);
                   9140:     if (!$symb) {
1.1172.2.128  raeburn  9141:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  9142:     }
1.1172.2.66  raeburn  9143:     if ($symb) {
                   9144:         @symbs = ($symb);
                   9145:     } elsif (keys(%possibles)) {
                   9146:         @symbs = keys(%possibles);
                   9147:     }
                   9148:     my $noblock;
                   9149:     foreach my $symb (@symbs) {
                   9150:         last if ($noblock);
                   9151:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128  raeburn  9152:         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  9153:             if ($block =~ /^firstaccess____(.+)$/) {
                   9154:                 my $item = $1;
1.1172.2.126  raeburn  9155:                 unless ($blocked) {
                   9156:                     if (($item eq $map) || ($item eq $symb)) {
                   9157:                         $noblock = 1;
                   9158:                         last;
                   9159:                     }
1.1172.2.66  raeburn  9160:                 }
1.1162    raeburn  9161:             }
1.1172.2.128  raeburn  9162:             if (ref($blockinfo{$block}) eq 'HASH') {
                   9163:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   9164:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  9165:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9166:                             push(@blockers,$block);
                   9167:                         }
                   9168:                     }
                   9169:                 }
1.1172.2.128  raeburn  9170:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   9171:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126  raeburn  9172:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9173:                             push(@blockers,$block);
                   9174:                         }
1.1172.2.66  raeburn  9175:                     }
                   9176:                 }
1.1162    raeburn  9177:             }
                   9178:         }
                   9179:     }
1.1172.2.126  raeburn  9180:     unless ($noblock) {
                   9181:         return @blockers;
                   9182:     }
                   9183:     return;
1.1172.2.66  raeburn  9184: }
1.1162    raeburn  9185: }
                   9186: 
1.1172.2.146.  .1(raebu 9187:22): sub deeplink_check {
                   9188:22):     my ($priv,$symb,$uri) = @_;
                   9189:22):     return unless ($env{'request.course.id'});
                   9190:22):     return unless ($priv eq 'bre');
                   9191:22):     return if ($env{'request.state'} eq 'construct');
                   9192:22):     return if ($env{'request.role.adv'});
                   9193:22):     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9194:22):     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9195:22):     my (%possibles,@symbs);
                   9196:22):     if (!$symb) {
                   9197:22):         $symb = &symbread($uri,1,1,1,\%possibles);
                   9198:22):     }
                   9199:22):     if ($symb) {
                   9200:22):         @symbs = ($symb);
                   9201:22):     } elsif (keys(%possibles)) {
                   9202:22):         @symbs = keys(%possibles);
                   9203:22):     }
                   9204:22): 
                   9205:22):     my ($deeplink_symb,$allow);
                   9206:22):     if ($env{'request.deeplink.login'}) {
                   9207:22):         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
                   9208:22):     }
                   9209:22):     foreach my $symb (@symbs) {
                   9210:22):         last if ($allow);
                   9211:22):         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   9212:22):         if ($deeplink eq '') {
                   9213:22):             $allow = 1;
                   9214:22):         } else {
                   9215:22):             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
                   9216:22):             if ($state ne 'only') {
                   9217:22):                 $allow = 1;
                   9218:22):             } else {
                   9219:22):                 my $check_deeplink_entry;
                   9220:22):                 if ($protect ne 'none') {
                   9221:22):                     my ($acctype,$item) = split(/:/,$protect);
                   9222:22):                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
                   9223:22):                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
                   9224:22):                             $check_deeplink_entry = 1
                   9225:22):                         }
                   9226:22):                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
                   9227:22):                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
                   9228:22):                             $check_deeplink_entry = 1;
                   9229:22):                         }
                   9230:22):                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   9231:22):                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   9232:22):                             $check_deeplink_entry = 1;
                   9233:22):                         }
                   9234:22):                     }
                   9235:22):                 }
                   9236:22):                 if (($protect eq 'none') || ($check_deeplink_entry)) {
                   9237:22):                     if ($scope eq 'res') {
                   9238:22):                         if ($symb eq $deeplink_symb) {
                   9239:22):                             $allow = 1;
                   9240:22):                         }
                   9241:22):                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
                   9242:22):                         my ($map_from_symb,$map_from_login);
                   9243:22):                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
                   9244:22):                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9245:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
                   9246:22):                         } else {
                   9247:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
                   9248:22):                         }
                   9249:22):                         if (($map_from_symb) && ($map_from_login)) {
                   9250:22):                             if ($map_from_symb eq $map_from_login) {
                   9251:22):                                 $allow = 1;
                   9252:22):                             } elsif ($scope eq 'rec') {
                   9253:22):                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
                   9254:22):                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
                   9255:22):                                     $allow = 1;
                   9256:22):                                 }
                   9257:22):                             }
                   9258:22):                         }
                   9259:22):                     }
                   9260:22):                 }
                   9261:22):             }
                   9262:22):         }
                   9263:22):     }
                   9264:22):     return if ($allow);
                   9265:22):     return 1;
                   9266:22): }
                   9267:22): 
1.1172.2.66  raeburn  9268: # -------------------------------- Deversion and split uri into path an filename
                   9269: 
1.1133    foxr     9270: #
1.1172.2.66  raeburn  9271: #   Removes the version from a URI and
1.1133    foxr     9272: #   splits it in to its filename and path to the filename.
                   9273: #   Seems like File::Basename could have done this more clearly.
                   9274: #   Parameters:
                   9275: #      $uri   - input URI
                   9276: #   Returns:
                   9277: #     Two element list consisting of 
                   9278: #     $pathname  - the URI up to and excluding the trailing /
                   9279: #     $filename  - The part of the URI following the last /
                   9280: #  NOTE:
                   9281: #    Another realization of this is simply:
                   9282: #    use File::Basename;
                   9283: #    ...
                   9284: #    $uri = shift;
                   9285: #    $filename = basename($uri);
                   9286: #    $path     = dirname($uri);
                   9287: #    return ($filename, $path);
                   9288: #
                   9289: #     The implementation below is probably faster however.
                   9290: #
1.710     albertel 9291: sub split_uri_for_cond {
                   9292:     my $uri=&deversion(&declutter(shift));
                   9293:     my @uriparts=split(/\//,$uri);
                   9294:     my $filename=pop(@uriparts);
                   9295:     my $pathname=join('/',@uriparts);
                   9296:     return ($pathname,$filename);
                   9297: }
1.232     www      9298: # --------------------------------------------------- Is a resource on the map?
                   9299: 
                   9300: sub is_on_map {
1.710     albertel 9301:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 9302:     #Trying to find the conditional for the file
1.620     albertel 9303:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 9304: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      9305:     if ($match) {
1.289     bowersj2 9306: 	return (1,$1);
                   9307:     } else {
1.434     www      9308: 	return (0,0);
1.289     bowersj2 9309:     }
1.12      www      9310: }
                   9311: 
1.427     www      9312: # --------------------------------------------------------- Get symb from alias
                   9313: 
                   9314: sub get_symb_from_alias {
                   9315:     my $symb=shift;
                   9316:     my ($map,$resid,$url)=&decode_symb($symb);
                   9317: # Already is a symb
                   9318:     if ($url) { return $symb; }
                   9319: # Must be an alias
                   9320:     my $aliassymb='';
                   9321:     my %bighash;
1.620     albertel 9322:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      9323:                             &GDBM_READER(),0640)) {
                   9324:         my $rid=$bighash{'mapalias_'.$symb};
                   9325: 	if ($rid) {
                   9326: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 9327: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   9328: 				    $resid,$bighash{'src_'.$rid});
1.427     www      9329: 	}
                   9330:         untie %bighash;
                   9331:     }
                   9332:     return $aliassymb;
                   9333: }
                   9334: 
1.12      www      9335: # ----------------------------------------------------------------- Define Role
                   9336: 
                   9337: sub definerole {
                   9338:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  9339:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9340:     foreach my $role (split(':',$sysrole)) {
                   9341: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9342:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9343:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9344: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9345:                return "refused:s:$crole&$cqual"; 
                   9346:             }
                   9347:         }
1.191     harris41 9348:     }
1.800     albertel 9349:     foreach my $role (split(':',$domrole)) {
                   9350: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9351:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9352:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9353: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9354:                return "refused:d:$crole&$cqual"; 
                   9355:             }
                   9356:         }
1.191     harris41 9357:     }
1.800     albertel 9358:     foreach my $role (split(':',$courole)) {
                   9359: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9360:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9361:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9362: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9363:                return "refused:c:$crole&$cqual"; 
                   9364:             }
                   9365:         }
1.191     harris41 9366:     }
1.1172.2.84  raeburn  9367:     my $uhome;
                   9368:     if (($uname ne '') && ($udom ne '')) {
                   9369:         $uhome = &homeserver($uname,$udom);
                   9370:         return $uhome if ($uhome eq 'no_host');
                   9371:     } else {
                   9372:         $uname = $env{'user.name'};
                   9373:         $udom = $env{'user.domain'};
                   9374:         $uhome = $env{'user.home'};
                   9375:     }
1.620     albertel 9376:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  9377:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9378:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  9379:     return reply($command,$uhome);
1.12      www      9380:   } else {
                   9381:     return 'refused';
                   9382:   }
1.105     harris41 9383: }
                   9384: 
                   9385: # ---------------- Make a metadata query against the network of library servers
                   9386: 
                   9387: sub metadata_query {
1.1172.2.33  raeburn  9388:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9389:     my %rhash;
1.845     albertel 9390:     my %libserv = &all_library();
1.244     matthew  9391:     my @server_list = (defined($server_array) ? @$server_array
                   9392:                                               : keys(%libserv) );
                   9393:     for my $server (@server_list) {
1.1172.2.33  raeburn  9394:         my $domains = '';
                   9395:         if (ref($domains_hash) eq 'HASH') {
                   9396:             $domains = $domains_hash->{$server};    
                   9397:         }
1.118     harris41 9398: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  9399: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9400: 	    $rhash{$server}=$reply;
                   9401: 	}
                   9402: 	else {
                   9403: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  9404: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9405: 			     $server);
                   9406: 	    $rhash{$server}=$reply;
                   9407: 	}
1.112     harris41 9408:     }
1.118     harris41 9409:     return \%rhash;
1.240     www      9410: }
                   9411: 
                   9412: # ----------------------------------------- Send log queries and wait for reply
                   9413: 
                   9414: sub log_query {
                   9415:     my ($uname,$udom,$query,%filters)=@_;
                   9416:     my $uhome=&homeserver($uname,$udom);
                   9417:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9418:     my $uhost=&hostname($uhome);
1.800     albertel 9419:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9420:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9421:                        $uhome);
1.479     albertel 9422:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9423:     return get_query_reply($queryid);
                   9424: }
                   9425: 
1.818     raeburn  9426: # -------------------------- Update MySQL table for portfolio file
                   9427: 
                   9428: sub update_portfolio_table {
1.821     raeburn  9429:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9430:     if ($group ne '') {
                   9431:         $file_name =~s /^\Q$group\E//;
                   9432:     }
1.818     raeburn  9433:     my $homeserver = &homeserver($uname,$udom);
                   9434:     my $queryid=
1.821     raeburn  9435:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9436:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9437:     my $reply = &get_query_reply($queryid);
                   9438:     return $reply;
                   9439: }
                   9440: 
1.899     raeburn  9441: # -------------------------- Update MySQL allusers table
                   9442: 
                   9443: sub update_allusers_table {
                   9444:     my ($uname,$udom,$names) = @_;
                   9445:     my $homeserver = &homeserver($uname,$udom);
                   9446:     my $queryid=
                   9447:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9448:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9449:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9450:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9451:                'generation='.&escape($names->{'generation'}).'%%'.
                   9452:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9453:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9454:     return;
1.899     raeburn  9455: }
                   9456: 
1.508     raeburn  9457: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9458: 
                   9459: sub fetch_enrollment_query {
1.511     raeburn  9460:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  9461:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9462:     my $maxtries = 1;
1.508     raeburn  9463:     if ($context eq 'automated') {
                   9464:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  9465:         $sleep = 2;
                   9466:         $loopmax = 100;
1.547     raeburn  9467:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9468:     } else {
                   9469:         $homeserver = &homeserver($cnum,$dom);
                   9470:     }
1.838     albertel 9471:     my $host=&hostname($homeserver);
1.506     raeburn  9472:     my $cmd = '';
1.1000    raeburn  9473:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9474:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9475:     }
                   9476:     $cmd =~ s/%%$//;
                   9477:     $cmd = &escape($cmd);
                   9478:     my $query = 'fetchenrollment';
1.620     albertel 9479:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9480:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9481:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9482:         return 'error: '.$queryid;
                   9483:     }
1.1172.2.93  raeburn  9484:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9485:     my $tries = 1;
                   9486:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  9487:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9488:         $tries ++;
                   9489:     }
1.526     raeburn  9490:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9491:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9492:     } else {
1.901     albertel 9493:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  9494:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9495:             foreach my $line (@responses) {
                   9496:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9497:                 $$replyref{$key} = $value;
                   9498:             }
                   9499:         } else {
1.1117    foxr     9500:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9501:             foreach my $line (@responses) {
                   9502:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9503:                 $$replyref{$key} = $value;
                   9504:                 if ($value > 0) {
1.800     albertel 9505:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9506:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9507:                         my $destname = $pathname.'/'.$filename;
                   9508:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9509:                         if ($xml_classlist =~ /^error/) {
                   9510:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9511:                         } else {
1.1172.2.96  raeburn  9512:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9513:                                 print FILE &unescape($xml_classlist);
                   9514:                                 close(FILE);
1.526     raeburn  9515:                             } else {
                   9516:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9517:                             }
                   9518:                         }
                   9519:                     }
                   9520:                 }
                   9521:             }
                   9522:         }
                   9523:         return 'ok';
                   9524:     }
                   9525:     return 'error';
                   9526: }
                   9527: 
1.242     www      9528: sub get_query_reply {
1.1172.2.79  raeburn  9529:     my ($queryid,$sleep,$loopmax) = @_;
                   9530:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9531:         $sleep = 0.2;
                   9532:     }
                   9533:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9534:         $loopmax = 100;
                   9535:     }
1.1117    foxr     9536:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9537:     my $reply='';
1.1172.2.79  raeburn  9538:     for (1..$loopmax) {
                   9539: 	sleep($sleep);
1.240     www      9540:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  9541: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9542: 		$reply = join('',<$fh>);
                   9543: 		close($fh);
1.240     www      9544: 	   } else { return 'error: reply_file_error'; }
1.242     www      9545:            return &unescape($reply);
                   9546: 	}
1.240     www      9547:     }
1.242     www      9548:     return 'timeout:'.$queryid;
1.240     www      9549: }
                   9550: 
                   9551: sub courselog_query {
1.241     www      9552: #
                   9553: # possible filters:
                   9554: # url: url or symb
                   9555: # username
                   9556: # domain
                   9557: # action: view, submit, grade
                   9558: # start: timestamp
                   9559: # end: timestamp
                   9560: #
1.240     www      9561:     my (%filters)=@_;
1.620     albertel 9562:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9563:     if ($filters{'url'}) {
                   9564: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9565:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9566:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9567:     }
1.620     albertel 9568:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9569:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9570:     return &log_query($cname,$cdom,'courselog',%filters);
                   9571: }
                   9572: 
                   9573: sub userlog_query {
1.858     raeburn  9574: #
                   9575: # possible filters:
                   9576: # action: log check role
                   9577: # start: timestamp
                   9578: # end: timestamp
                   9579: #
1.240     www      9580:     my ($uname,$udom,%filters)=@_;
                   9581:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9582: }
                   9583: 
1.506     raeburn  9584: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9585: 
                   9586: sub auto_run {
1.508     raeburn  9587:     my ($cnum,$cdom) = @_;
1.876     raeburn  9588:     my $response = 0;
                   9589:     my $settings;
                   9590:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9591:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9592:         $settings = $domconfig{'autoenroll'};
                   9593:         if ($settings->{'run'} eq '1') {
                   9594:             $response = 1;
                   9595:         }
                   9596:     } else {
1.934     raeburn  9597:         my $homeserver;
                   9598:         if (&is_course($cdom,$cnum)) {
                   9599:             $homeserver = &homeserver($cnum,$cdom);
                   9600:         } else {
                   9601:             $homeserver = &domain($cdom,'primary');
                   9602:         }
                   9603:         if ($homeserver ne 'no_host') {
                   9604:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9605:         }
1.876     raeburn  9606:     }
1.506     raeburn  9607:     return $response;
                   9608: }
1.776     albertel 9609: 
1.506     raeburn  9610: sub auto_get_sections {
1.508     raeburn  9611:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9612:     my $homeserver;
                   9613:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9614:         $homeserver = &homeserver($cnum,$cdom);
                   9615:     }
                   9616:     if (!defined($homeserver)) { 
                   9617:         if ($cdom =~ /^$match_domain$/) {
                   9618:             $homeserver = &domain($cdom,'primary');
                   9619:         }
                   9620:     }
                   9621:     my @secs;
                   9622:     if (defined($homeserver)) {
                   9623:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9624:         unless ($response eq 'refused') {
                   9625:             @secs = split(/:/,$response);
                   9626:         }
1.506     raeburn  9627:     }
                   9628:     return @secs;
                   9629: }
1.776     albertel 9630: 
1.506     raeburn  9631: sub auto_new_course {
1.1099    raeburn  9632:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9633:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9634:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9635:     return $response;
                   9636: }
1.776     albertel 9637: 
1.506     raeburn  9638: sub auto_validate_courseID {
1.508     raeburn  9639:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9640:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9641:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9642:     return $response;
                   9643: }
1.776     albertel 9644: 
1.1007    raeburn  9645: sub auto_validate_instcode {
1.1020    raeburn  9646:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9647:     my ($homeserver,$response);
                   9648:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9649:         $homeserver = &homeserver($cnum,$cdom);
                   9650:     }
                   9651:     if (!defined($homeserver)) {
                   9652:         if ($cdom =~ /^$match_domain$/) {
                   9653:             $homeserver = &domain($cdom,'primary');
                   9654:         }
                   9655:     }
1.1065    raeburn  9656:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9657:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9658:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9659:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9660: }
                   9661: 
1.1172.2.141  raeburn  9662: sub auto_validate_inst_crosslist {
                   9663:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   9664:     my ($homeserver,$response);
                   9665:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9666:         $homeserver = &homeserver($cnum,$cdom);
                   9667:     }
                   9668:     if (!defined($homeserver)) {
                   9669:         if ($cdom =~ /^$match_domain$/) {
                   9670:             $homeserver = &domain($cdom,'primary');
                   9671:         }
                   9672:     }
                   9673:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   9674:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   9675:                          &escape($instcode).':'.&escape($inst_xlist).':'.
                   9676:                          &escape($coowner),$homeserver);
                   9677:     }
                   9678:     return $response;
                   9679: }
                   9680: 
1.506     raeburn  9681: sub auto_create_password {
1.873     raeburn  9682:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9683:     my ($homeserver,$response);
1.506     raeburn  9684:     my $create_passwd = 0;
                   9685:     my $authchk = '';
1.873     raeburn  9686:     if ($udom =~ /^$match_domain$/) {
                   9687:         $homeserver = &domain($udom,'primary');
                   9688:     }
                   9689:     if ($homeserver eq '') {
                   9690:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9691:             $homeserver = &homeserver($cnum,$cdom);
                   9692:         }
                   9693:     }
                   9694:     if ($homeserver eq '') {
                   9695:         $authchk = 'nodomain';
1.506     raeburn  9696:     } else {
1.873     raeburn  9697:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9698:         if ($response eq 'refused') {
                   9699:             $authchk = 'refused';
                   9700:         } else {
1.901     albertel 9701:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9702:         }
1.506     raeburn  9703:     }
                   9704:     return ($authparam,$create_passwd,$authchk);
                   9705: }
                   9706: 
1.706     raeburn  9707: sub auto_photo_permission {
                   9708:     my ($cnum,$cdom,$students) = @_;
                   9709:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9710:     my ($outcome,$perm_reqd,$conditions) = 
                   9711: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9712:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9713: 	return (undef,undef);
                   9714:     }
1.706     raeburn  9715:     return ($outcome,$perm_reqd,$conditions);
                   9716: }
                   9717: 
                   9718: sub auto_checkphotos {
                   9719:     my ($uname,$udom,$pid) = @_;
                   9720:     my $homeserver = &homeserver($uname,$udom);
                   9721:     my ($result,$resulttype);
                   9722:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9723: 				   &escape($uname).':'.&escape($pid),
                   9724: 				   $homeserver));
1.709     albertel 9725:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9726: 	return (undef,undef);
                   9727:     }
1.706     raeburn  9728:     if ($outcome) {
                   9729:         ($result,$resulttype) = split(/:/,$outcome);
                   9730:     } 
                   9731:     return ($result,$resulttype);
                   9732: }
                   9733: 
                   9734: sub auto_photochoice {
                   9735:     my ($cnum,$cdom) = @_;
                   9736:     my $homeserver = &homeserver($cnum,$cdom);
                   9737:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9738: 						       &escape($cdom),
                   9739: 						       $homeserver)));
1.709     albertel 9740:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9741: 	return (undef,undef);
                   9742:     }
1.706     raeburn  9743:     return ($update,$comment);
                   9744: }
                   9745: 
                   9746: sub auto_photoupdate {
                   9747:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9748:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9749:     my $host=&hostname($homeserver);
1.706     raeburn  9750:     my $cmd = '';
                   9751:     my $maxtries = 1;
1.800     albertel 9752:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9753:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9754:     }
                   9755:     $cmd =~ s/%%$//;
                   9756:     $cmd = &escape($cmd);
                   9757:     my $query = 'institutionalphotos';
                   9758:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9759:     unless ($queryid=~/^\Q$host\E\_/) {
                   9760:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9761:         return 'error: '.$queryid;
                   9762:     }
                   9763:     my $reply = &get_query_reply($queryid);
                   9764:     my $tries = 1;
                   9765:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9766:         $reply = &get_query_reply($queryid);
                   9767:         $tries ++;
                   9768:     }
                   9769:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9770:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9771:     } else {
                   9772:         my @responses = split(/:/,$reply);
                   9773:         my $outcome = shift(@responses); 
                   9774:         foreach my $item (@responses) {
                   9775:             my ($key,$value) = split(/=/,$item);
                   9776:             $$photo{$key} = $value;
                   9777:         }
                   9778:         return $outcome;
                   9779:     }
                   9780:     return 'error';
                   9781: }
                   9782: 
1.521     raeburn  9783: sub auto_instcode_format {
1.793     albertel 9784:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9785: 	$cat_order) = @_;
1.521     raeburn  9786:     my $courses = '';
1.772     raeburn  9787:     my @homeservers;
1.521     raeburn  9788:     if ($caller eq 'global') {
1.841     albertel 9789: 	my %servers = &get_servers($codedom,'library');
                   9790: 	foreach my $tryserver (keys(%servers)) {
                   9791: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9792: 		push(@homeservers,$tryserver);
                   9793: 	    }
1.584     raeburn  9794:         }
1.1022    raeburn  9795:     } elsif ($caller eq 'requests') {
                   9796:         if ($codedom =~ /^$match_domain$/) {
                   9797:             my $chome = &domain($codedom,'primary');
                   9798:             unless ($chome eq 'no_host') {
                   9799:                 push(@homeservers,$chome);
                   9800:             }
                   9801:         }
1.521     raeburn  9802:     } else {
1.772     raeburn  9803:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9804:     }
1.793     albertel 9805:     foreach my $code (keys(%{$instcodes})) {
                   9806:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9807:     }
                   9808:     chop($courses);
1.772     raeburn  9809:     my $ok_response = 0;
                   9810:     my $response;
                   9811:     while (@homeservers > 0 && $ok_response == 0) {
                   9812:         my $server = shift(@homeservers); 
                   9813:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9814:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9815:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9816: 		split(/:/,$response);
1.772     raeburn  9817:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9818:             push(@{$codetitles},&str2array($codetitles_str));
                   9819:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9820:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9821:             $ok_response = 1;
                   9822:         }
                   9823:     }
                   9824:     if ($ok_response) {
1.521     raeburn  9825:         return 'ok';
1.772     raeburn  9826:     } else {
                   9827:         return $response;
1.521     raeburn  9828:     }
                   9829: }
                   9830: 
1.792     raeburn  9831: sub auto_instcode_defaults {
                   9832:     my ($domain,$returnhash,$code_order) = @_;
                   9833:     my @homeservers;
1.841     albertel 9834: 
                   9835:     my %servers = &get_servers($domain,'library');
                   9836:     foreach my $tryserver (keys(%servers)) {
                   9837: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9838: 	    push(@homeservers,$tryserver);
                   9839: 	}
1.792     raeburn  9840:     }
1.841     albertel 9841: 
1.792     raeburn  9842:     my $response;
1.841     albertel 9843:     foreach my $server (@homeservers) {
1.792     raeburn  9844:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9845:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9846: 	
                   9847: 	foreach my $pair (split(/\&/,$response)) {
                   9848: 	    my ($name,$value)=split(/\=/,$pair);
                   9849: 	    if ($name eq 'code_order') {
                   9850: 		@{$code_order} = split(/\&/,&unescape($value));
                   9851: 	    } else {
                   9852: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9853: 	    }
                   9854: 	}
                   9855: 	return 'ok';
1.792     raeburn  9856:     }
1.841     albertel 9857: 
                   9858:     return $response;
1.1003    raeburn  9859: }
                   9860: 
                   9861: sub auto_possible_instcodes {
1.1007    raeburn  9862:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9863:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9864:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9865:         return;
                   9866:     }
1.1003    raeburn  9867:     my (@homeservers,$uhome);
                   9868:     if (defined(&domain($domain,'primary'))) {
                   9869:         $uhome=&domain($domain,'primary');
                   9870:         push(@homeservers,&domain($domain,'primary'));
                   9871:     } else {
                   9872:         my %servers = &get_servers($domain,'library');
                   9873:         foreach my $tryserver (keys(%servers)) {
                   9874:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9875:                 push(@homeservers,$tryserver);
                   9876:             }
                   9877:         }
                   9878:     }
                   9879:     my $response;
                   9880:     foreach my $server (@homeservers) {
                   9881:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9882:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9883:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9884:             split(':',$response);
                   9885:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9886:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9887:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9888:             my ($name,$value)=split('=',$item);
                   9889:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9890:         }
                   9891:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9892:             my ($name,$value)=split('=',$item);
                   9893:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9894:         }
                   9895:         return 'ok';
                   9896:     }
                   9897:     return $response;
                   9898: }
1.792     raeburn  9899: 
1.1010    raeburn  9900: sub auto_courserequest_checks {
                   9901:     my ($dom) = @_;
1.1020    raeburn  9902:     my ($homeserver,%validations);
                   9903:     if ($dom =~ /^$match_domain$/) {
                   9904:         $homeserver = &domain($dom,'primary');
                   9905:     }
                   9906:     unless ($homeserver eq 'no_host') {
                   9907:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9908:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9909:             my @items = split(/&/,$response);
                   9910:             foreach my $item (@items) {
                   9911:                 my ($key,$value) = split('=',$item);
                   9912:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9913:             }
                   9914:         }
                   9915:     }
1.1010    raeburn  9916:     return %validations; 
                   9917: }
                   9918: 
1.1020    raeburn  9919: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9920:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9921:     my ($homeserver,$response);
                   9922:     if ($dom =~ /^$match_domain$/) {
                   9923:         $homeserver = &domain($dom,'primary');
                   9924:     }
1.1172.2.43  raeburn  9925:     unless ($homeserver eq 'no_host') {
                   9926:         my $customdata;
                   9927:         if (ref($custominfo) eq 'HASH') {
                   9928:             $customdata = &freeze_escape($custominfo);
                   9929:         }
1.1020    raeburn  9930:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9931:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9932:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9933:                                     $customdata,$homeserver));
1.1020    raeburn  9934:     }
                   9935:     return $response;
                   9936: }
                   9937: 
1.777     albertel 9938: sub auto_validate_class_sec {
1.918     raeburn  9939:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9940:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9941:     my $ownerlist;
                   9942:     if (ref($owners) eq 'ARRAY') {
                   9943:         $ownerlist = join(',',@{$owners});
                   9944:     } else {
                   9945:         $ownerlist = $owners;
                   9946:     }
1.773     raeburn  9947:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9948:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9949:     return $response;
                   9950: }
                   9951: 
1.1172.2.141  raeburn  9952: sub auto_instsec_reformat {
                   9953:     my ($cdom,$action,$instsecref) = @_;
                   9954:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   9955:     my @homeservers;
                   9956:     if (defined(&domain($cdom,'primary'))) {
                   9957:         push(@homeservers,&domain($cdom,'primary'));
                   9958:     } else {
                   9959:         my %servers = &get_servers($cdom,'library');
                   9960:         foreach my $tryserver (keys(%servers)) {
                   9961:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9962:                 push(@homeservers,$tryserver);
                   9963:             }
                   9964:         }
                   9965:     }
                   9966:     my $response;
                   9967:     my %reformatted = %{$instsecref};
                   9968:     foreach my $server (@homeservers) {
                   9969:         if (ref($instsecref) eq 'HASH') {
                   9970:             my $info = &freeze_escape($instsecref);
                   9971:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   9972:                                 $action.':'.$info,$server);
                   9973:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   9974:             my @items = split(/&/,$response);
                   9975:             foreach my $item (@items) {
                   9976:                 my ($key,$value) = split(/=/,$item);
                   9977:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   9978:             }
                   9979:         }
                   9980:     }
                   9981:     return %reformatted;
                   9982: }
                   9983: 
1.1172.2.94  raeburn  9984: sub auto_validate_instclasses {
                   9985:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9986:     my ($homeserver,%validations);
                   9987:     $homeserver = &homeserver($cnum,$cdom);
                   9988:     unless ($homeserver eq 'no_host') {
                   9989:         my $ownerlist;
                   9990:         if (ref($owners) eq 'ARRAY') {
                   9991:             $ownerlist = join(',',@{$owners});
                   9992:         } else {
                   9993:             $ownerlist = $owners;
                   9994:         }
                   9995:         if (ref($classesref) eq 'HASH') {
                   9996:             my $classes = &freeze_escape($classesref);
                   9997:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9998:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9999:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   10000:                 my @items = split(/&/,$response);
                   10001:                 foreach my $item (@items) {
                   10002:                     my ($key,$value) = split('=',$item);
                   10003:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   10004:                 }
                   10005:             }
                   10006:         }
                   10007:     }
                   10008:     return %validations;
                   10009: }
                   10010: 
1.1172.2.38  raeburn  10011: sub auto_crsreq_update {
                   10012:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  10013:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  10014:     my ($homeserver,%crsreqresponse);
                   10015:     if ($cdom =~ /^$match_domain$/) {
                   10016:         $homeserver = &domain($cdom,'primary');
                   10017:     }
                   10018:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   10019:         my $info;
                   10020:         if (ref($inbound) eq 'HASH') {
                   10021:             $info = &freeze_escape($inbound);
                   10022:         }
                   10023:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   10024:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   10025:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  10026:                             &escape($title).':'.&escape($code).':'.
                   10027:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  10028:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   10029:             my @items = split(/&/,$response);
                   10030:             foreach my $item (@items) {
                   10031:                 my ($key,$value) = split('=',$item);
                   10032:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   10033:             }
                   10034:         }
                   10035:     }
                   10036:     return \%crsreqresponse;
                   10037: }
                   10038: 
1.1172.2.78  raeburn  10039: sub auto_export_grades {
                   10040:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   10041:     my ($homeserver,%exportresponse);
                   10042:     if ($cdom =~ /^$match_domain$/) {
                   10043:         $homeserver = &domain($cdom,'primary');
                   10044:     }
                   10045:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   10046:         my $info;
                   10047:         if (ref($inforef) eq 'HASH') {
                   10048:             $info = &freeze_escape($inforef);
                   10049:         }
                   10050:         if (ref($gradesref) eq 'HASH') {
                   10051:             my $grades = &freeze_escape($gradesref);
                   10052:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   10053:                                 $info.':'.$grades,$homeserver);
                   10054:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   10055:                 my @items = split(/&/,$response);
                   10056:                 foreach my $item (@items) {
                   10057:                     my ($key,$value) = split('=',$item);
                   10058:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   10059:                 }
                   10060:             }
                   10061:         }
                   10062:     }
                   10063:     return \%exportresponse;
                   10064: }
                   10065: 
1.1172.2.68  raeburn  10066: sub check_instcode_cloning {
                   10067:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   10068:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   10069:         return;
                   10070:     }
                   10071:     my $canclone;
                   10072:     if (@{$code_order} > 0) {
                   10073:         my $instcoderegexp ='^';
                   10074:         my @clonecodes = split(/\&/,$cloner);
                   10075:         foreach my $item (@{$code_order}) {
                   10076:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   10077:                 foreach my $pair (@clonecodes) {
                   10078:                     my ($key,$val) = split(/\=/,$pair,2);
                   10079:                     $val = &unescape($val);
                   10080:                     if ($key eq $item) {
                   10081:                         $instcoderegexp .= '('.$val.')';
                   10082:                         last;
                   10083:                     }
                   10084:                 }
                   10085:             } else {
                   10086:                 $instcoderegexp .= $codedefaults->{$item};
                   10087:             }
                   10088:         }
                   10089:         $instcoderegexp .= '$';
                   10090:         my (@from,@to);
                   10091:         eval {
                   10092:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10093:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10094:         };
                   10095:         if ((@from > 0) && (@to > 0)) {
                   10096:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10097:             if (!@diffs) {
                   10098:                 $canclone = 1;
                   10099:             }
                   10100:         }
                   10101:     }
                   10102:     return $canclone;
                   10103: }
                   10104: 
                   10105: sub default_instcode_cloning {
                   10106:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   10107:     my (%codedefaults,@code_order,$canclone);
                   10108:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   10109:         %codedefaults = %{$codedefaultsref};
                   10110:         @code_order = @{$codeorderref};
                   10111:     } elsif ($clonedom) {
                   10112:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   10113:     }
                   10114:     if (($domdefclone) && (@code_order)) {
                   10115:         my @clonecodes = split(/\+/,$domdefclone);
                   10116:         my $instcoderegexp ='^';
                   10117:         foreach my $item (@code_order) {
                   10118:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   10119:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   10120:             } else {
                   10121:                 $instcoderegexp .= $codedefaults{$item};
                   10122:             }
                   10123:         }
                   10124:         $instcoderegexp .= '$';
                   10125:         my (@from,@to);
                   10126:         eval {
                   10127:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10128:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10129:         };
                   10130:         if ((@from > 0) && (@to > 0)) {
                   10131:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10132:             if (!@diffs) {
                   10133:                 $canclone = 1;
                   10134:             }
                   10135:         }
                   10136:     }
                   10137:     return $canclone;
                   10138: }
                   10139: 
1.679     raeburn  10140: # ------------------------------------------------------- Course Group routines
                   10141: 
                   10142: sub get_coursegroups {
1.809     raeburn  10143:     my ($cdom,$cnum,$group,$namespace) = @_;
                   10144:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  10145: }
                   10146: 
1.679     raeburn  10147: sub modify_coursegroup {
                   10148:     my ($cdom,$cnum,$groupsettings) = @_;
                   10149:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   10150: }
                   10151: 
1.809     raeburn  10152: sub toggle_coursegroup_status {
                   10153:     my ($cdom,$cnum,$group,$action) = @_;
                   10154:     my ($from_namespace,$to_namespace);
                   10155:     if ($action eq 'delete') {
                   10156:         $from_namespace = 'coursegroups';
                   10157:         $to_namespace = 'deleted_groups';
                   10158:     } else {
                   10159:         $from_namespace = 'deleted_groups';
                   10160:         $to_namespace = 'coursegroups';
                   10161:     }
                   10162:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  10163:     if (my $tmp = &error(%curr_group)) {
                   10164:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   10165:         return ('read error',$tmp);
                   10166:     } else {
                   10167:         my %savedsettings = %curr_group; 
1.809     raeburn  10168:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  10169:         my $deloutcome;
                   10170:         if ($result eq 'ok') {
1.809     raeburn  10171:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  10172:         } else {
                   10173:             return ('write error',$result);
                   10174:         }
                   10175:         if ($deloutcome eq 'ok') {
                   10176:             return 'ok';
                   10177:         } else {
                   10178:             return ('delete error',$deloutcome);
                   10179:         }
                   10180:     }
                   10181: }
                   10182: 
1.679     raeburn  10183: sub modify_group_roles {
1.957     raeburn  10184:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  10185:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   10186:     my $role = 'gr/'.&escape($userprivs);
                   10187:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  10188:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  10189:     if ($result eq 'ok') {
                   10190:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   10191:     }
1.679     raeburn  10192:     return $result;
                   10193: }
                   10194: 
                   10195: sub modify_coursegroup_membership {
                   10196:     my ($cdom,$cnum,$membership) = @_;
                   10197:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   10198:     return $result;
                   10199: }
                   10200: 
1.682     raeburn  10201: sub get_active_groups {
                   10202:     my ($udom,$uname,$cdom,$cnum) = @_;
                   10203:     my $now = time;
                   10204:     my %groups = ();
                   10205:     foreach my $key (keys(%env)) {
1.811     albertel 10206:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  10207:             my ($start,$end) = split(/\./,$env{$key});
                   10208:             if (($end!=0) && ($end<$now)) { next; }
                   10209:             if (($start!=0) && ($start>$now)) { next; }
                   10210:             if ($1 eq $cdom && $2 eq $cnum) {
                   10211:                 $groups{$3} = $env{$key} ;
                   10212:             }
                   10213:         }
                   10214:     }
                   10215:     return %groups;
                   10216: }
                   10217: 
1.683     raeburn  10218: sub get_group_membership {
                   10219:     my ($cdom,$cnum,$group) = @_;
                   10220:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   10221: }
                   10222: 
                   10223: sub get_users_groups {
                   10224:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  10225:     my @usersgroups;
1.683     raeburn  10226:     my $cachetime=1800;
                   10227: 
                   10228:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  10229:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   10230:     if (defined($cached)) {
1.734     albertel 10231:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  10232:     } else {  
                   10233:         $grouplist = '';
1.816     raeburn  10234:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  10235:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  10236:         my $access_end = $env{'course.'.$courseid.
                   10237:                               '.default_enrollment_end_date'};
                   10238:         my $now = time;
                   10239:         foreach my $key (keys(%roleshash)) {
                   10240:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   10241:                 my $group = $1;
                   10242:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   10243:                     my $start = $2;
                   10244:                     my $end = $1;
                   10245:                     if ($start == -1) { next; } # deleted from group
                   10246:                     if (($start!=0) && ($start>$now)) { next; }
                   10247:                     if (($end!=0) && ($end<$now)) {
                   10248:                         if ($access_end && $access_end < $now) {
                   10249:                             if ($access_end - $end < 86400) {
                   10250:                                 push(@usersgroups,$group);
1.733     raeburn  10251:                             }
                   10252:                         }
1.817     raeburn  10253:                         next;
1.733     raeburn  10254:                     }
1.817     raeburn  10255:                     push(@usersgroups,$group);
1.683     raeburn  10256:                 }
                   10257:             }
                   10258:         }
1.817     raeburn  10259:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   10260:         $grouplist = join(':',@usersgroups);
                   10261:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  10262:     }
1.733     raeburn  10263:     return @usersgroups;
1.683     raeburn  10264: }
                   10265: 
                   10266: sub devalidate_getgroups_cache {
                   10267:     my ($udom,$uname,$cdom,$cnum)=@_;
                   10268:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 10269: 
1.683     raeburn  10270:     my $hashid="$udom:$uname:$courseid";
                   10271:     &devalidate_cache_new('getgroups',$hashid);
                   10272: }
                   10273: 
1.12      www      10274: # ------------------------------------------------------------------ Plain Text
                   10275: 
                   10276: sub plaintext {
1.988     raeburn  10277:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  10278:     if ($short =~ m{^cr/}) {
1.758     albertel 10279: 	return (split('/',$short))[-1];
                   10280:     }
1.742     raeburn  10281:     if (!defined($cid)) {
                   10282:         $cid = $env{'request.course.id'};
                   10283:     }
                   10284:     my %rolenames = (
1.1008    raeburn  10285:                       Course    => 'std',
                   10286:                       Community => 'alt1',
1.742     raeburn  10287:                     );
1.1037    raeburn  10288:     if ($cid ne '') {
                   10289:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   10290:             unless ($forcedefault) {
                   10291:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   10292:                 &Apache::lonlocal::mt_escape(\$roletext);
                   10293:                 return &Apache::lonlocal::mt($roletext);
                   10294:             }
                   10295:         }
                   10296:     }
                   10297:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   10298:         (defined($rolenames{$type})) && 
                   10299:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  10300:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  10301:     } elsif ($cid ne '') {
                   10302:         my $crstype = $env{'course.'.$cid.'.type'};
                   10303:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   10304:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   10305:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   10306:         }
1.742     raeburn  10307:     }
1.1037    raeburn  10308:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      10309: }
                   10310: 
                   10311: # ----------------------------------------------------------------- Assign Role
                   10312: 
                   10313: sub assignrole {
1.957     raeburn  10314:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   10315:         $context)=@_;
1.21      www      10316:     my $mrole;
                   10317:     if ($role =~ /^cr\//) {
1.393     www      10318:         my $cwosec=$url;
1.811     albertel 10319:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      10320: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  10321:            my $refused = 1;
                   10322:            if ($context eq 'requestcourses') {
                   10323:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   10324:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   10325:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   10326:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10327:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10328:                            if ($crsenv{'internal.courseowner'} eq
                   10329:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   10330:                                $refused = '';
                   10331:                            }
                   10332:                        }
                   10333:                    }
                   10334:                }
                   10335:            }
                   10336:            if ($refused) {
                   10337:                &logthis('Refused custom assignrole: '.
                   10338:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   10339:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   10340:                return 'refused';
                   10341:            }
1.104     www      10342:         }
1.21      www      10343:         $mrole='cr';
1.678     raeburn  10344:     } elsif ($role =~ /^gr\//) {
                   10345:         my $cwogrp=$url;
1.811     albertel 10346:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  10347:         unless (&allowed('mdg',$cwogrp)) {
                   10348:             &logthis('Refused group assignrole: '.
                   10349:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   10350:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   10351:             return 'refused';
                   10352:         }
                   10353:         $mrole='gr';
1.21      www      10354:     } else {
1.82      www      10355:         my $cwosec=$url;
1.811     albertel 10356:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  10357:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   10358:             my $refused;
                   10359:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   10360:                 if (!(&allowed('c'.$role,$url))) {
                   10361:                     $refused = 1;
                   10362:                 }
                   10363:             } else {
                   10364:                 $refused = 1;
                   10365:             }
1.947     raeburn  10366:             if ($refused) {
1.1045    raeburn  10367:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10368:                 if (!$selfenroll && $context eq 'course') {
                   10369:                     my %crsenv;
                   10370:                     if ($role eq 'cc' || $role eq 'co') {
                   10371:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10372:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   10373:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   10374:                                 if ($crsenv{'internal.courseowner'} eq 
                   10375:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10376:                                     $refused = '';
                   10377:                                 }
                   10378:                             }
                   10379:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   10380:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   10381:                                 if ($crsenv{'internal.courseowner'} eq 
                   10382:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10383:                                     $refused = '';
                   10384:                                 }
                   10385:                             }
                   10386:                         }
                   10387:                     }
1.1172.2.146.  .13(raeb 10388:-23):                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   10389:-23):                     if ($role eq 'st') {
                   10390:-23):                         $refused = '';
                   10391:-23):                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
                   10392:-23):                         $refused = '';
                   10393:-23):                     }
1.1017    raeburn  10394:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10395:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10396:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10397:                         my $wrongcc;
                   10398:                         if ($cnum =~ /^$match_community$/) {
                   10399:                             $wrongcc = 1 if ($role eq 'cc');
                   10400:                         } else {
                   10401:                             $wrongcc = 1 if ($role eq 'co');
                   10402:                         }
                   10403:                         unless ($wrongcc) {
                   10404:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10405:                             if ($crsenv{'internal.courseowner'} eq 
                   10406:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10407:                                 $refused = '';
                   10408:                             }
1.1017    raeburn  10409:                         }
                   10410:                     }
1.1172.2.9  raeburn  10411:                 } elsif ($context eq 'requestauthor') {
                   10412:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   10413:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10414:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10415:                             $refused = '';
                   10416:                         } else {
                   10417:                             my %domdefaults = &get_domain_defaults($udom);
                   10418:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10419:                                 my $checkbystatus;
                   10420:                                 if ($env{'user.adv'}) {
                   10421:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10422:                                     if ($disposition eq 'automatic') {
                   10423:                                         $refused = '';
                   10424:                                     } elsif ($disposition eq '') {
                   10425:                                         $checkbystatus = 1;
                   10426:                                     }
                   10427:                                 } else {
                   10428:                                     $checkbystatus = 1;
                   10429:                                 }
                   10430:                                 if ($checkbystatus) {
                   10431:                                     if ($env{'environment.inststatus'}) {
                   10432:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10433:                                         foreach my $type (@inststatuses) {
                   10434:                                             if (($type ne '') &&
                   10435:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10436:                                                 $refused = '';
                   10437:                                             }
                   10438:                                         }
                   10439:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10440:                                         $refused = '';
                   10441:                                     }
                   10442:                                 }
                   10443:                             }
                   10444:                         }
                   10445:                     }
1.1017    raeburn  10446:                 }
                   10447:                 if ($refused) {
1.947     raeburn  10448:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10449:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10450: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10451:                     return 'refused';
                   10452:                 }
1.932     raeburn  10453:             }
1.1131    raeburn  10454:         } elsif ($role eq 'au') {
                   10455:             if ($url ne '/'.$udom.'/') {
                   10456:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10457:                          ' to assign author role for '.$uname.':'.$udom.
                   10458:                          ' in domain: '.$url.' refused (wrong domain).');
                   10459:                 return 'refused';
                   10460:             }
1.104     www      10461:         }
1.21      www      10462:         $mrole=$role;
                   10463:     }
1.620     albertel 10464:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10465:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10466:     if ($end) { $command.='_'.$end; }
1.21      www      10467:     if ($start) {
                   10468: 	if ($end) { 
1.81      www      10469:            $command.='_'.$start; 
1.21      www      10470:         } else {
1.81      www      10471:            $command.='_0_'.$start;
1.21      www      10472:         }
                   10473:     }
1.739     raeburn  10474:     my $origstart = $start;
                   10475:     my $origend = $end;
1.957     raeburn  10476:     my $delflag;
1.357     www      10477: # actually delete
                   10478:     if ($deleteflag) {
1.373     www      10479: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10480: # modify command to delete the role
1.620     albertel 10481:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10482:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10483: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10484: # set start and finish to negative values for userrolelog
                   10485:            $start=-1;
                   10486:            $end=-1;
1.957     raeburn  10487:            $delflag = 1;
1.357     www      10488:         }
                   10489:     }
                   10490: # send command
1.349     www      10491:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      10492: # log new user role if status is ok
1.349     www      10493:     if ($answer eq 'ok') {
1.663     raeburn  10494: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  10495:         if (($role eq 'cc') || ($role eq 'in') ||
                   10496:             ($role eq 'ep') || ($role eq 'ad') ||
                   10497:             ($role eq 'ta') || ($role eq 'st') ||
                   10498:             ($role=~/^cr/) || ($role eq 'gr') ||
                   10499:             ($role eq 'co')) {
1.1172.2.13  raeburn  10500: # for course roles, perform group memberships changes triggered by role change.
                   10501:             unless ($role =~ /^gr/) {
                   10502:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10503:                                                  $origstart,$selfenroll,$context);
                   10504:             }
1.1172.2.9  raeburn  10505:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10506:                            $selfenroll,$context);
                   10507:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  10508:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10509:                  ($role eq 'da')) {
1.1172.2.9  raeburn  10510:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10511:                            $context);
                   10512:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10513:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10514:                              $context);
                   10515:         }
1.1053    raeburn  10516:         if ($role eq 'cc') {
                   10517:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10518:         }
1.349     www      10519:     }
                   10520:     return $answer;
1.169     harris41 10521: }
                   10522: 
1.1053    raeburn  10523: sub autoupdate_coowners {
                   10524:     my ($url,$end,$start,$uname,$udom) = @_;
                   10525:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10526:     if (($cdom ne '') && ($cnum ne '')) {
                   10527:         my $now = time;
                   10528:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10529:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10530:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10531:             my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141  raeburn  10532:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  10533:             if ($instcode ne '') {
1.1056    raeburn  10534:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10535:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10536:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10537:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141  raeburn  10538:                         unless ($result eq 'valid') {
                   10539:                             if ($xlists ne '') {
                   10540:                                 foreach my $xlist (split(',',$xlists)) {
                   10541:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   10542:                                     $result =
                   10543:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   10544:                                                                       $inst_crosslist,$uname.':'.$udom);
                   10545:                                     last if ($result eq 'valid');
                   10546:                                 }
                   10547:                             }
                   10548:                         }
1.1056    raeburn  10549:                         if ($result eq 'valid') {
                   10550:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10551:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10552:                                     push(@newcoowners,$coowner);
                   10553:                                 }
                   10554:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10555:                                     push(@newcoowners,$uname.':'.$udom);
                   10556:                                 }
                   10557:                                 @newcoowners = sort(@newcoowners);
                   10558:                             } else {
                   10559:                                 push(@newcoowners,$uname.':'.$udom);
                   10560:                             }
1.1172.2.141  raeburn  10561:                         } elsif ($coursehash{'internal.co-owners'}) {
                   10562:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10563:                                 unless ($coowner eq $uname.':'.$udom) {
                   10564:                                     push(@newcoowners,$coowner);
1.1053    raeburn  10565:                                 }
                   10566:                             }
1.1172.2.141  raeburn  10567:                             unless (@newcoowners > 0) {
                   10568:                                 $delcoowners = 1;
                   10569:                                 $coowners = '';
                   10570:                             }
1.1053    raeburn  10571:                         }
                   10572:                         if (@newcoowners || $delcoowners) {
                   10573:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10574:                                             $delcoowners,@newcoowners);
                   10575:                         }
                   10576:                     }
                   10577:                 }
                   10578:             }
                   10579:         }
                   10580:     }
                   10581: }
                   10582: 
                   10583: sub store_coowners {
                   10584:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10585:     my $cid = $cdom.'_'.$cnum;
                   10586:     my ($coowners,$delresult,$putresult);
                   10587:     if (@newcoowners) {
                   10588:         $coowners = join(',',@newcoowners);
                   10589:         my %coownershash = (
                   10590:                             'internal.co-owners' => $coowners,
                   10591:                            );
                   10592:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10593:         if ($putresult eq 'ok') {
                   10594:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10595:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10596:             }
                   10597:         }
                   10598:     }
                   10599:     if ($delcoowners) {
                   10600:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10601:         if ($delresult eq 'ok') {
                   10602:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10603:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10604:             }
                   10605:         }
                   10606:     }
                   10607:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10608:         my %crsinfo =
                   10609:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10610:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10611:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10612:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10613:         }
                   10614:     }
                   10615: }
                   10616: 
1.169     harris41 10617: # -------------------------------------------------- Modify user authentication
1.197     www      10618: # Overrides without validation
                   10619: 
1.169     harris41 10620: sub modifyuserauth {
                   10621:     my ($udom,$uname,$umode,$upass)=@_;
                   10622:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  10623:     my $allowed;
                   10624:     if (&allowed('mau',$udom)) {
                   10625:         $allowed = 1;
                   10626:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10627:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10628:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10629:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10630:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10631:         if (($cdom ne '') && ($cnum ne '')) {
                   10632:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10633:             if ($is_owner) {
                   10634:                 $allowed = 1;
                   10635:             }
                   10636:         }
                   10637:     }
                   10638:     unless ($allowed) { return 'refused'; }
1.197     www      10639:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10640:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10641:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10642:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10643: 		     &escape($upass),$uhome);
1.1172.2.134  raeburn  10644:     my $ip = &get_requestor_ip();
1.620     albertel 10645:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10646:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134  raeburn  10647:          '(Remote '.$ip.'): '.$reply);
1.197     www      10648:     &log($udom,,$uname,$uhome,
1.620     albertel 10649:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10650:                                      $env{'user.name'}.', '.$umode.
1.1172.2.134  raeburn  10651:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10652:     unless ($reply eq 'ok') {
1.197     www      10653:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10654: 	return 'error: '.$reply;
                   10655:     }   
1.170     harris41 10656:     return 'ok';
1.80      www      10657: }
                   10658: 
1.81      www      10659: # --------------------------------------------------------------- Modify a user
1.80      www      10660: 
1.81      www      10661: sub modifyuser {
1.206     matthew  10662:     my ($udom,    $uname, $uid,
                   10663:         $umode,   $upass, $first,
                   10664:         $middle,  $last,  $gene,
1.1058    raeburn  10665:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10666:     $udom= &LONCAPA::clean_domain($udom);
                   10667:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10668:     my $showcandelete = 'none';
                   10669:     if (ref($candelete) eq 'ARRAY') {
                   10670:         if (@{$candelete} > 0) {
                   10671:             $showcandelete = join(', ',@{$candelete});
                   10672:         }
                   10673:     }
1.81      www      10674:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10675:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10676: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10677:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10678:                                      ' desiredhome not specified'). 
1.620     albertel 10679:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10680:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10681:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10682:     my $newuser;
                   10683:     if ($uhome eq 'no_host') {
                   10684:         $newuser = 1;
1.1172.2.146.  .13(raeb 10685:-23):         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   10686:-23):                 ($umode eq 'lti')) {
                   10687:-23):             return 'error: more information needed to create new user';
                   10688:-23):         }
1.1075    raeburn  10689:     }
1.80      www      10690: # ----------------------------------------------------------------- Create User
1.406     albertel 10691:     if (($uhome eq 'no_host') && 
1.1172.2.146.  .13(raeb 10692:-23): 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      10693:         my $unhome='';
1.844     albertel 10694:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10695:             $unhome = $desiredhome;
1.620     albertel 10696: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10697: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10698:         } else { # load balancing routine for determining $unhome
1.81      www      10699:             my $loadm=10000000;
1.841     albertel 10700: 	    my %servers = &get_servers($udom,'library');
                   10701: 	    foreach my $tryserver (keys(%servers)) {
                   10702: 		my $answer=reply('load',$tryserver);
                   10703: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10704: 		    $loadm=$answer;
                   10705: 		    $unhome=$tryserver;
                   10706: 		}
1.80      www      10707: 	    }
                   10708:         }
                   10709:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10710: 	    return 'error: unable to find a home server for '.$uname.
                   10711:                    ' in domain '.$udom;
1.80      www      10712:         }
                   10713:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10714:                          &escape($upass),$unhome);
                   10715: 	unless ($reply eq 'ok') {
                   10716:             return 'error: '.$reply;
                   10717:         }   
1.230     stredwic 10718:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10719:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10720: 	    return 'error: unable verify users home machine.';
1.80      www      10721:         }
1.209     matthew  10722:     }   # End of creation of new user
1.80      www      10723: # ---------------------------------------------------------------------- Add ID
                   10724:     if ($uid) {
                   10725:        $uid=~tr/A-Z/a-z/;
                   10726:        my %uidhash=&idrget($udom,$uname);
1.196     www      10727:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10728:          && (!$forceid)) {
1.80      www      10729: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10730: 	      return 'error: user id "'.$uid.'" does not match '.
                   10731:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10732:           }
                   10733:        } else {
                   10734: 	  &idput($udom,($uname => $uid));
                   10735:        }
                   10736:     }
                   10737: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10738:     my @tmp=&get('environment',
1.899     raeburn  10739: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10740:                     'permanentemail','inststatus'],
1.134     albertel 10741: 		   $udom,$uname);
1.1075    raeburn  10742:     my (%names,%oldnames);
1.313     matthew  10743:     if ($tmp[0] =~ m/^error:.*/) { 
                   10744:         %names=(); 
                   10745:     } else {
                   10746:         %names = @tmp;
1.1075    raeburn  10747:         %oldnames = %names;
1.313     matthew  10748:     }
1.388     www      10749: #
1.1058    raeburn  10750: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10751: # of users did not contain them), do not overwrite existing values
                   10752: # unless field is in $candelete array ref.  
                   10753: #
                   10754: 
                   10755:     my @fields = ('firstname','middlename','lastname','generation',
                   10756:                   'permanentemail','id');
                   10757:     my %newvalues;
                   10758:     if (ref($candelete) eq 'ARRAY') {
                   10759:         foreach my $field (@fields) {
                   10760:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10761:                 if ($field eq 'firstname') {
                   10762:                     $names{$field} = $first;
                   10763:                 } elsif ($field eq 'middlename') {
                   10764:                     $names{$field} = $middle;
                   10765:                 } elsif ($field eq 'lastname') {
                   10766:                     $names{$field} = $last;
                   10767:                 } elsif ($field eq 'generation') { 
                   10768:                     $names{$field} = $gene;
                   10769:                 } elsif ($field eq 'permanentemail') {
                   10770:                     $names{$field} = $email;
                   10771:                 } elsif ($field eq 'id') {
                   10772:                     $names{$field}  = $uid;
                   10773:                 }
                   10774:             }
                   10775:         }
                   10776:     }
1.388     www      10777:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10778:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10779:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10780:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10781:     if ($email) {
                   10782:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10783:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10784:     }
1.899     raeburn  10785:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10786:     if (defined($inststatus)) {
                   10787:         $names{'inststatus'} = '';
                   10788:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10789:         if (ref($usertypes) eq 'HASH') {
                   10790:             my @okstatuses; 
                   10791:             foreach my $item (split(/:/,$inststatus)) {
                   10792:                 if (defined($usertypes->{$item})) {
                   10793:                     push(@okstatuses,$item);  
                   10794:                 }
                   10795:             }
                   10796:             if (@okstatuses) {
                   10797:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10798:             }
                   10799:         }
                   10800:     }
1.1075    raeburn  10801:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10802:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10803:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10804:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10805:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10806:     } else {
                   10807:         $logmsg .= ' during self creation';
                   10808:     }
1.1075    raeburn  10809:     my $changed;
                   10810:     if ($newuser) {
                   10811:         $changed = 1;
                   10812:     } else {
                   10813:         foreach my $field (@fields) {
                   10814:             if ($names{$field} ne $oldnames{$field}) {
                   10815:                 $changed = 1;
                   10816:                 last;
                   10817:             }
                   10818:         }
                   10819:     }
                   10820:     unless ($changed) {
                   10821:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10822:         &logthis($logmsg);
                   10823:         return 'ok';
                   10824:     }
                   10825:     my $reply = &put('environment', \%names, $udom,$uname);
                   10826:     if ($reply ne 'ok') { 
                   10827:         return 'error: '.$reply;
                   10828:     }
1.1087    raeburn  10829:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10830:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10831:     }
1.1075    raeburn  10832:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10833:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10834:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10835:     &logthis($logmsg);
1.134     albertel 10836:     return 'ok';
1.80      www      10837: }
                   10838: 
1.81      www      10839: # -------------------------------------------------------------- Modify student
1.80      www      10840: 
1.81      www      10841: sub modifystudent {
                   10842:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10843:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10844:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10845:     if (!$cid) {
1.620     albertel 10846: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10847: 	    return 'not_in_class';
                   10848: 	}
1.80      www      10849:     }
                   10850: # --------------------------------------------------------------- Make the user
1.81      www      10851:     my $reply=&modifyuser
1.209     matthew  10852: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10853:          $desiredhome,$email,$inststatus);
1.80      www      10854:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10855:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10856:     # student's environment
1.297     matthew  10857:     $uid = undef if (!$forceid);
1.455     albertel 10858:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10859: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10860:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10861:     return $reply;
                   10862: }
                   10863: 
                   10864: sub modify_student_enrollment {
1.1172.2.23  raeburn  10865:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10866:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10867:     my ($cdom,$cnum,$chome);
                   10868:     if (!$cid) {
1.620     albertel 10869: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10870: 	    return 'not_in_class';
                   10871: 	}
1.620     albertel 10872: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10873: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10874:     } else {
                   10875: 	($cdom,$cnum)=split(/_/,$cid);
                   10876:     }
1.620     albertel 10877:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10878:     if (!$chome) {
1.457     raeburn  10879: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10880:     }
1.455     albertel 10881:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10882:     # Make sure the user exists
1.81      www      10883:     my $uhome=&homeserver($uname,$udom);
                   10884:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10885: 	return 'error: no such user';
                   10886:     }
1.297     matthew  10887:     # Get student data if we were not given enough information
                   10888:     if (!defined($first)  || $first  eq '' || 
                   10889:         !defined($last)   || $last   eq '' || 
                   10890:         !defined($uid)    || $uid    eq '' || 
                   10891:         !defined($middle) || $middle eq '' || 
                   10892:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10893:         # They did not supply us with enough data to enroll the student, so
                   10894:         # we need to pick up more information.
1.297     matthew  10895:         my %tmp = &get('environment',
1.294     matthew  10896:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10897:                        ,$udom,$uname);
                   10898: 
1.800     albertel 10899:         #foreach my $key (keys(%tmp)) {
                   10900:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10901:         #}
1.294     matthew  10902:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10903:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10904:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10905:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10906:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10907:     }
1.556     albertel 10908:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10909:     my $user = "$uname:$udom";
                   10910:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10911:     my $reply=cput('classlist',
1.1148    raeburn  10912: 		   {$user => 
1.1172.2.76  raeburn  10913: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10914: 		   $cdom,$cnum);
1.1148    raeburn  10915:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10916:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10917:     } else { 
1.81      www      10918: 	return 'error: '.$reply;
                   10919:     }
1.297     matthew  10920:     # Add student role to user
1.83      www      10921:     my $uurl='/'.$cid;
1.81      www      10922:     $uurl=~s/\_/\//g;
                   10923:     if ($usec) {
                   10924: 	$uurl.='/'.$usec;
                   10925:     }
1.1148    raeburn  10926:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10927:                              $selfenroll,$context);
                   10928:     if ($result ne 'ok') {
                   10929:         if ($old_entry{$user} ne '') {
                   10930:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10931:         } else {
                   10932:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10933:         }
                   10934:     }
                   10935:     return $result; 
1.21      www      10936: }
                   10937: 
1.556     albertel 10938: sub format_name {
                   10939:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10940:     my $name;
                   10941:     if ($first ne 'lastname') {
                   10942: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10943:     } else {
                   10944: 	if ($lastname=~/\S/) {
                   10945: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10946: 	    $name=~s/\s+,/,/;
                   10947: 	} else {
                   10948: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10949: 	}
                   10950:     }
                   10951:     $name=~s/^\s+//;
                   10952:     $name=~s/\s+$//;
                   10953:     $name=~s/\s+/ /g;
                   10954:     return $name;
                   10955: }
                   10956: 
1.84      www      10957: # ------------------------------------------------- Write to course preferences
                   10958: 
                   10959: sub writecoursepref {
                   10960:     my ($courseid,%prefs)=@_;
                   10961:     $courseid=~s/^\///;
                   10962:     $courseid=~s/\_/\//g;
                   10963:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10964:     my $chome=homeserver($cnum,$cdomain);
                   10965:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10966: 	return 'error: no such course';
                   10967:     }
                   10968:     my $cstring='';
1.800     albertel 10969:     foreach my $pref (keys(%prefs)) {
                   10970: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10971:     }
1.84      www      10972:     $cstring=~s/\&$//;
                   10973:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10974: }
                   10975: 
                   10976: # ---------------------------------------------------------- Make/modify course
                   10977: 
                   10978: sub createcourse {
1.741     raeburn  10979:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.146.  .1(raebu 10980:22):         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10981:     $url=&declutter($url);
                   10982:     my $cid='';
1.1028    raeburn  10983:     if ($context eq 'requestcourses') {
                   10984:         my $can_create = 0;
                   10985:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10986:         if ($udom eq $ownerdom) {
1.1172.2.146.  .1(raebu 10987:22):             my $reload;
                   10988:22):             if (($callercontext eq 'auto') &&
                   10989:22):                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10990:22):                 $reload = 'reload';
                   10991:22):             }
                   10992:22):             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10993:                                   $context)) {
                   10994:                 $can_create = 1;
                   10995:             }
                   10996:         } else {
                   10997:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10998:                                            $category);
                   10999:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   11000:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   11001:                 if (@curr > 0) {
                   11002:                     my @options = qw(approval validate autolimit);
                   11003:                     my $optregex = join('|',@options);
                   11004:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   11005:                         $can_create = 1;
                   11006:                     }
                   11007:                 }
                   11008:             }
                   11009:         }
                   11010:         if ($can_create) {
                   11011:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   11012:                 unless (&allowed('ccc',$udom)) {
                   11013:                     return 'refused'; 
                   11014:                 }
1.1017    raeburn  11015:             }
                   11016:         } else {
                   11017:             return 'refused';
                   11018:         }
1.1028    raeburn  11019:     } elsif (!&allowed('ccc',$udom)) {
                   11020:         return 'refused';
1.84      www      11021:     }
1.1011    raeburn  11022: # --------------------------------------------------------------- Get Unique ID
                   11023:     my $uname;
                   11024:     if ($cnum =~ /^$match_courseid$/) {
                   11025:         my $chome=&homeserver($cnum,$udom,'true');
                   11026:         if (($chome eq '') || ($chome eq 'no_host')) {
                   11027:             $uname = $cnum;
                   11028:         } else {
1.1038    raeburn  11029:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  11030:         }
                   11031:     } else {
1.1038    raeburn  11032:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  11033:     }
                   11034:     return $uname if ($uname =~ /^error/);
                   11035: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  11036:     if (!defined($course_server)) {
                   11037:         if (defined(&domain($udom,'primary'))) {
                   11038:             $course_server = &domain($udom,'primary');
                   11039:         } else {
                   11040:             $course_server = $env{'user.home'}; 
                   11041:         }
                   11042:     }
                   11043:     my %host_servers =
                   11044:         &Apache::lonnet::get_servers($udom,'library');
                   11045:     unless ($host_servers{$course_server}) {
                   11046:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  11047:     }
1.84      www      11048: # ------------------------------------------------------------- Make the course
                   11049:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  11050:                       $course_server);
1.84      www      11051:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  11052:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      11053:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   11054: 	return 'error: no such course';
                   11055:     }
1.271     www      11056: # ----------------------------------------------------------------- Course made
1.516     raeburn  11057: # log existence
1.1029    raeburn  11058:     my $now = time;
1.918     raeburn  11059:     my $newcourse = {
                   11060:                     $udom.'_'.$uname => {
1.921     raeburn  11061:                                      description => $description,
                   11062:                                      inst_code   => $inst_code,
                   11063:                                      owner       => $course_owner,
                   11064:                                      type        => $crstype,
1.1029    raeburn  11065:                                      creator     => $env{'user.name'}.':'.
                   11066:                                                     $env{'user.domain'},
                   11067:                                      created     => $now,
                   11068:                                      context     => $context,
1.918     raeburn  11069:                                                 },
                   11070:                     };
1.921     raeburn  11071:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      11072: # set toplevel url
1.271     www      11073:     my $topurl=$url;
                   11074:     unless ($nonstandard) {
                   11075: # ------------------------------------------ For standard courses, make top url
                   11076:         my $mapurl=&clutter($url);
1.278     www      11077:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 11078:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      11079: <map>
                   11080: <resource id="1" type="start"></resource>
                   11081: <resource id="2" src="$mapurl"></resource>
                   11082: <resource id="3" type="finish"></resource>
                   11083: <link index="1" from="1" to="2"></link>
                   11084: <link index="2" from="2" to="3"></link>
                   11085: </map>
                   11086: ENDINITMAP
                   11087:         $topurl=&declutter(
1.638     albertel 11088:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      11089:                           );
                   11090:     }
                   11091: # ----------------------------------------------------------- Write preferences
1.84      www      11092:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  11093:                      ('description'              => $description,
                   11094:                       'url'                      => $topurl,
                   11095:                       'internal.creator'         => $env{'user.name'}.':'.
                   11096:                                                     $env{'user.domain'},
                   11097:                       'internal.created'         => $now,
                   11098:                       'internal.creationcontext' => $context)
                   11099:                     );
1.84      www      11100:     return '/'.$udom.'/'.$uname;
                   11101: }
                   11102: 
1.1011    raeburn  11103: # ------------------------------------------------------------------- Create ID
                   11104: sub generate_coursenum {
1.1038    raeburn  11105:     my ($udom,$crstype) = @_;
1.1011    raeburn  11106:     my $domdesc = &domain($udom);
                   11107:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  11108:     my $first;
                   11109:     if ($crstype eq 'Community') {
                   11110:         $first = '0';
                   11111:     } else {
                   11112:         $first = int(1+rand(9)); 
                   11113:     } 
                   11114:     my $uname=$first.
1.1011    raeburn  11115:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11116:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11117:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11118: # ----------------------------------------------- Make sure that does not exist
                   11119:     my $uhome=&homeserver($uname,$udom,'true');
                   11120:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  11121:         if ($crstype eq 'Community') {
                   11122:             $first = '0';
                   11123:         } else {
                   11124:             $first = int(1+rand(9));
                   11125:         }
                   11126:         $uname=$first.
1.1011    raeburn  11127:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11128:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11129:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11130:         $uhome=&homeserver($uname,$udom,'true');
                   11131:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   11132:             return 'error: unable to generate unique course-ID';
                   11133:         }
                   11134:     }
                   11135:     return $uname;
                   11136: }
                   11137: 
1.813     albertel 11138: sub is_course {
1.1167    droeschl 11139:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   11140:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  11141:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   11142:     my $uhome=&homeserver($cnum,$cdom);
                   11143:     my $iscourse;
                   11144:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   11145:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   11146:     } else {
                   11147:         my $hashid = $cdom.':'.$cnum;
                   11148:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   11149:         unless (defined($cached)) {
                   11150:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   11151:                                         $cnum,undef,undef,'.');
                   11152:             $iscourse = 0;
                   11153:             if (exists($courses{$cdom.'_'.$cnum})) {
                   11154:                 $iscourse = 1;
                   11155:             }
                   11156:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   11157:         }
                   11158:     }
                   11159:     return unless($iscourse);
1.1167    droeschl 11160:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 11161: }
                   11162: 
1.1015    raeburn  11163: sub store_userdata {
                   11164:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  11165:     my $result;
1.1016    raeburn  11166:     if ($datakey ne '') {
1.1013    raeburn  11167:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  11168:             if ($udom eq '' || $uname eq '') {
                   11169:                 $udom = $env{'user.domain'};
                   11170:                 $uname = $env{'user.name'};
                   11171:             }
                   11172:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  11173:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   11174:                 $result = 'error: no_host';
                   11175:             } else {
1.1172.2.138  raeburn  11176:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  11177:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   11178: 
                   11179:                 my $namevalue='';
                   11180:                 foreach my $key (keys(%{$storehash})) {
                   11181:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   11182:                 }
                   11183:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  11184:                 unless ($namespace eq 'courserequests') {
                   11185:                     $datakey = &escape($datakey);
                   11186:                 }
1.1105    raeburn  11187:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   11188:                                   $namevalue,$uhome);
1.1013    raeburn  11189:             }
                   11190:         } else {
                   11191:             $result = 'error: data to store was not a hash reference'; 
                   11192:         }
                   11193:     } else {
                   11194:         $result= 'error: invalid requestkey'; 
                   11195:     }
                   11196:     return $result;
                   11197: }
                   11198: 
1.21      www      11199: # ---------------------------------------------------------- Assign Custom Role
                   11200: 
                   11201: sub assigncustomrole {
1.957     raeburn  11202:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11203:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  11204:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      11205: }
                   11206: 
                   11207: # ----------------------------------------------------------------- Revoke Role
                   11208: 
                   11209: sub revokerole {
1.957     raeburn  11210:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11211:     my $now=time;
1.965     raeburn  11212:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      11213: }
                   11214: 
                   11215: # ---------------------------------------------------------- Revoke Custom Role
                   11216: 
                   11217: sub revokecustomrole {
1.957     raeburn  11218:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11219:     my $now=time;
1.357     www      11220:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  11221:            $deleteflag,$selfenroll,$context);
1.17      www      11222: }
                   11223: 
1.533     banghart 11224: # ------------------------------------------------------------ Disk usage
1.535     albertel 11225: sub diskusage {
1.955     raeburn  11226:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   11227:     $directorypath =~ s/\/$//;
                   11228:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   11229:                        .&escape($getpropath).':'.&escape($uname).':'
                   11230:                        .&escape($udom),homeserver($uname,$udom));
                   11231:     if ($listing eq 'unknown_cmd') {
                   11232:         if ($getpropath) {
                   11233:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   11234:         }
                   11235:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   11236:     }
1.514     albertel 11237:     return $listing;
1.512     banghart 11238: }
                   11239: 
1.566     banghart 11240: sub is_locked {
1.1096    raeburn  11241:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 11242:     my @check;
                   11243:     my $is_locked;
1.1093    raeburn  11244:     push (@check,$file_name);
1.613     albertel 11245:     my %locked = &get('file_permissions',\@check,
1.620     albertel 11246: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 11247:     my ($tmp)=keys(%locked);
                   11248:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  11249:     
1.566     banghart 11250:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  11251:         $is_locked = 'false';
                   11252:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  11253:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  11254:                $is_locked = 'true';
1.1096    raeburn  11255:                if (ref($which) eq 'ARRAY') {
                   11256:                    push(@{$which},$entry);
                   11257:                } else {
                   11258:                    last;
                   11259:                }
1.745     raeburn  11260:            }
                   11261:        }
1.566     banghart 11262:     } else {
                   11263:         $is_locked = 'false';
                   11264:     }
1.1093    raeburn  11265:     return $is_locked;
1.566     banghart 11266: }
                   11267: 
1.759     albertel 11268: sub declutter_portfile {
                   11269:     my ($file) = @_;
1.833     albertel 11270:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 11271:     return $file;
                   11272: }
                   11273: 
1.559     banghart 11274: # ------------------------------------------------------------- Mark as Read Only
                   11275: 
                   11276: sub mark_as_readonly {
                   11277:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 11278:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11279:     my ($tmp)=keys(%current_permissions);
                   11280:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 11281:     foreach my $file (@{$files}) {
1.759     albertel 11282: 	$file = &declutter_portfile($file);
1.561     banghart 11283:         push(@{$current_permissions{$file}},$what);
1.559     banghart 11284:     }
1.613     albertel 11285:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11286:     return;
                   11287: }
                   11288: 
1.572     banghart 11289: # ------------------------------------------------------------Save Selected Files
                   11290: 
                   11291: sub save_selected_files {
                   11292:     my ($user, $path, @files) = @_;
                   11293:     my $filename = $user."savedfiles";
1.573     banghart 11294:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  11295:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 11296:     foreach my $file (@files) {
1.620     albertel 11297:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 11298:     }
                   11299:     foreach my $file (@other_files) {
1.574     banghart 11300:         print (OUT $file."\n");
1.572     banghart 11301:     }
1.574     banghart 11302:     close (OUT);
1.572     banghart 11303:     return 'ok';
                   11304: }
                   11305: 
1.574     banghart 11306: sub clear_selected_files {
                   11307:     my ($user) = @_;
                   11308:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  11309:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 11310:     print (OUT undef);
                   11311:     close (OUT);
                   11312:     return ("ok");    
                   11313: }
                   11314: 
1.572     banghart 11315: sub files_in_path {
                   11316:     my ($user, $path) = @_;
                   11317:     my $filename = $user."savedfiles";
                   11318:     my %return_files;
1.1172.2.96  raeburn  11319:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 11320:     while (my $line_in = <IN>) {
1.574     banghart 11321:         chomp ($line_in);
                   11322:         my @paths_and_file = split (m!/!, $line_in);
                   11323:         my $file_part = pop (@paths_and_file);
                   11324:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 11325:         $path_part.='/';
                   11326:         my $path_and_file = $path_part.$file_part;
                   11327:         if ($path_part eq $path) {
                   11328:             $return_files{$file_part}= 'selected';
                   11329:         }
                   11330:     }
1.574     banghart 11331:     close (IN);
                   11332:     return (\%return_files);
1.572     banghart 11333: }
                   11334: 
                   11335: # called in portfolio select mode, to show files selected NOT in current directory
                   11336: sub files_not_in_path {
                   11337:     my ($user, $path) = @_;
                   11338:     my $filename = $user."savedfiles";
                   11339:     my @return_files;
                   11340:     my $path_part;
1.1172.2.96  raeburn  11341:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 11342:     while (my $line = <IN>) {
1.572     banghart 11343:         #ok, I know it's clunky, but I want it to work
1.800     albertel 11344:         my @paths_and_file = split(m|/|, $line);
                   11345:         my $file_part = pop(@paths_and_file);
                   11346:         chomp($file_part);
                   11347:         my $path_part = join('/', @paths_and_file);
1.572     banghart 11348:         $path_part .= '/';
                   11349:         my $path_and_file = $path_part.$file_part;
                   11350:         if ($path_part ne $path) {
1.800     albertel 11351:             push(@return_files, ($path_and_file));
1.572     banghart 11352:         }
                   11353:     }
1.800     albertel 11354:     close(OUT);
1.574     banghart 11355:     return (@return_files);
1.572     banghart 11356: }
                   11357: 
1.745     raeburn  11358: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11359: 
1.745     raeburn  11360: sub get_portfile_permissions {
                   11361:     my ($domain,$user) = @_;
1.613     albertel 11362:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11363:     my ($tmp)=keys(%current_permissions);
                   11364:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11365:     return \%current_permissions;
                   11366: }
                   11367: 
                   11368: #---------------------------------------------Get portfolio file access controls
                   11369: 
1.749     raeburn  11370: sub get_access_controls {
1.745     raeburn  11371:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11372:     my %access;
                   11373:     my $real_file = $file;
                   11374:     $file =~ s/\.meta$//;
1.745     raeburn  11375:     if (defined($file)) {
1.749     raeburn  11376:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11377:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11378:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11379:             }
                   11380:         }
1.745     raeburn  11381:     } else {
1.749     raeburn  11382:         foreach my $key (keys(%{$current_permissions})) {
                   11383:             if ($key =~ /\0accesscontrol$/) {
                   11384:                 if (defined($group)) {
                   11385:                     if ($key !~ m-^\Q$group\E/-) {
                   11386:                         next;
                   11387:                     }
                   11388:                 }
                   11389:                 my ($fullpath) = split(/\0/,$key);
                   11390:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11391:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11392:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11393:                     }
                   11394:                 }
                   11395:             }
                   11396:         }
                   11397:     }
                   11398:     return %access;
                   11399: }
                   11400: 
                   11401: sub modify_access_controls {
                   11402:     my ($file_name,$changes,$domain,$user)=@_;
                   11403:     my ($outcome,$deloutcome);
                   11404:     my %store_permissions;
                   11405:     my %new_values;
                   11406:     my %new_control;
                   11407:     my %translation;
                   11408:     my @deletions = ();
                   11409:     my $now = time;
                   11410:     if (exists($$changes{'activate'})) {
                   11411:         if (ref($$changes{'activate'}) eq 'HASH') {
                   11412:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   11413:             my $numnew = scalar(@newitems);
                   11414:             for (my $i=0; $i<$numnew; $i++) {
                   11415:                 my $newkey = $newitems[$i];
                   11416:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  11417:                 if ($newkey =~ /^\d+:/) { 
                   11418:                     $newkey =~ s/^(\d+)/$newid/;
                   11419:                     $translation{$1} = $newid;
                   11420:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   11421:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   11422:                     $translation{$1} = $newid;
                   11423:                 }
1.749     raeburn  11424:                 $new_values{$file_name."\0".$newkey} = 
                   11425:                                           $$changes{'activate'}{$newitems[$i]};
                   11426:                 $new_control{$newkey} = $now;
                   11427:             }
                   11428:         }
                   11429:     }
                   11430:     my %todelete;
                   11431:     my %changed_items;
                   11432:     foreach my $action ('delete','update') {
                   11433:         if (exists($$changes{$action})) {
                   11434:             if (ref($$changes{$action}) eq 'HASH') {
                   11435:                 foreach my $key (keys(%{$$changes{$action}})) {
                   11436:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   11437:                     if ($action eq 'delete') { 
                   11438:                         $todelete{$itemnum} = 1;
                   11439:                     } else {
                   11440:                         $changed_items{$itemnum} = $key;
                   11441:                     }
                   11442:                 }
1.745     raeburn  11443:             }
                   11444:         }
1.749     raeburn  11445:     }
                   11446:     # get lock on access controls for file.
                   11447:     my $lockhash = {
                   11448:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   11449:                                                        ':'.$env{'user.domain'},
                   11450:                    }; 
                   11451:     my $tries = 0;
                   11452:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11453:    
1.1172.2.79  raeburn  11454:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  11455:         $tries ++;
1.1172.2.79  raeburn  11456:         sleep(0.1);
1.749     raeburn  11457:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11458:     }
                   11459:     if ($gotlock eq 'ok') {
                   11460:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   11461:         my ($tmp)=keys(%curr_permissions);
                   11462:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   11463:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   11464:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   11465:             if (ref($curr_controls) eq 'HASH') {
                   11466:                 foreach my $control_item (keys(%{$curr_controls})) {
                   11467:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   11468:                     if (defined($todelete{$itemnum})) {
                   11469:                         push(@deletions,$file_name."\0".$control_item);
                   11470:                     } else {
                   11471:                         if (defined($changed_items{$itemnum})) {
                   11472:                             $new_control{$changed_items{$itemnum}} = $now;
                   11473:                             push(@deletions,$file_name."\0".$control_item);
                   11474:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   11475:                         } else {
                   11476:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   11477:                         }
                   11478:                     }
1.745     raeburn  11479:                 }
                   11480:             }
                   11481:         }
1.970     raeburn  11482:         my ($group);
                   11483:         if (&is_course($domain,$user)) {
                   11484:             ($group,my $file) = split(/\//,$file_name,2);
                   11485:         }
1.749     raeburn  11486:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   11487:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   11488:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   11489:         #  remove lock
                   11490:         my @del_lock = ($file_name."\0".'locked_access_records');
                   11491:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  11492:         my $sqlresult =
1.970     raeburn  11493:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  11494:                                     $group);
1.749     raeburn  11495:     } else {
                   11496:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  11497:     }
1.749     raeburn  11498:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  11499: }
                   11500: 
1.827     raeburn  11501: sub make_public_indefinitely {
                   11502:     my ($requrl) = @_;
                   11503:     my $now = time;
                   11504:     my $action = 'activate';
                   11505:     my $aclnum = 0;
                   11506:     if (&is_portfolio_url($requrl)) {
                   11507:         my (undef,$udom,$unum,$file_name,$group) =
                   11508:             &parse_portfolio_url($requrl);
                   11509:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   11510:         my %access_controls = &get_access_controls($current_perms,
                   11511:                                                    $group,$file_name);
                   11512:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11513:             my ($num,$scope,$end,$start) = 
                   11514:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   11515:             if ($scope eq 'public') {
                   11516:                 if ($start <= $now && $end == 0) {
                   11517:                     $action = 'none';
                   11518:                 } else {
                   11519:                     $action = 'update';
                   11520:                     $aclnum = $num;
                   11521:                 }
                   11522:                 last;
                   11523:             }
                   11524:         }
                   11525:         if ($action eq 'none') {
                   11526:              return 'ok';
                   11527:         } else {
                   11528:             my %changes;
                   11529:             my $newend = 0;
                   11530:             my $newstart = $now;
                   11531:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   11532:             $changes{$action}{$newkey} = {
                   11533:                 type => 'public',
                   11534:                 time => {
                   11535:                     start => $newstart,
                   11536:                     end   => $newend,
                   11537:                 },
                   11538:             };
                   11539:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11540:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   11541:             return $outcome;
                   11542:         }
                   11543:     } else {
                   11544:         return 'invalid';
                   11545:     }
                   11546: }
                   11547: 
1.745     raeburn  11548: #------------------------------------------------------Get Marked as Read Only
                   11549: 
                   11550: sub get_marked_as_readonly {
                   11551:     my ($domain,$user,$what,$group) = @_;
                   11552:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11553:     my @readonly_files;
1.629     banghart 11554:     my $cmp1=$what;
                   11555:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11556:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11557:         if (defined($group)) {
                   11558:             if ($file_name !~ m-^\Q$group\E/-) {
                   11559:                 next;
                   11560:             }
                   11561:         }
1.561     banghart 11562:         if (ref($value) eq "ARRAY"){
                   11563:             foreach my $stored_what (@{$value}) {
1.629     banghart 11564:                 my $cmp2=$stored_what;
1.759     albertel 11565:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11566:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11567:                 }
1.629     banghart 11568:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11569:                     push(@readonly_files, $file_name);
1.745     raeburn  11570:                     last;
1.563     banghart 11571:                 } elsif (!defined($what)) {
                   11572:                     push(@readonly_files, $file_name);
1.745     raeburn  11573:                     last;
1.561     banghart 11574:                 }
                   11575:             }
1.745     raeburn  11576:         }
1.561     banghart 11577:     }
                   11578:     return @readonly_files;
                   11579: }
1.577     banghart 11580: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11581: 
1.577     banghart 11582: sub get_marked_as_readonly_hash {
1.745     raeburn  11583:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11584:     my %readonly_files;
1.745     raeburn  11585:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11586:         if (defined($group)) {
                   11587:             if ($file_name !~ m-^\Q$group\E/-) {
                   11588:                 next;
                   11589:             }
                   11590:         }
1.577     banghart 11591:         if (ref($value) eq "ARRAY"){
                   11592:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11593:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11594:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11595:                         if ($lock_descriptor eq 'graded') {
                   11596:                             $readonly_files{$file_name} = 'graded';
                   11597:                         } elsif ($lock_descriptor eq 'handback') {
                   11598:                             $readonly_files{$file_name} = 'handback';
                   11599:                         } else {
                   11600:                             if (!exists($readonly_files{$file_name})) {
                   11601:                                 $readonly_files{$file_name} = 'locked';
                   11602:                             }
                   11603:                         }
1.745     raeburn  11604:                     }
1.750     banghart 11605:                 } 
1.577     banghart 11606:             }
                   11607:         } 
                   11608:     }
                   11609:     return %readonly_files;
                   11610: }
1.559     banghart 11611: # ------------------------------------------------------------ Unmark as Read Only
                   11612: 
                   11613: sub unmark_as_readonly {
1.629     banghart 11614:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11615:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11616:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11617:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11618:     my $symb_crs = $what;
                   11619:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11620:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11621:     my ($tmp)=keys(%current_permissions);
                   11622:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11623:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11624:     foreach my $file (@readonly_files) {
1.759     albertel 11625: 	my $clean_file = &declutter_portfile($file);
                   11626: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11627: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11628:         my @new_locks;
                   11629:         my @del_keys;
                   11630:         if (ref($current_locks) eq "ARRAY"){
                   11631:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11632:                 my $compare=$locker;
1.749     raeburn  11633:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11634:                     $compare=join('',@{$locker});
1.746     raeburn  11635:                     if ($compare ne $symb_crs) {
                   11636:                         push(@new_locks, $locker);
                   11637:                     }
1.563     banghart 11638:                 }
                   11639:             }
1.650     albertel 11640:             if (scalar(@new_locks) > 0) {
1.563     banghart 11641:                 $current_permissions{$file} = \@new_locks;
                   11642:             } else {
                   11643:                 push(@del_keys, $file);
1.613     albertel 11644:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11645:                 delete($current_permissions{$file});
1.563     banghart 11646:             }
                   11647:         }
1.561     banghart 11648:     }
1.613     albertel 11649:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11650:     return;
                   11651: }
1.512     banghart 11652: 
1.17      www      11653: # ------------------------------------------------------------ Directory lister
                   11654: 
                   11655: sub dirlist {
1.955     raeburn  11656:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11657:     $uri=~s/^\///;
                   11658:     $uri=~s/\/$//;
1.253     stredwic 11659:     my ($udom, $uname);
1.955     raeburn  11660:     if ($getuserdir) {
1.253     stredwic 11661:         $udom = $userdomain;
                   11662:         $uname = $username;
1.955     raeburn  11663:     } else {
                   11664:         (undef,$udom,$uname)=split(/\//,$uri);
                   11665:         if(defined($userdomain)) {
                   11666:             $udom = $userdomain;
                   11667:         }
                   11668:         if(defined($username)) {
                   11669:             $uname = $username;
                   11670:         }
1.253     stredwic 11671:     }
1.955     raeburn  11672:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11673: 
1.955     raeburn  11674:     $dirRoot = $perlvar{'lonDocRoot'};
                   11675:     if (defined($getpropath)) {
                   11676:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11677:         $dirRoot =~ s/\/$//;
1.955     raeburn  11678:     } elsif (defined($getuserdir)) {
                   11679:         my $subdir=$uname.'__';
                   11680:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11681:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11682:                    ."/$udom/$subdir/$uname";
                   11683:     } elsif (defined($alternateRoot)) {
                   11684:         $dirRoot = $alternateRoot;
1.751     banghart 11685:     }
1.253     stredwic 11686: 
                   11687:     if($udom) {
                   11688:         if($uname) {
1.1135    raeburn  11689:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11690:             if ($uhome eq 'no_host') {
                   11691:                 return ([],'no_host');
                   11692:             }
1.955     raeburn  11693:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11694:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11695:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11696:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11697:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11698:             } else {
                   11699:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11700:             }
1.605     matthew  11701:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11702:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11703:                 @listing_results = split(/:/,$listing);
                   11704:             } else {
                   11705:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11706:             }
1.1135    raeburn  11707:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11708:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11709:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11710:                 return ([],$listing);
                   11711:             } else {
                   11712:                 return (\@listing_results);
1.1135    raeburn  11713:             }
1.955     raeburn  11714:         } elsif(!$alternateRoot) {
1.1136    raeburn  11715:             my (%allusers,%listerror);
1.841     albertel 11716: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11717:  	    foreach my $tryserver (keys(%servers)) {
                   11718:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11719:                                   &escape($udom),$tryserver);
                   11720:                 if ($listing eq 'unknown_cmd') {
                   11721: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11722: 				      $udom, $tryserver);
                   11723:                 } else {
                   11724:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11725:                 }
1.841     albertel 11726: 		if ($listing eq 'unknown_cmd') {
                   11727: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11728: 				      $udom, $tryserver);
                   11729: 		    @listing_results = split(/:/,$listing);
                   11730: 		} else {
                   11731: 		    @listing_results =
                   11732: 			map { &unescape($_); } split(/:/,$listing);
                   11733: 		}
1.1136    raeburn  11734:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11735:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11736:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11737:                     $listerror{$tryserver} = $listing;
                   11738:                 } else {
1.841     albertel 11739: 		    foreach my $line (@listing_results) {
                   11740: 			my ($entry) = split(/&/,$line,2);
                   11741: 			$allusers{$entry} = 1;
                   11742: 		    }
                   11743: 		}
1.253     stredwic 11744:             }
1.1136    raeburn  11745:             my @alluserslist=();
1.800     albertel 11746:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11747:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11748:             }
1.1172.2.80  raeburn  11749:             if (!%listerror) {
                   11750:                 # no errors
                   11751:                 return (\@alluserslist);
                   11752:             } elsif (scalar(keys(%servers)) == 1) {
                   11753:                 # one library server, one error
                   11754:                 my ($key) = keys(%listerror);
                   11755:                 return (\@alluserslist, $listerror{$key});
                   11756:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11757:                 # con_lost indicates that we might miss data from at least one
                   11758:                 # library server
                   11759:                 return (\@alluserslist, 'con_lost');
                   11760:             } else {
                   11761:                 # multiple library servers and no con_lost -> data should be
                   11762:                 # complete.
                   11763:                 return (\@alluserslist);
                   11764:             }
                   11765: 
1.253     stredwic 11766:         } else {
1.1136    raeburn  11767:             return ([],'missing username');
1.253     stredwic 11768:         }
1.955     raeburn  11769:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11770:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11771:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11772:         return (\@all_domains);
1.955     raeburn  11773:     } else {
1.1136    raeburn  11774:         return ([],'missing domain');
1.275     stredwic 11775:     }
                   11776: }
                   11777: 
                   11778: # --------------------------------------------- GetFileTimestamp
                   11779: # This function utilizes dirlist and returns the date stamp for
                   11780: # when it was last modified.  It will also return an error of -1
                   11781: # if an error occurs
                   11782: 
                   11783: sub GetFileTimestamp {
1.955     raeburn  11784:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11785:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11786:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11787:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11788:                                     undef,$getuserdir);
                   11789:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11790:         return -1;
                   11791:     }
                   11792:     if (ref($fileref) eq 'ARRAY') {
                   11793:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11794:         # @stats contains first the filename, then the stat output
                   11795:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11796:     } else {
                   11797:         return -1;
1.253     stredwic 11798:     }
1.26      www      11799: }
                   11800: 
1.712     albertel 11801: sub stat_file {
                   11802:     my ($uri) = @_;
1.787     albertel 11803:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11804: 
1.955     raeburn  11805:     my ($udom,$uname,$file);
1.712     albertel 11806:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11807: 	($udom,$uname,$file) =
1.811     albertel 11808: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11809: 	$file = 'userfiles/'.$file;
                   11810:     }
                   11811:     if ($uri =~ m-^/res/-) {
                   11812: 	($udom,$uname) = 
1.807     albertel 11813: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11814: 	$file = $uri;
                   11815:     }
                   11816: 
                   11817:     if (!$udom || !$uname || !$file) {
                   11818: 	# unable to handle the uri
                   11819: 	return ();
                   11820:     }
1.956     raeburn  11821:     my $getpropath;
                   11822:     if ($file =~ /^userfiles\//) {
                   11823:         $getpropath = 1;
                   11824:     }
1.1136    raeburn  11825:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11826:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11827:         return ();
                   11828:     } else {
                   11829:         if (ref($listref) eq 'ARRAY') {
                   11830:             my @stats = split('&',$listref->[0]);
                   11831: 	    shift(@stats); #filename is first
                   11832: 	    return @stats;
                   11833:         }
1.712     albertel 11834:     }
                   11835:     return ();
                   11836: }
                   11837: 
1.26      www      11838: # -------------------------------------------------------- Value of a Condition
                   11839: 
1.713     albertel 11840: # gets the value of a specific preevaluated condition
                   11841: #    stored in the string  $env{user.state.<cid>}
                   11842: # or looks up a condition reference in the bighash and if if hasn't
                   11843: # already been evaluated recurses into docondval to get the value of
                   11844: # the condition, then memoizing it to 
                   11845: #   $env{user.state.<cid>.<condition>}
1.40      www      11846: sub directcondval {
                   11847:     my $number=shift;
1.620     albertel 11848:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11849: 	&Apache::lonuserstate::evalstate();
                   11850:     }
1.713     albertel 11851:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11852: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11853:     } elsif ($number =~ /^_/) {
                   11854: 	my $sub_condition;
                   11855: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11856: 		&GDBM_READER(),0640)) {
                   11857: 	    $sub_condition=$bighash{'conditions'.$number};
                   11858: 	    untie(%bighash);
                   11859: 	}
                   11860: 	my $value = &docondval($sub_condition);
1.949     raeburn  11861: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11862: 	return $value;
                   11863:     }
1.620     albertel 11864:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11865:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11866:     } else {
                   11867:        return 2;
                   11868:     }
                   11869: }
                   11870: 
1.713     albertel 11871: # get the collection of conditions for this resource
1.26      www      11872: sub condval {
                   11873:     my $condidx=shift;
1.54      www      11874:     my $allpathcond='';
1.713     albertel 11875:     foreach my $cond (split(/\|/,$condidx)) {
                   11876: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11877: 	    $allpathcond.=
                   11878: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11879: 	}
1.191     harris41 11880:     }
1.54      www      11881:     $allpathcond=~s/\|$//;
1.713     albertel 11882:     return &docondval($allpathcond);
                   11883: }
                   11884: 
                   11885: #evaluates an expression of conditions
                   11886: sub docondval {
                   11887:     my ($allpathcond) = @_;
                   11888:     my $result=0;
                   11889:     if ($env{'request.course.id'}
                   11890: 	&& defined($allpathcond)) {
                   11891: 	my $operand='|';
                   11892: 	my @stack;
                   11893: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11894: 	    if ($chunk eq '(') {
                   11895: 		push @stack,($operand,$result);
                   11896: 	    } elsif ($chunk eq ')') {
                   11897: 		my $before=pop @stack;
                   11898: 		if (pop @stack eq '&') {
                   11899: 		    $result=$result>$before?$before:$result;
                   11900: 		} else {
                   11901: 		    $result=$result>$before?$result:$before;
                   11902: 		}
                   11903: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11904: 		$operand=$chunk;
                   11905: 	    } else {
                   11906: 		my $new=directcondval($chunk);
                   11907: 		if ($operand eq '&') {
                   11908: 		    $result=$result>$new?$new:$result;
                   11909: 		} else {
                   11910: 		    $result=$result>$new?$result:$new;
                   11911: 		}
                   11912: 	    }
                   11913: 	}
1.26      www      11914:     }
                   11915:     return $result;
1.421     albertel 11916: }
                   11917: 
                   11918: # ---------------------------------------------------- Devalidate courseresdata
                   11919: 
                   11920: sub devalidatecourseresdata {
                   11921:     my ($coursenum,$coursedomain)=@_;
                   11922:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11923:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11924: }
                   11925: 
1.763     www      11926: 
1.200     www      11927: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11928: #
                   11929: #  Parameters:
                   11930: #      $coursenum    - Number of the course.
                   11931: #      $coursedomain - Domain at which the course was created.
                   11932: #  Returns:
                   11933: #     A hash of the course parameters along (I think) with timestamps
                   11934: #     and version info.
1.877     foxr     11935: 
1.624     albertel 11936: sub get_courseresdata {
                   11937:     my ($coursenum,$coursedomain)=@_;
1.200     www      11938:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11939:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11940:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11941:     my %dumpreply;
1.417     albertel 11942:     unless (defined($cached)) {
1.624     albertel 11943: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11944: 	$result=\%dumpreply;
1.251     albertel 11945: 	my ($tmp) = keys(%dumpreply);
                   11946: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11947: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11948: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11949: 	    return $tmp;
1.416     albertel 11950: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11951: 	    $result=undef;
1.599     albertel 11952: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11953: 	}
                   11954:     }
1.624     albertel 11955:     return $result;
                   11956: }
                   11957: 
1.633     albertel 11958: sub devalidateuserresdata {
                   11959:     my ($uname,$udom)=@_;
                   11960:     my $hashid="$udom:$uname";
                   11961:     &devalidate_cache_new('userres',$hashid);
                   11962: }
                   11963: 
1.624     albertel 11964: sub get_userresdata {
                   11965:     my ($uname,$udom)=@_;
                   11966:     #most student don\'t have any data set, check if there is some data
                   11967:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11968: 
                   11969:     my $hashid="$udom:$uname";
                   11970:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11971:     if (!defined($cached)) {
                   11972: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11973: 	$result=\%resourcedata;
                   11974: 	&do_cache_new('userres',$hashid,$result,600);
                   11975:     }
                   11976:     my ($tmp)=keys(%$result);
                   11977:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11978: 	return $result;
                   11979:     }
                   11980:     #error 2 occurs when the .db doesn't exist
                   11981:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11982:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11983: 	    &logthis("<font color=\"blue\">WARNING:".
                   11984: 		     " Trying to get resource data for ".
                   11985: 		     $uname." at ".$udom.": ".
                   11986: 		     $tmp."</font>");
                   11987:         }
1.624     albertel 11988:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11989: 	#&EXT_cache_set($udom,$uname);
                   11990: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11991: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11992:     }
                   11993:     return $tmp;
                   11994: }
1.879     foxr     11995: #----------------------------------------------- resdata - return resource data
                   11996: #  Purpose:
                   11997: #    Return resource data for either users or for a course.
                   11998: #  Parameters:
                   11999: #     $name      - Course/user name.
                   12000: #     $domain    - Name of the domain the user/course is registered on.
                   12001: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   12002: #     @which     - Array of names of resources desired.
                   12003: #  Returns:
                   12004: #     The value of the first reasource in @which that is found in the
                   12005: #     resource hash.
                   12006: #  Exceptional Conditions:
                   12007: #     If the $type passed in is not valid (not the string 'course' or 
                   12008: #     'user', an undefined  reference is returned.
                   12009: #     If none of the resources are found, an undef is returned
1.624     albertel 12010: sub resdata {
                   12011:     my ($name,$domain,$type,@which)=@_;
                   12012:     my $result;
                   12013:     if ($type eq 'course') {
                   12014: 	$result=&get_courseresdata($name,$domain);
                   12015:     } elsif ($type eq 'user') {
                   12016: 	$result=&get_userresdata($name,$domain);
                   12017:     }
                   12018:     if (!ref($result)) { return $result; }    
1.251     albertel 12019:     foreach my $item (@which) {
1.927     albertel 12020: 	if (defined($result->{$item->[0]})) {
                   12021: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 12022: 	}
1.250     albertel 12023:     }
1.291     albertel 12024:     return undef;
1.200     www      12025: }
                   12026: 
1.1172.2.146.  .1(raebu 12027:22): sub get_domain_lti {
                   12028:22):     my ($cdom,$context) = @_;
          .4(raebu 12029:22):     my ($name,$cachename,%lti);
          .1(raebu 12030:22):     if ($context eq 'consumer') {
                   12031:22):         $name = 'ltitools';
                   12032:22):     } elsif ($context eq 'provider') {
                   12033:22):         $name = 'lti';
          .4(raebu 12034:22):     } elsif ($context eq 'linkprot') {
                   12035:22):         $name = 'ltisec';
          .1(raebu 12036:22):     } else {
                   12037:22):         return %lti;
                   12038:22):     }
          .4(raebu 12039:22):     if ($context eq 'linkprot') {
                   12040:22):         $cachename = $context;
                   12041:22):     } else {
                   12042:22):         $cachename = $name;
                   12043:22):     }
                   12044:22):     my ($result,$cached)=&is_cached_new($cachename,$cdom);
          .1(raebu 12045:22):     if (defined($cached)) {
                   12046:22):         if (ref($result) eq 'HASH') {
                   12047:22):             %lti = %{$result};
                   12048:22):         }
                   12049:22):     } else {
                   12050:22):         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   12051:22):         if (ref($domconfig{$name}) eq 'HASH') {
          .4(raebu 12052:22):             if ($context eq 'linkprot') {
                   12053:22):                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
                   12054:22):                     %lti = %{$domconfig{$name}{'linkprot'}};
                   12055:22):                 }
                   12056:22):             } else {
                   12057:22):                 %lti = %{$domconfig{$name}};
                   12058:22):             }
          .1(raebu 12059:22):         }
                   12060:22):         my $cachetime = 24*60*60;
          .4(raebu 12061:22):         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
          .1(raebu 12062:22):     }
                   12063:22):     return %lti;
                   12064:22): }
                   12065:22): 
                   12066:22): sub get_course_lti {
          .13(raeb 12067:-23):     my ($cnum,$cdom,$context) = @_;
                   12068:-23):     my ($name,$cachename,%lti);
                   12069:-23):     if ($context eq 'consumer') {
                   12070:-23):         $name = 'ltitools';
                   12071:-23):         $cachename = 'courseltitools';
                   12072:-23):     } elsif ($context eq 'provider') {
                   12073:-23):         $name = 'lti';
                   12074:-23):         $cachename = 'courselti';
                   12075:-23):     } else {
                   12076:-23):         return %lti;
                   12077:-23):     }
          .1(raebu 12078:22):     my $hashid=$cdom.'_'.$cnum;
          .13(raeb 12079:-23):     my ($result,$cached)=&is_cached_new($cachename,$hashid);
          .1(raebu 12080:22):     if (defined($cached)) {
                   12081:22):         if (ref($result) eq 'HASH') {
          .13(raeb 12082:-23):             %lti = %{$result};
          .1(raebu 12083:22):         }
                   12084:22):     } else {
          .13(raeb 12085:-23):         %lti = &dump($name,$cdom,$cnum,undef,undef,undef,1);
          .1(raebu 12086:22):         my $cachetime = 24*60*60;
          .13(raeb 12087:-23):         &do_cache_new($cachename,$hashid,\%lti,$cachetime);
          .1(raebu 12088:22):     }
          .13(raeb 12089:-23):     return %lti;
          .1(raebu 12090:22): }
                   12091:22): 
          .3(raebu 12092:22): sub courselti_itemid {
                   12093:22):     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
                   12094:22):     my ($chome,$itemid);
                   12095:22):     $chome = &homeserver($cnum,$cdom);
                   12096:22):     return if ($chome eq 'no_host');
                   12097:22):     if (ref($params) eq 'HASH') {
                   12098:22):         my $rep;
                   12099:22):         if (grep { $_ eq $chome } current_machine_ids()) {
                   12100:22):             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
                   12101:22):         } else {
                   12102:22):             my $escurl = &escape($url);
                   12103:22):             my $escmethod = &escape($method);
                   12104:22):             my $items = &freeze_escape($params);
                   12105:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
                   12106:22):         }
                   12107:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   12108:22):                 ($rep eq 'unknown_cmd')) {
                   12109:22):             $itemid = $rep;
                   12110:22):         }
                   12111:22):     }
                   12112:22):     return $itemid;
                   12113:22): }
                   12114:22): 
                   12115:22): sub domainlti_itemid {
                   12116:22):     my ($cdom,$url,$method,$params,$context) = @_;
                   12117:22):     my ($primary_id,$itemid);
                   12118:22):     $primary_id = &domain($cdom,'primary');
                   12119:22):     return if ($primary_id eq '');
                   12120:22):     if (ref($params) eq 'HASH') {
                   12121:22):         my $rep;
                   12122:22):         if (grep { $_ eq $primary_id } current_machine_ids()) {
                   12123:22):             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
                   12124:22):         } else {
                   12125:22):             my $cnum = '';
                   12126:22):             my $escurl = &escape($url);
                   12127:22):             my $escmethod = &escape($method);
                   12128:22):             my $items = &freeze_escape($params);
                   12129:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
                   12130:22):         }
                   12131:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   12132:22):                 ($rep eq 'unknown_cmd')) {
                   12133:22):             $itemid = $rep;
                   12134:22):         }
                   12135:22):     }
                   12136:22):     return $itemid;
                   12137:22): }
                   12138:22): 
          .15(raeb 12139:-23): sub get_ltitools_id {
                   12140:-23):     my ($context,$cdom,$cnum,$title) = @_;
                   12141:-23):     my ($lockhash,$tries,$gotlock,$id,$error);
                   12142:-23): 
                   12143:-23):     # get lock on ltitools db
                   12144:-23):     $lockhash = {
                   12145:-23):                    lock => $env{'user.name'}.
                   12146:-23):                            ':'.$env{'user.domain'},
                   12147:-23):                 };
                   12148:-23):     $tries = 0;
                   12149:-23):     if ($context eq 'domain') {
                   12150:-23):         $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
                   12151:-23):     } else {
                   12152:-23):         $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
                   12153:-23):     }
                   12154:-23):     while (($gotlock ne 'ok') && ($tries<10)) {
                   12155:-23):         $tries ++;
                   12156:-23):         sleep (0.1);
                   12157:-23):         if ($context eq 'domain') {
                   12158:-23):             $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
                   12159:-23):         } else {
                   12160:-23):             $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
                   12161:-23):         }
                   12162:-23):     }
                   12163:-23):     if ($gotlock eq 'ok') {
                   12164:-23):         my %currids;
                   12165:-23):         if ($context eq 'domain') {
                   12166:-23):             %currids = &dump_dom('ltitools',$cdom);
                   12167:-23):         } else {
                   12168:-23):             %currids = &dump('ltitools',$cdom,$cnum);
                   12169:-23):         }
                   12170:-23):         if ($currids{'lock'}) {
                   12171:-23):             delete($currids{'lock'});
                   12172:-23):             if (keys(%currids)) {
                   12173:-23):                 my @curr = sort { $a <=> $b } keys(%currids);
                   12174:-23):                 if ($curr[-1] =~ /^\d+$/) {
                   12175:-23):                     $id = 1 + $curr[-1];
                   12176:-23):                 }
                   12177:-23):             } else {
                   12178:-23):                 $id = 1;
                   12179:-23):             }
                   12180:-23):             if ($id) {
                   12181:-23):                 if ($context eq 'domain') {
                   12182:-23):                     unless (&newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
                   12183:-23):                         $error = 'nostore';
                   12184:-23):                     }
                   12185:-23):                 } else {
                   12186:-23):                     unless (&newput('ltitools',{ $id => $title },$cdom,$cnum) eq 'ok') {
                   12187:-23):                         $error = 'nostore';
                   12188:-23):                     }
                   12189:-23):                 }
                   12190:-23):             } else {
                   12191:-23):                 $error = 'nonumber';
                   12192:-23):             }
                   12193:-23):         }
                   12194:-23):         my $dellockoutcome;
                   12195:-23):         if ($context eq 'domain') {
                   12196:-23):             $dellockoutcome = &del_dom('ltitools',['lock'],$cdom);
                   12197:-23):         } else {
                   12198:-23):             $dellockoutcome = &del('ltitools',['lock'],$cdom,$cnum);
                   12199:-23):         }
                   12200:-23):     } else {
                   12201:-23):         $error = 'nolock';
                   12202:-23):     }
                   12203:-23):     return ($id,$error);
                   12204:-23): }
                   12205:-23): 
          .9(raebu 12206:23): sub count_supptools {
                   12207:23):     my ($cnum,$cdom,$ignorecache,$reload)=@_;
1.1172.2.31  raeburn  12208:     my $hashid=$cnum.':'.$cdom;
1.1172.2.146.  .9(raebu 12209:23):     my ($numexttools,$cached);
1.1172.2.31  raeburn  12210:     unless ($ignorecache) {
1.1172.2.146.  .9(raebu 12211:23):         ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
1.1172.2.31  raeburn  12212:     }
                   12213:     unless (defined($cached)) {
                   12214:         my $chome=&homeserver($cnum,$cdom);
1.1172.2.146.  .9(raebu 12215:23):         $numexttools = 0;
1.1172.2.31  raeburn  12216:         unless ($chome eq 'no_host') {
1.1172.2.146.  .9(raebu 12217:23):             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
                   12218:23):             if (ref($supplemental) eq 'HASH') {
                   12219:23):                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   12220:23):                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
                   12221:23):                         if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   12222:23):                             $numexttools ++;
                   12223:23):                         }
                   12224:23):                     }
                   12225:23):                 }
                   12226:23):             }
1.1172.2.31  raeburn  12227:         }
1.1172.2.146.  .9(raebu 12228:23):         &do_cache_new('supptools',$hashid,$numexttools,600);
1.1172.2.31  raeburn  12229:     }
1.1172.2.146.  .9(raebu 12230:23):     return $numexttools;
                   12231:23): }
                   12232:23): 
                   12233:23): sub has_unhidden_suppfiles {
                   12234:23):     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   12235:23):     my $hashid=$cnum.':'.$cdom;
                   12236:23):     my ($showsupp,$cached);
                   12237:23):     unless ($ignorecache) {
                   12238:23):         ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
                   12239:23):     }
                   12240:23):     unless (defined($cached)) {
                   12241:23):         my $chome=&homeserver($cnum,$cdom);
                   12242:23):         unless ($chome eq 'no_host') {
                   12243:23):             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
                   12244:23):             if (ref($supplemental) eq 'HASH') {
                   12245:23):                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   12246:23):                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
                   12247:23):                         next if ($key =~ /\.sequence$/);
                   12248:23):                         if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
                   12249:23):                             foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
                   12250:23):                                 unless ($supplemental->{'hidden'}->{$id}) {
                   12251:23):                                     $showsupp = 1;
                   12252:23):                                     last;
                   12253:23):                                 }
                   12254:23):                             }
                   12255:23):                         }
                   12256:23):                         last if ($showsupp);
                   12257:23):                     }
                   12258:23):                 }
                   12259:23):             }
                   12260:23):         }
                   12261:23):         &do_cache_new('showsupp',$hashid,$showsupp,600);
                   12262:23):     }
                   12263:23):     return $showsupp;
1.1172.2.31  raeburn  12264: }
                   12265: 
1.379     matthew  12266: #
                   12267: # EXT resource caching routines
                   12268: #
                   12269: 
1.1172.2.146.  .1(raebu 12270:22): {
                   12271:22): # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   12272:22): #
                   12273:22): # The course for which we cache
                   12274:22): my $cachedmapkey='';
                   12275:22): # The cached recursive maps for this course
                   12276:22): my %cachedmaps=();
                   12277:22): # When this was last done
                   12278:22): my $cachedmaptime='';
                   12279:22): 
1.379     matthew  12280: sub clear_EXT_cache_status {
1.383     albertel 12281:     &delenv('cache.EXT.');
1.379     matthew  12282: }
                   12283: 
                   12284: sub EXT_cache_status {
                   12285:     my ($target_domain,$target_user) = @_;
1.383     albertel 12286:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 12287:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  12288:         # We know already the user has no data
                   12289:         return 1;
                   12290:     } else {
                   12291:         return 0;
                   12292:     }
                   12293: }
                   12294: 
                   12295: sub EXT_cache_set {
                   12296:     my ($target_domain,$target_user) = @_;
1.383     albertel 12297:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  12298:     #&appenv({$cachename => time});
1.379     matthew  12299: }
                   12300: 
1.28      www      12301: # --------------------------------------------------------- Value of a Variable
1.58      www      12302: sub EXT {
1.715     albertel 12303: 
1.1172.2.28  raeburn  12304:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      12305:     unless ($varname) { return ''; }
1.218     albertel 12306:     #get real user name/domain, courseid and symb
                   12307:     my $courseid;
1.359     albertel 12308:     my $publicuser;
1.427     www      12309:     if ($symbparm) {
                   12310: 	$symbparm=&get_symb_from_alias($symbparm);
                   12311:     }
1.218     albertel 12312:     if (!($uname && $udom)) {
1.790     albertel 12313:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 12314:       if (!$symbparm) {	$symbparm=$cursymb; }
                   12315:     } else {
1.620     albertel 12316: 	$courseid=$env{'request.course.id'};
1.218     albertel 12317:     }
1.48      www      12318:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   12319:     my $rest;
1.320     albertel 12320:     if (defined($therest[0])) {
1.48      www      12321:        $rest=join('.',@therest);
                   12322:     } else {
                   12323:        $rest='';
                   12324:     }
1.320     albertel 12325: 
1.57      www      12326:     my $qualifierrest=$qualifier;
                   12327:     if ($rest) { $qualifierrest.='.'.$rest; }
                   12328:     my $spacequalifierrest=$space;
                   12329:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      12330:     if ($realm eq 'user') {
1.48      www      12331: # --------------------------------------------------------------- user.resource
                   12332: 	if ($space eq 'resource') {
1.651     albertel 12333: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   12334: 		  || defined($Apache::lonhomework::parsing_a_task))
                   12335: 		 &&
1.1172.2.142  raeburn  12336: 		 ($symbparm eq &symbread()) ) {
1.744     albertel 12337: 		# if we are in the middle of processing the resource the
                   12338: 		# get the value we are planning on committing
                   12339:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   12340:                     return $Apache::lonhomework::results{$qualifierrest};
                   12341:                 } else {
                   12342:                     return $Apache::lonhomework::history{$qualifierrest};
                   12343:                 }
1.335     albertel 12344: 	    } else {
1.359     albertel 12345: 		my %restored;
1.620     albertel 12346: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 12347: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   12348: 		} else {
                   12349: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   12350: 		}
1.335     albertel 12351: 		return $restored{$qualifierrest};
                   12352: 	    }
1.48      www      12353: # ----------------------------------------------------------------- user.access
                   12354:         } elsif ($space eq 'access') {
1.218     albertel 12355: 	    # FIXME - not supporting calls for a specific user
1.48      www      12356:             return &allowed($qualifier,$rest);
                   12357: # ------------------------------------------ user.preferences, user.environment
                   12358:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 12359: 	    if (($uname eq $env{'user.name'}) &&
                   12360: 		($udom eq $env{'user.domain'})) {
                   12361: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 12362: 	    } else {
1.359     albertel 12363: 		my %returnhash;
                   12364: 		if (!$publicuser) {
                   12365: 		    %returnhash=&userenvironment($udom,$uname,
                   12366: 						 $qualifierrest);
                   12367: 		}
1.218     albertel 12368: 		return $returnhash{$qualifierrest};
                   12369: 	    }
1.48      www      12370: # ----------------------------------------------------------------- user.course
                   12371:         } elsif ($space eq 'course') {
1.218     albertel 12372: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12373:             return $env{join('.',('request.course',$qualifier))};
1.48      www      12374: # ------------------------------------------------------------------- user.role
                   12375:         } elsif ($space eq 'role') {
1.218     albertel 12376: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12377:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      12378:             if ($qualifier eq 'value') {
                   12379: 		return $role;
                   12380:             } elsif ($qualifier eq 'extent') {
                   12381:                 return $where;
                   12382:             }
                   12383: # ----------------------------------------------------------------- user.domain
                   12384:         } elsif ($space eq 'domain') {
1.218     albertel 12385:             return $udom;
1.48      www      12386: # ------------------------------------------------------------------- user.name
                   12387:         } elsif ($space eq 'name') {
1.218     albertel 12388:             return $uname;
1.48      www      12389: # ---------------------------------------------------- Any other user namespace
1.29      www      12390:         } else {
1.359     albertel 12391: 	    my %reply;
                   12392: 	    if (!$publicuser) {
                   12393: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   12394: 	    }
                   12395: 	    return $reply{$qualifierrest};
1.48      www      12396:         }
1.236     www      12397:     } elsif ($realm eq 'query') {
                   12398: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 12399:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   12400: 						[$spacequalifierrest]);
1.620     albertel 12401: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      12402:    } elsif ($realm eq 'request') {
1.48      www      12403: # ------------------------------------------------------------- request.browser
                   12404:         if ($space eq 'browser') {
1.1145    bisitz   12405:             return $env{'browser.'.$qualifier};
1.57      www      12406: # ------------------------------------------------------------ request.filename
                   12407:         } else {
1.620     albertel 12408:             return $env{'request.'.$spacequalifierrest};
1.29      www      12409:         }
1.28      www      12410:     } elsif ($realm eq 'course') {
1.48      www      12411: # ---------------------------------------------------------- course.description
1.620     albertel 12412:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      12413:     } elsif ($realm eq 'resource') {
1.165     www      12414: 
1.620     albertel 12415: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 12416: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   12417: 	}
1.693     albertel 12418: 
1.1172.2.30  raeburn  12419:         if ($qualifier eq '') {
                   12420: 	    if ($space eq 'title') {
                   12421: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   12422: 	        return &gettitle($symbparm);
                   12423: 	    }
1.693     albertel 12424: 	
1.1172.2.30  raeburn  12425: 	    if ($space eq 'map') {
                   12426: 	        my ($map) = &decode_symb($symbparm);
                   12427: 	        return &symbread($map);
                   12428: 	    }
                   12429:             if ($space eq 'maptitle') {
                   12430:                 my ($map) = &decode_symb($symbparm);
                   12431:                 return &gettitle($map);
                   12432:             }
                   12433: 	    if ($space eq 'filename') {
                   12434: 	        if ($symbparm) {
                   12435: 		    return &clutter((&decode_symb($symbparm))[2]);
                   12436: 	        }
                   12437: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 12438: 	    }
1.1172.2.30  raeburn  12439: 
                   12440:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   12441:                 if ($space eq 'visibleparts') {
                   12442:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   12443:                     my $item;
                   12444:                     if (ref($navmap)) {
                   12445:                         my $res = $navmap->getBySymb($symbparm);
                   12446:                         my $parts = $res->parts();
                   12447:                         if (ref($parts) eq 'ARRAY') {
                   12448:                             $item = join(',',@{$parts});
                   12449:                         }
                   12450:                         undef($navmap);
                   12451:                     }
                   12452:                     return $item;
                   12453:                 }
                   12454:             }
                   12455:         }
1.693     albertel 12456: 
                   12457: 	my ($section, $group, @groups);
1.593     albertel 12458: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  12459:         if (($courseid eq '') && ($cid)) {
                   12460:             $courseid = $cid;
                   12461:         }
                   12462: 	if (($symbparm && $courseid) && 
                   12463: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      12464: 
1.218     albertel 12465: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      12466: 
1.60      www      12467: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 12468: 	    my $symbp=$symbparm;
1.735     albertel 12469: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 12470: 
                   12471: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   12472: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   12473: 
1.620     albertel 12474: 	    if (($env{'user.name'} eq $uname) &&
                   12475: 		($env{'user.domain'} eq $udom)) {
                   12476: 		$section=$env{'request.course.sec'};
1.733     raeburn  12477:                 @groups = split(/:/,$env{'request.course.groups'});  
                   12478:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 12479: 	    } else {
1.539     albertel 12480: 		if (! defined($usection)) {
1.551     albertel 12481: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 12482: 		} else {
                   12483: 		    $section = $usection;
                   12484: 		}
1.733     raeburn  12485:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12486: 	    }
                   12487: 
                   12488: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12489: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   12490: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12491: 
1.593     albertel 12492: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12493: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 12494: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12495: 
1.60      www      12496: # ----------------------------------------------------------- first, check user
1.624     albertel 12497: 
                   12498: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 12499: 				       ([$courselevelr,'resource'],
                   12500: 					[$courselevelm,'map'     ],
                   12501: 					[$courselevel, 'course'  ]));
1.931     albertel 12502: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12503: 
1.594     albertel 12504: # ------------------------------------------------ second, check some of course
1.684     raeburn  12505:             my $coursereply;
1.691     raeburn  12506:             if (@groups > 0) {
                   12507:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   12508:                                        $mapparm,$spacequalifierrest);
1.927     albertel 12509:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  12510:             }
1.96      www      12511: 
1.684     raeburn  12512: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12513: 				  $env{'course.'.$courseid.'.domain'},
                   12514: 				  'course',
                   12515: 				  ([$seclevelr,   'resource'],
                   12516: 				   [$seclevelm,   'map'     ],
                   12517: 				   [$seclevel,    'course'  ],
                   12518: 				   [$courselevelr,'resource']));
                   12519: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12520: 
1.60      www      12521: # ------------------------------------------------------ third, check map parms
1.218     albertel 12522: 	    my %parmhash=();
                   12523: 	    my $thisparm='';
                   12524: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12525: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12526: 		    &GDBM_READER(),0640)) {
1.218     albertel 12527: 		$thisparm=$parmhash{$symbparm};
                   12528: 		untie(%parmhash);
                   12529: 	    }
1.927     albertel 12530: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12531: 	}
1.594     albertel 12532: # ------------------------------------------ fourth, look in resource metadata
1.71      www      12533: 
1.1172.2.146.  .13(raeb 12534:-23):         my $what = $spacequalifierrest;
                   12535:-23):         $what=~s/\./\_/;
                   12536:-23):         my $filename;
1.282     albertel 12537: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12538: 	if ($symbparm) {
1.409     www      12539: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12540: 	} else {
1.620     albertel 12541: 	    $filename=$env{'request.filename'};
1.282     albertel 12542: 	}
1.1172.2.146.  .13(raeb 12543:-23):         my $toolsymb;
                   12544:-23):         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   12545:-23):             $toolsymb = $symbparm;
                   12546:-23):         }
                   12547:-23): 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 12548: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1172.2.146.  .13(raeb 12549:-23): 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 12550: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12551: 
1.1172.2.146.  .13(raeb 12552:-23): # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 12553: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12554: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12555: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12556: 				     $env{'course.'.$courseid.'.domain'},
                   12557: 				     'course',
1.927     albertel 12558: 				     ([$courselevelm,'map'   ],
                   12559: 				      [$courselevel, 'course']));
                   12560: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12561: 	}
1.145     www      12562: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12563: 	unless ($space eq '0') {
1.336     albertel 12564: 	    my @parts=split(/_/,$space);
                   12565: 	    my $id=pop(@parts);
                   12566: 	    my $part=join('_',@parts);
                   12567: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12568: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12569: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12570: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12571: 	}
1.395     albertel 12572: 	if ($recurse) { return undef; }
1.1172.2.146.  .13(raeb 12573:-23): 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 12574: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12575: # ---------------------------------------------------- Any other user namespace
                   12576:     } elsif ($realm eq 'environment') {
                   12577: # ----------------------------------------------------------------- environment
1.620     albertel 12578: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12579: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12580: 	} else {
1.770     albertel 12581: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12582: 		return '';
                   12583: 	    }
1.219     albertel 12584: 	    my %returnhash=&userenvironment($udom,$uname,
                   12585: 					    $spacequalifierrest);
                   12586: 	    return $returnhash{$spacequalifierrest};
                   12587: 	}
1.28      www      12588:     } elsif ($realm eq 'system') {
1.48      www      12589: # ----------------------------------------------------------------- system.time
                   12590: 	if ($space eq 'time') {
                   12591: 	    return time;
                   12592:         }
1.696     albertel 12593:     } elsif ($realm eq 'server') {
                   12594: # ----------------------------------------------------------------- system.time
                   12595: 	if ($space eq 'name') {
                   12596: 	    return $ENV{'SERVER_NAME'};
                   12597:         }
1.1172.2.146.  .1(raebu 12598:22):     } elsif ($realm eq 'client') {
                   12599:22):         if ($space eq 'remote_addr') {
                   12600:22):             return &get_requestor_ip();
                   12601:22):         }
1.28      www      12602:     }
1.48      www      12603:     return '';
1.61      www      12604: }
                   12605: 
1.927     albertel 12606: sub get_reply {
                   12607:     my ($reply_value) = @_;
1.940     raeburn  12608:     if (ref($reply_value) eq 'ARRAY') {
                   12609:         if (wantarray) {
                   12610: 	    return @$reply_value;
                   12611:         }
                   12612:         return $reply_value->[0];
                   12613:     } else {
                   12614:         return $reply_value;
1.927     albertel 12615:     }
                   12616: }
                   12617: 
1.691     raeburn  12618: sub check_group_parms {
                   12619:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   12620:     my @groupitems = ();
                   12621:     my $resultitem;
1.927     albertel 12622:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  12623:     foreach my $group (@{$groups}) {
                   12624:         foreach my $level (@levels) {
1.927     albertel 12625:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12626:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12627:         }
                   12628:     }
                   12629:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12630:                             $env{'course.'.$courseid.'.domain'},
                   12631:                                      'course',@groupitems);
                   12632:     return $coursereply;
                   12633: }
                   12634: 
1.1172.2.146.  .1(raebu 12635:22): sub get_map_hierarchy {
                   12636:22):     my ($mapname,$courseid) = @_;
                   12637:22):     my @recurseup = ();
                   12638:22):     if ($mapname) {
                   12639:22):         if (($cachedmapkey eq $courseid) &&
                   12640:22):             (abs($cachedmaptime-time)<5)) {
                   12641:22):             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12642:22):                 return @{$cachedmaps{$mapname}};
                   12643:22):             }
                   12644:22):         }
                   12645:22):         my $navmap = Apache::lonnavmaps::navmap->new();
                   12646:22):         if (ref($navmap)) {
                   12647:22):             @recurseup = $navmap->recurseup_maps($mapname);
                   12648:22):             undef($navmap);
                   12649:22):             $cachedmaps{$mapname} = \@recurseup;
                   12650:22):             $cachedmaptime=time;
                   12651:22):             $cachedmapkey=$courseid;
                   12652:22):         }
                   12653:22):     }
                   12654:22):     return @recurseup;
                   12655:22): }
                   12656:22): 
          .2(raebu 12657:22): }
          .1(raebu 12658:22): 
1.691     raeburn  12659: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12660:     my ($courseid,@groups) = @_;
                   12661:     @groups = sort(@groups);
1.691     raeburn  12662:     return @groups;
                   12663: }
                   12664: 
1.395     albertel 12665: sub packages_tab_default {
1.1172.2.146.  .13(raeb 12666:-23):     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 12667:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12668: 
                   12669:     my (@extension,@specifics,$do_default);
1.1172.2.146.  .13(raeb 12670:-23):     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 12671: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12672: 	if ($pack_type eq 'default') {
                   12673: 	    $do_default=1;
                   12674: 	} elsif ($pack_type eq 'extension') {
                   12675: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12676: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12677: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12678: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12679: 	}
                   12680:     }
                   12681:     # first look for a package that matches the requested part id
                   12682:     foreach my $package (@specifics) {
                   12683: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12684: 	next if ($pack_part ne $part);
                   12685: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12686: 	    return $packagetab{"$pack_type&$name&default"};
                   12687: 	}
                   12688:     }
                   12689:     # look for any possible matching non extension_ package
                   12690:     foreach my $package (@specifics) {
                   12691: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12692: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12693: 	    return $packagetab{"$pack_type&$name&default"};
                   12694: 	}
1.585     albertel 12695: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12696: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12697: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12698: 	}
                   12699:     }
1.738     albertel 12700:     # look for any posible extension_ match
                   12701:     foreach my $package (@extension) {
                   12702: 	my ($package,$pack_type)=@{$package};
                   12703: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12704: 	    return $packagetab{"$pack_type&$name&default"};
                   12705: 	}
                   12706: 	if (defined($packagetab{$package."&$name&default"})) {
                   12707: 	    return $packagetab{$package."&$name&default"};
                   12708: 	}
                   12709:     }
                   12710:     # look for a global default setting
                   12711:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12712: 	return $packagetab{"default&$name&default"};
                   12713:     }
1.395     albertel 12714:     return undef;
                   12715: }
                   12716: 
1.334     albertel 12717: sub add_prefix_and_part {
                   12718:     my ($prefix,$part)=@_;
                   12719:     my $keyroot;
                   12720:     if (defined($prefix) && $prefix !~ /^__/) {
                   12721: 	# prefix that has a part already
                   12722: 	$keyroot=$prefix;
                   12723:     } elsif (defined($prefix)) {
                   12724: 	# prefix that is missing a part
                   12725: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12726:     } else {
                   12727: 	# no prefix at all
                   12728: 	if (defined($part)) { $keyroot='_'.$part; }
                   12729:     }
                   12730:     return $keyroot;
                   12731: }
                   12732: 
1.71      www      12733: # ---------------------------------------------------------------- Get metadata
                   12734: 
1.599     albertel 12735: my %metaentry;
1.1070    www      12736: my %importedpartids;
1.1172.2.99  raeburn  12737: my %importedrespids;
1.71      www      12738: sub metadata {
1.1172.2.146.  .13(raeb 12739:-23):     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      12740:     $uri=&declutter($uri);
1.288     albertel 12741:     # if it is a non metadata possible uri return quickly
1.529     albertel 12742:     if (($uri eq '') || 
                   12743: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.146.  .1(raebu 12744:22): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12745:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12746: 	return undef;
                   12747:     }
1.1172.2.49  raeburn  12748:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12749: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12750: 	return undef;
1.288     albertel 12751:     }
1.73      www      12752:     my $filename=$uri;
                   12753:     $uri=~s/\.meta$//;
1.172     www      12754: #
                   12755: # Is the metadata already cached?
1.177     www      12756: # Look at timestamp of caching
1.172     www      12757: # Everything is cached by the main uri, libraries are never directly cached
                   12758: #
1.428     albertel 12759:     if (!defined($liburi)) {
1.599     albertel 12760: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12761: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12762:     }
1.1172.2.146.  .13(raeb 12763:-23): 
                   12764:-23): #
                   12765:-23): # If the uri is for an external tool the file from
                   12766:-23): # which metadata should be retrieved depends on whether
                   12767:-23): # the tool had been configured to be gradable (set in the Course
                   12768:-23): # Editor or Resource Editor).
                   12769:-23): #
                   12770:-23): # If a valid symb has been included as the third arg in the call
                   12771:-23): # to &metadata() that can be used to retrieve the value of
                   12772:-23): # parameter_0_gradable set for the resource, and included in the
                   12773:-23): # uploaded map containing the tool. The value is retrieved via
                   12774:-23): # &EXT(), if a valid symb is available.  Otherwise the value of
                   12775:-23): # gradable in the exttool_$marker.db file for the tool instance
                   12776:-23): # is retrieved via &get().
                   12777:-23): #
                   12778:-23): # When lonuserstate::traceroute() calls lonnet::EXT() for
                   12779:-23): # hiddenresource and encrypturl (during course initialization)
                   12780:-23): # the map-level parameter for resource.0.gradable included in the
                   12781:-23): # uploaded map containing the tool will not yet have been stored
                   12782:-23): # in the user_course_parms.db file for the user's session, so in
                   12783:-23): # this case fall back to retrieving gradable status from the
                   12784:-23): # exttool_$marker.db file.
                   12785:-23): #
                   12786:-23): # In order to avoid an infinite loop, &metadata() will return
                   12787:-23): # before a call to &EXT(), if the uri is for an external tool
                   12788:-23): # and the $what for which metadata is being requested is
                   12789:-23): # parameter_0_gradable or 0_gradable.
                   12790:-23): #
                   12791:-23): 
                   12792:-23):     if ($uri =~ /ext\.tool$/) {
                   12793:-23):         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   12794:-23):             return;
                   12795:-23):         } else {
                   12796:-23):             my ($checked,$use_passback);
                   12797:-23):             if ($toolsymb ne '') {
                   12798:-23):                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
                   12799:-23):                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
                   12800:-23):                     $checked = 1;
                   12801:-23):                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   12802:-23):                         $use_passback = 1;
                   12803:-23):                     }
                   12804:-23):                 }
                   12805:-23):             }
                   12806:-23):             unless ($checked) {
                   12807:-23):                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   12808:-23):                 $marker=~s/\D//g;
                   12809:-23):                 if ($marker) {
                   12810:-23):                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   12811:-23):                     $use_passback = $toolsettings{'gradable'};
                   12812:-23):                 }
                   12813:-23):             }
                   12814:-23):             if ($use_passback) {
                   12815:-23):                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   12816:-23):             } else {
                   12817:-23):                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   12818:-23):             }
                   12819:-23):         }
                   12820:-23):     }
                   12821:-23): 
1.428     albertel 12822:     {
1.1069    www      12823: # Imported parts would go here
1.1172.2.99  raeburn  12824:         my @origfiletagids=();
1.1069    www      12825:         my $importedparts=0;
1.1172.2.99  raeburn  12826: 
                   12827: # Imported responseids would go here
                   12828:         my $importedresponses=0;
1.172     www      12829: #
                   12830: # Is this a recursive call for a library?
                   12831: #
1.599     albertel 12832: #	if (! exists($metacache{$uri})) {
                   12833: #	    $metacache{$uri}={};
                   12834: #	}
1.924     albertel 12835: 	my $cachetime = 60*60;
1.171     www      12836:         if ($liburi) {
                   12837: 	    $liburi=&declutter($liburi);
                   12838:             $filename=$liburi;
1.401     bowersj2 12839:         } else {
1.599     albertel 12840: 	    &devalidate_cache_new('meta',$uri);
                   12841: 	    undef(%metaentry);
1.401     bowersj2 12842: 	}
1.140     www      12843:         my %metathesekeys=();
1.73      www      12844:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12845: 	my $metastring;
1.1140    www      12846: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12847: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12848: 	    $metastring = 
1.929     albertel 12849: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12850: 					  ('grade_target' => 'meta'));
                   12851: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12852: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12853:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12854: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12855: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12856: 	    $metastring=&getfile($file);
1.489     albertel 12857: 	}
1.208     albertel 12858:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12859:         my $token;
1.140     www      12860:         undef %metathesekeys;
1.71      www      12861:         while ($token=$parser->get_token) {
1.339     albertel 12862: 	    if ($token->[0] eq 'S') {
                   12863: 		if (defined($token->[2]->{'package'})) {
1.172     www      12864: #
                   12865: # This is a package - get package info
                   12866: #
1.339     albertel 12867: 		    my $package=$token->[2]->{'package'};
                   12868: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12869: 		    if (defined($token->[2]->{'id'})) { 
                   12870: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12871: 		    }
1.599     albertel 12872: 		    if ($metaentry{':packages'}) {
                   12873: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12874: 		    } else {
1.599     albertel 12875: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12876: 		    }
1.736     albertel 12877: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12878: 			my $part=$keyroot;
                   12879: 			$part=~s/^\_//;
1.736     albertel 12880: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12881: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12882: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12883: 			    # ignore package.tab specified default values
                   12884:                             # here &package_tab_default() will fetch those
                   12885: 			    if ($subp eq 'default') { next; }
1.736     albertel 12886: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12887: 			    my $unikey;
                   12888: 			    if ($pack =~ /_0$/) {
                   12889: 				$unikey='parameter_0_'.$name;
                   12890: 				$part=0;
                   12891: 			    } else {
                   12892: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12893: 			    }
1.339     albertel 12894: 			    if ($subp eq 'display') {
                   12895: 				$value.=' [Part: '.$part.']';
                   12896: 			    }
1.599     albertel 12897: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12898: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12899: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12900: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12901: 			    }
1.599     albertel 12902: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12903: 				$metaentry{':'.$unikey}=
                   12904: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12905: 			    }
1.339     albertel 12906: 			}
                   12907: 		    }
                   12908: 		} else {
1.172     www      12909: #
                   12910: # This is not a package - some other kind of start tag
1.339     albertel 12911: #
                   12912: 		    my $entry=$token->[1];
1.1068    www      12913: 		    my $unikey='';
1.175     www      12914: 
1.339     albertel 12915: 		    if ($entry eq 'import') {
1.175     www      12916: #
                   12917: # Importing a library here
1.339     albertel 12918: #
1.1067    www      12919:                         my $location=$parser->get_text('/import');
                   12920:                         my $dir=$filename;
                   12921:                         $dir=~s|[^/]*$||;
                   12922:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  12923: 
                   12924:                         my $importid=$token->[2]->{'id'};
1.1068    www      12925:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  12926: #
                   12927: # Check metadata for imported file to
                   12928: # see if it contained response items
                   12929: #
                   12930:                         my %currmetaentry = %metaentry;
                   12931:                         my $libresponseorder = &metadata($location,'responseorder');
                   12932:                         my $origfile;
                   12933:                         if ($libresponseorder ne '') {
                   12934:                             if ($#origfiletagids<0) {
                   12935:                                 undef(%importedrespids);
                   12936:                                 undef(%importedpartids);
                   12937:                             }
                   12938:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   12939:                             if (@{$importedrespids{$importid}} > 0) {
                   12940:                                 $importedresponses = 1;
                   12941: # We need to get the original file and the imported file to get the response order correct
                   12942: # Load and inspect original file
                   12943:                                 if ($#origfiletagids<0) {
                   12944:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12945:                                     $origfile=&getfile($origfilelocation);
                   12946:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12947:                                 }
                   12948:                             }
                   12949:                         }
                   12950: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12951: # hash populated for imported library file
                   12952:                         %metaentry = %currmetaentry;
                   12953:                         undef(%currmetaentry);
1.1068    www      12954:                         if ($importmode eq 'problem') {
1.1069    www      12955: # Import as problem/response
1.1068    www      12956:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12957:                         } elsif ($importmode eq 'part') {
                   12958: # Import as part(s)
1.1069    www      12959:                            $importedparts=1;
                   12960: # We need to get the original file and the imported file to get the part order correct
                   12961: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  12962: # Load and inspect original file if we didn't do that already
                   12963:                            if ($#origfiletagids<0) {
                   12964:                                undef(%importedrespids);
                   12965:                                undef(%importedpartids);
                   12966:                                if ($origfile eq '') {
                   12967:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12968:                                    $origfile=&getfile($origfilelocation);
                   12969:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12970:                                }
1.1070    www      12971:                            }
                   12972: 
1.1069    www      12973: # Load and inspect imported file
                   12974:                            my $impfile=&getfile($location);
                   12975:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12976:                            if ($#impfilepartids>=0) {
                   12977: # This problem had parts
1.1070    www      12978:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12979:                            } else {
                   12980: # Importing by turning a single problem into a problem part
                   12981: # It gets the import-tags ID as part-ID
                   12982:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12983:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12984:                            }
1.1068    www      12985:                         } else {
                   12986: # Normal import
                   12987:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12988:                            if (defined($token->[2]->{'id'})) {
                   12989:                               $unikey.='_'.$token->[2]->{'id'};
                   12990:                            }
1.1067    www      12991:                         }
                   12992: 
1.339     albertel 12993: 			if ($depthcount<20) {
1.736     albertel 12994: 			    my $metadata = 
1.1172.2.146.  .13(raeb 12995:-23): 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12996: 					  $depthcount+1);
                   12997: 			    foreach my $meta (split(',',$metadata)) {
                   12998: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12999: 				$metathesekeys{$meta}=1;
1.339     albertel 13000: 			    }
1.1068    www      13001: 			
                   13002:                         }
1.1067    www      13003: 		    } else {
                   13004: #
                   13005: # Not importing, some other kind of non-package, non-library start tag
                   13006: # 
                   13007:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13008:                         if (defined($token->[2]->{'id'})) {
                   13009:                             $unikey.='_'.$token->[2]->{'id'};
                   13010:                         }
1.339     albertel 13011: 			if (defined($token->[2]->{'name'})) { 
                   13012: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   13013: 			}
                   13014: 			$metathesekeys{$unikey}=1;
1.736     albertel 13015: 			foreach my $param (@{$token->[3]}) {
                   13016: 			    $metaentry{':'.$unikey.'.'.$param} =
                   13017: 				$token->[2]->{$param};
1.339     albertel 13018: 			}
                   13019: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 13020: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 13021: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   13022: 		 # only ws inside the tag, and not in default, so use default
                   13023: 		 # as value
1.599     albertel 13024: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 13025: 			} elsif ( $internaltext =~ /\S/ ) {
                   13026: 		  # something interesting inside the tag
                   13027: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 13028: 			} else {
1.908     albertel 13029: 		  # no interesting values, don't set a default
1.339     albertel 13030: 			}
1.172     www      13031: # end of not-a-package not-a-library import
1.339     albertel 13032: 		    }
1.172     www      13033: # end of not-a-package start tag
1.339     albertel 13034: 		}
1.172     www      13035: # the next is the end of "start tag"
1.339     albertel 13036: 	    }
                   13037: 	}
1.483     albertel 13038: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 13039: 	$extension = lc($extension);
                   13040: 	if ($extension eq 'htm') { $extension='html'; }
                   13041: 
1.737     albertel 13042: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 13043: 	    #no specific packages #how's our extension
                   13044: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 13045: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 13046: 					 \%metathesekeys);
                   13047: 	}
1.883     albertel 13048: 
                   13049: 	if (!exists($metaentry{':packages'})
                   13050: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 13051: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 13052: 		#no specific packages well let's get default then
                   13053: 		if ($key!~/^default&/) { next; }
1.488     albertel 13054: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 13055: 					     \%metathesekeys);
                   13056: 	    }
                   13057: 	}
1.338     www      13058: # are there custom rights to evaluate
1.599     albertel 13059: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 13060: 
1.338     www      13061:     #
                   13062:     # Importing a rights file here
1.339     albertel 13063:     #
                   13064: 	    unless ($depthcount) {
1.599     albertel 13065: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 13066: 		my $dir=$filename;
                   13067: 		$dir=~s|[^/]*$||;
                   13068: 		$location=&filelocation($dir,$location);
1.736     albertel 13069: 		my $rights_metadata =
1.1172.2.146.  .13(raeb 13070:-23): 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 13071: 			      $depthcount+1);
                   13072: 		foreach my $rights (split(',',$rights_metadata)) {
                   13073: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   13074: 		    $metathesekeys{$rights}=1;
1.339     albertel 13075: 		}
                   13076: 	    }
                   13077: 	}
1.737     albertel 13078: 	# uniqifiy package listing
                   13079: 	my %seen;
                   13080: 	my @uniq_packages =
                   13081: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   13082: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   13083: 
1.1172.2.99  raeburn  13084:         if (($importedresponses) || ($importedparts)) {
                   13085:             if ($importedparts) {
1.1070    www      13086: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  13087:                 $metaentry{':partorder'}='';
                   13088:                 $metathesekeys{'partorder'}=1;
                   13089:             }
                   13090:             if ($importedresponses) {
                   13091: # We had imported responses and need to rebuild responseorder
                   13092:                 $metaentry{':responseorder'}='';
                   13093:                 $metathesekeys{'responseorder'}=1;
                   13094:             }
                   13095:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   13096:                 my $origid = $origfiletagids[$index+1];
                   13097:                 if ($origfiletagids[$index] eq 'part') {
                   13098: # Original part, part of the problem
                   13099:                     if ($importedparts) {
                   13100:                         $metaentry{':partorder'}.=','.$origid;
                   13101:                     }
                   13102:                 } elsif ($origfiletagids[$index] eq 'import') {
                   13103:                     if ($importedparts) {
                   13104: # We have imported parts at this position
                   13105:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   13106:                     }
                   13107:                     if ($importedresponses) {
                   13108: # We have imported responses at this position
                   13109:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   13110:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   13111:                         }
                   13112:                     }
                   13113:                 } else {
                   13114: # Original response item, part of the problem
                   13115:                     if ($importedresponses) {
                   13116:                         $metaentry{':responseorder'}.=','.$origid;
                   13117:                     }
                   13118:                 }
                   13119:             }
                   13120:             if ($importedparts) {
                   13121:                 $metaentry{':partorder'}=~s/^\,//;
                   13122:             }
                   13123:             if ($importedresponses) {
                   13124:                 $metaentry{':responseorder'}=~s/^\,//;
                   13125:             }
1.1070    www      13126:         }
                   13127: 
1.737     albertel 13128: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 13129: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  13130: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 13131: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      13132: # this is the end of "was not already recently cached
1.71      www      13133:     }
1.599     albertel 13134:     return $metaentry{':'.$what};
1.261     albertel 13135: }
                   13136: 
1.488     albertel 13137: sub metadata_create_package_def {
1.483     albertel 13138:     my ($uri,$key,$package,$metathesekeys)=@_;
                   13139:     my ($pack,$name,$subp)=split(/\&/,$key);
                   13140:     if ($subp eq 'default') { next; }
                   13141:     
1.599     albertel 13142:     if (defined($metaentry{':packages'})) {
                   13143: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 13144:     } else {
1.599     albertel 13145: 	$metaentry{':packages'}=$package;
1.483     albertel 13146:     }
                   13147:     my $value=$packagetab{$key};
                   13148:     my $unikey;
                   13149:     $unikey='parameter_0_'.$name;
1.599     albertel 13150:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 13151:     $$metathesekeys{$unikey}=1;
1.599     albertel 13152:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   13153: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 13154:     }
1.599     albertel 13155:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   13156: 	$metaentry{':'.$unikey}=
                   13157: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 13158:     }
                   13159: }
                   13160: 
1.261     albertel 13161: sub metadata_generate_part0 {
                   13162:     my ($metadata,$metacache,$uri) = @_;
                   13163:     my %allnames;
1.737     albertel 13164:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 13165: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 13166: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   13167: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 13168: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 13169: 	    $allnames{$name}=$part;
                   13170: 	  }
                   13171: 	}
                   13172:     }
                   13173:     foreach my $name (keys(%allnames)) {
                   13174:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 13175:       my $key=":parameter_0_$name";
1.261     albertel 13176:       $$metacache{"$key.part"}='0';
                   13177:       $$metacache{"$key.name"}=$name;
1.428     albertel 13178:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 13179: 					   $allnames{$name}.'_'.$name.
                   13180: 					   '.type'};
1.428     albertel 13181:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 13182: 			     '.display'};
1.644     www      13183:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 13184:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 13185:       $$metacache{"$key.display"}=$olddis;
                   13186:     }
1.71      www      13187: }
                   13188: 
1.764     albertel 13189: # ------------------------------------------------------ Devalidate title cache
                   13190: 
                   13191: sub devalidate_title_cache {
                   13192:     my ($url)=@_;
                   13193:     if (!$env{'request.course.id'}) { return; }
                   13194:     my $symb=&symbread($url);
                   13195:     if (!$symb) { return; }
                   13196:     my $key=$env{'request.course.id'}."\0".$symb;
                   13197:     &devalidate_cache_new('title',$key);
                   13198: }
                   13199: 
1.1014    droeschl 13200: # ------------------------------------------------- Get the title of a course
                   13201: 
                   13202: sub current_course_title {
                   13203:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   13204: }
1.301     www      13205: # ------------------------------------------------- Get the title of a resource
                   13206: 
                   13207: sub gettitle {
                   13208:     my $urlsymb=shift;
                   13209:     my $symb=&symbread($urlsymb);
1.534     albertel 13210:     if ($symb) {
1.620     albertel 13211: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 13212: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 13213: 	if (defined($cached)) { 
                   13214: 	    return $result;
                   13215: 	}
1.534     albertel 13216: 	my ($map,$resid,$url)=&decode_symb($symb);
                   13217: 	my $title='';
1.907     albertel 13218: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   13219: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   13220: 	} else {
                   13221: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   13222: 		    &GDBM_READER(),0640)) {
                   13223: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   13224: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   13225: 		untie(%bighash);
                   13226: 	    }
1.534     albertel 13227: 	}
                   13228: 	$title=~s/\&colon\;/\:/gs;
                   13229: 	if ($title) {
1.1159    www      13230: # Remember both $symb and $title for dynamic metadata
                   13231:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      13232:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      13233: # Cache this title and then return it
1.599     albertel 13234: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 13235: 	}
                   13236: 	$urlsymb=$url;
                   13237:     }
                   13238:     my $title=&metadata($urlsymb,'title');
                   13239:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   13240:     return $title;
1.301     www      13241: }
1.613     albertel 13242: 
1.614     albertel 13243: sub get_slot {
                   13244:     my ($which,$cnum,$cdom)=@_;
                   13245:     if (!$cnum || !$cdom) {
1.790     albertel 13246: 	(undef,my $courseid)=&whichuser();
1.620     albertel 13247: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   13248: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 13249:     }
1.703     albertel 13250:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   13251:     my %slotinfo;
                   13252:     if (exists($remembered{$key})) {
                   13253: 	$slotinfo{$which} = $remembered{$key};
                   13254:     } else {
                   13255: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   13256: 	&Apache::lonhomework::showhash(%slotinfo);
                   13257: 	my ($tmp)=keys(%slotinfo);
                   13258: 	if ($tmp=~/^error:/) { return (); }
                   13259: 	$remembered{$key} = $slotinfo{$which};
                   13260:     }
1.616     albertel 13261:     if (ref($slotinfo{$which}) eq 'HASH') {
                   13262: 	return %{$slotinfo{$which}};
                   13263:     }
                   13264:     return $slotinfo{$which};
1.614     albertel 13265: }
1.1150    raeburn  13266: 
                   13267: sub get_reservable_slots {
                   13268:     my ($cnum,$cdom,$uname,$udom) = @_;
                   13269:     my $now = time;
                   13270:     my $reservable_info;
                   13271:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   13272:     if (exists($remembered{$key})) {
                   13273:         $reservable_info = $remembered{$key};
                   13274:     } else {
                   13275:         my %resv;
                   13276:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   13277:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   13278:         $reservable_info = \%resv;
                   13279:         $remembered{$key} = $reservable_info;
                   13280:     }
                   13281:     return $reservable_info;
                   13282: }
                   13283: 
                   13284: sub get_course_slots {
                   13285:     my ($cnum,$cdom) = @_;
                   13286:     my $hashid=$cnum.':'.$cdom;
                   13287:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   13288:     if (defined($cached)) {
                   13289:         if (ref($result) eq 'HASH') {
                   13290:             return %{$result};
                   13291:         }
                   13292:     } else {
                   13293:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   13294:         my ($tmp) = keys(%slots);
                   13295:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  13296:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  13297:             return %slots;
                   13298:         }
                   13299:     }
                   13300:     return;
                   13301: }
                   13302: 
                   13303: sub devalidate_slots_cache {
                   13304:     my ($cnum,$cdom)=@_;
                   13305:     my $hashid=$cnum.':'.$cdom;
                   13306:     &devalidate_cache_new('allslots',$hashid);
                   13307: }
                   13308: 
1.1172.2.8  raeburn  13309: sub get_coursechange {
                   13310:     my ($cdom,$cnum) = @_;
                   13311:     if ($cdom eq '' || $cnum eq '') {
                   13312:         return unless ($env{'request.course.id'});
                   13313:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   13314:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   13315:     }
                   13316:     my $hashid=$cdom.'_'.$cnum;
                   13317:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   13318:     if ((defined($cached)) && ($change ne '')) {
                   13319:         return $change;
                   13320:     } else {
                   13321:         my %crshash;
                   13322:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   13323:         if ($crshash{'internal.contentchange'} eq '') {
                   13324:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13325:             if ($change eq '') {
                   13326:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13327:                 $change = $crshash{'internal.created'};
                   13328:             }
                   13329:         } else {
                   13330:             $change = $crshash{'internal.contentchange'};
                   13331:         }
                   13332:         my $cachetime = 600;
                   13333:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   13334:     }
                   13335:     return $change;
                   13336: }
                   13337: 
                   13338: sub devalidate_coursechange_cache {
1.1172.2.146.  .9(raebu 13339:23):     my ($cdom,$cnum)=@_;
                   13340:23):     my $hashid=$cdom.'_'.$cnum;
1.1172.2.8  raeburn  13341:     &devalidate_cache_new('crschange',$hashid);
                   13342: }
                   13343: 
1.1172.2.146.  .9(raebu 13344:23): sub get_suppchange {
                   13345:23):     my ($cdom,$cnum) = @_;
                   13346:23):     if ($cdom eq '' || $cnum eq '') {
                   13347:23):         return unless ($env{'request.course.id'});
                   13348:23):         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   13349:23):         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   13350:23):     }
                   13351:23):     my $hashid=$cdom.'_'.$cnum;
                   13352:23):     my ($change,$cached)=&is_cached_new('suppchange',$hashid);
                   13353:23):     if ((defined($cached)) && ($change ne '')) {
                   13354:23):         return $change;
                   13355:23):     } else {
                   13356:23):         my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
                   13357:23):         if ($crshash{'internal.supplementalchange'} eq '') {
                   13358:23):             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13359:23):             if ($change eq '') {
                   13360:23):                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13361:23):                 $change = $crshash{'internal.created'};
                   13362:23):             }
                   13363:23):         } else {
                   13364:23):             $change = $crshash{'internal.supplementalchange'};
                   13365:23):         }
                   13366:23):         my $cachetime = 600;
                   13367:23):         &do_cache_new('suppchange',$hashid,$change,$cachetime);
                   13368:23):     }
                   13369:23):     return $change;
                   13370:23): }
                   13371:23): 
                   13372:23): sub devalidate_suppchange_cache {
                   13373:23):     my ($cdom,$cnum)=@_;
                   13374:23):     my $hashid=$cdom.'_'.$cnum;
                   13375:23):     &devalidate_cache_new('suppchange',$hashid);
                   13376:23): }
                   13377:23): 
                   13378:23): sub update_supp_caches {
                   13379:23):     my ($cdom,$cnum) = @_;
                   13380:23):     my %servers = &internet_dom_servers($cdom);
                   13381:23):     my @ids=&current_machine_ids();
                   13382:23):     foreach my $server (keys(%servers)) {
                   13383:23):         next if (grep(/^\Q$server\E$/,@ids));
                   13384:23):         my $hashid=$cnum.':'.$cdom;
                   13385:23):         my $cachekey = &escape('showsupp').':'.&escape($hashid);
                   13386:23):         &remote_devalidate_cache($server,[$cachekey]);
                   13387:23):     }
                   13388:23):     &has_unhidden_suppfiles($cnum,$cdom,1,1);
                   13389:23):     &count_supptools($cnum,$cdom,1);
                   13390:23):     my $now = time;
                   13391:23):     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   13392:23):         &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
                   13393:23):     }
                   13394:23):     &put('environment',{'internal.supplementalchange' => $now},
                   13395:23):          $cdom,$cnum);
                   13396:23):     &Apache::lonnet::appenv(
                   13397:23):         {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
                   13398:23):     &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
                   13399:23): }
                   13400:23): 
1.31      www      13401: # ------------------------------------------------- Update symbolic store links
                   13402: 
                   13403: sub symblist {
                   13404:     my ($mapname,%newhash)=@_;
1.438     www      13405:     $mapname=&deversion(&declutter($mapname));
1.31      www      13406:     my %hash;
1.620     albertel 13407:     if (($env{'request.course.fn'}) && (%newhash)) {
                   13408:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 13409:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  13410: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 13411: 		next if ($url eq 'last_known'
                   13412: 			 && $env{'form.no_update_last_known'});
                   13413: 		$hash{declutter($url)}=&encode_symb($mapname,
                   13414: 						    $newhash{$url}->[1],
                   13415: 						    $newhash{$url}->[0]);
1.191     harris41 13416:             }
1.31      www      13417:             if (untie(%hash)) {
                   13418: 		return 'ok';
                   13419:             }
                   13420:         }
                   13421:     }
                   13422:     return 'error';
1.212     www      13423: }
                   13424: 
                   13425: # --------------------------------------------------------------- Verify a symb
                   13426: 
                   13427: sub symbverify {
1.1172.2.11  raeburn  13428:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      13429:     my $thisfn=$thisurl;
1.439     www      13430:     $thisfn=&declutter($thisfn);
1.215     www      13431: # direct jump to resource in page or to a sequence - will construct own symbs
                   13432:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   13433: # check URL part
1.409     www      13434:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      13435: 
1.431     www      13436:     unless ($url eq $thisfn) { return 0; }
1.213     www      13437: 
1.216     www      13438:     $symb=&symbclean($symb);
1.510     www      13439:     $thisurl=&deversion($thisurl);
1.439     www      13440:     $thisfn=&deversion($thisfn);
1.213     www      13441: 
                   13442:     my %bighash;
                   13443:     my $okay=0;
1.431     www      13444: 
1.620     albertel 13445:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13446:                             &GDBM_READER(),0640)) {
1.1032    raeburn  13447:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   13448:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  13449:             if ($map =~ m{^uploaded/.+\.page$}) {
                   13450:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   13451:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   13452:             }
                   13453:         }
                   13454:         my $ids;
1.1172.2.122  raeburn  13455:         if ($map =~ m{^uploaded/.+\.page$}) {
                   13456:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  13457:         } else {
                   13458:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  13459:         }
1.1102    raeburn  13460:         unless ($ids) {
1.1172.2.13  raeburn  13461:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  13462:             $ids=$bighash{$idkey};
1.216     www      13463:         }
                   13464:         if ($ids) {
                   13465: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  13466:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   13467:                 $symb =~ s/\?.+$//;
                   13468:             }
1.800     albertel 13469: 	    foreach my $id (split(/\,/,$ids)) {
                   13470: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      13471:                if (
                   13472:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  13473:    eq $symb) {
1.1172.2.11  raeburn  13474:                    if (ref($encstate)) {
                   13475:                        $$encstate = $bighash{'encrypted_'.$id};
                   13476:                    }
1.1172.2.13  raeburn  13477:                    if (($env{'request.role.adv'}) ||
                   13478:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  13479:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  13480:                        $okay=1;
                   13481:                        last;
                   13482:                    }
                   13483:                }
                   13484:            }
1.216     www      13485:         }
1.213     www      13486: 	untie(%bighash);
                   13487:     }
                   13488:     return $okay;
1.31      www      13489: }
                   13490: 
1.210     www      13491: # --------------------------------------------------------------- Clean-up symb
                   13492: 
                   13493: sub symbclean {
                   13494:     my $symb=shift;
1.568     albertel 13495:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      13496: # remove version from map
                   13497:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      13498: 
1.210     www      13499: # remove version from URL
                   13500:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      13501: 
1.507     www      13502: # remove wrapper
                   13503: 
1.510     www      13504:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 13505:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      13506:     return $symb;
1.409     www      13507: }
                   13508: 
                   13509: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 13510: 
                   13511: sub encode_symb {
                   13512:     my ($map,$resid,$url)=@_;
                   13513:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   13514: }
1.409     www      13515: 
                   13516: sub decode_symb {
1.568     albertel 13517:     my $symb=shift;
                   13518:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   13519:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      13520:     return (&fixversion($map),$resid,&fixversion($url));
                   13521: }
                   13522: 
                   13523: sub fixversion {
                   13524:     my $fn=shift;
1.609     banghart 13525:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      13526:     my %bighash;
                   13527:     my $uri=&clutter($fn);
1.620     albertel 13528:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      13529: # is this cached?
1.599     albertel 13530:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      13531:     if (defined($cached)) { return $result; }
                   13532: # unfortunately not cached, or expired
1.620     albertel 13533:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      13534: 	    &GDBM_READER(),0640)) {
                   13535:  	if ($bighash{'version_'.$uri}) {
                   13536:  	    my $version=$bighash{'version_'.$uri};
1.444     www      13537:  	    unless (($version eq 'mostrecent') || 
                   13538: 		    ($version==&getversion($uri))) {
1.440     www      13539:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   13540:  	    }
                   13541:  	}
                   13542:  	untie %bighash;
1.413     www      13543:     }
1.599     albertel 13544:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      13545: }
                   13546: 
                   13547: sub deversion {
                   13548:     my $url=shift;
                   13549:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   13550:     return $url;
1.210     www      13551: }
                   13552: 
1.31      www      13553: # ------------------------------------------------------ Return symb list entry
                   13554: 
                   13555: sub symbread {
1.1172.2.126  raeburn  13556:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128  raeburn  13557:         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  13558:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128  raeburn  13559:     if (defined($env{$cache_str})) {
1.1172.2.126  raeburn  13560:         unless (ref($possibles) eq 'HASH') {
                   13561:             if ($ignorecachednull) {
                   13562:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   13563:             } else {
                   13564:                 return $env{$cache_str};
                   13565:             }
1.1172.2.66  raeburn  13566:         }
                   13567:     }
1.242     www      13568: # no filename provided? try from environment
1.1172.2.54  raeburn  13569:     unless ($thisfn) {
1.620     albertel 13570:         if ($env{'request.symb'}) {
1.1172.2.128  raeburn  13571:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  13572:         }
                   13573:         $thisfn=$env{'request.filename'};
1.44      www      13574:     }
1.569     albertel 13575:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13576: # is that filename actually a symb? Verify, clean, and return
                   13577:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13578: 	if (&symbverify($thisfn,$1)) {
1.1172.2.128  raeburn  13579: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13580: 	}
1.242     www      13581:     }
1.44      www      13582:     $thisfn=declutter($thisfn);
1.31      www      13583:     my %hash;
1.37      www      13584:     my %bighash;
                   13585:     my $syval='';
1.620     albertel 13586:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.1172.2.128  raeburn  13587:         unless ($ignoresymbdb) {
1.1172.2.126  raeburn  13588:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   13589:                           &GDBM_READER(),0640)) {
1.1172.2.146.  .7(raebu 13590:22): 	        $syval=$hash{$thisfn};
1.1172.2.126  raeburn  13591:                 untie(%hash);
                   13592:             }
1.1172.2.128  raeburn  13593:             if ($syval && $checkforblock) {
                   13594:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126  raeburn  13595:                 if (@blockers) {
                   13596:                     $syval='';
                   13597:                 }
                   13598:             }
1.37      www      13599:         }
                   13600: # ---------------------------------------------------------- There was an entry
                   13601:         if ($syval) {
1.601     albertel 13602: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13603: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13604: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13605: 		    #return $env{$cache_str}='';
1.601     albertel 13606: 		#}    
                   13607: 		#$syval.=$1;
                   13608: 	    #}
1.37      www      13609:         } else {
                   13610: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13611:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13612:                             &GDBM_READER(),0640)) {
1.37      www      13613: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13614:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13615:               unless ($ids) { 
                   13616:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13617:               }
                   13618:               unless ($ids) {
                   13619: # alias?
                   13620: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13621:               }
1.37      www      13622:               if ($ids) {
                   13623: # ------------------------------------------------------------------- Has ID(s)
                   13624:                  my @possibilities=split(/\,/,$ids);
1.39      www      13625:                  if ($#possibilities==0) {
                   13626: # ----------------------------------------------- There is only one possibility
1.37      www      13627: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13628: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13629: 						    $resid,$thisfn);
1.1172.2.66  raeburn  13630:                      if (ref($possibles) eq 'HASH') {
1.1172.2.126  raeburn  13631:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   13632:                              $possibles->{$syval} = 1;
                   13633:                          }
1.1172.2.66  raeburn  13634:                      }
                   13635:                      if ($checkforblock) {
1.1172.2.126  raeburn  13636:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127  raeburn  13637:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126  raeburn  13638:                              if (@blockers) {
                   13639:                                  $syval = '';
                   13640:                                  untie(%bighash);
                   13641:                                  return $env{$cache_str}='';
                   13642:                              }
1.1172.2.66  raeburn  13643:                          }
                   13644:                      }
                   13645:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      13646: # ------------------------------------------ There is more than one possibility
                   13647:                      my $realpossible=0;
1.800     albertel 13648:                      foreach my $id (@possibilities) {
                   13649: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  13650:                          my $canaccess;
                   13651:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13652:                              $canaccess = 1;
                   13653:                          } else {
                   13654:                              $canaccess = &allowed('bre',$file);
                   13655:                          }
                   13656:                          if ($canaccess) {
                   13657:          		     my ($mapid,$resid)=split(/\./,$id);
                   13658:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13659:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13660:                                                              $resid,$thisfn);
1.1172.2.126  raeburn  13661:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127  raeburn  13662:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  13663:                                  if ($checkforblock) {
1.1172.2.127  raeburn  13664:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126  raeburn  13665:                                      if (@blockers > 0) {
                   13666:                                          $syval = '';
                   13667:                                      } else {
1.1172.2.66  raeburn  13668:                                          $syval = $poss_syval;
                   13669:                                          $realpossible++;
                   13670:                                      }
                   13671:                                  } else {
                   13672:                                      $syval = $poss_syval;
                   13673:                                      $realpossible++;
                   13674:                                  }
1.1172.2.126  raeburn  13675:                                  if ($syval) {
                   13676:                                      if (ref($possibles) eq 'HASH') {
                   13677:                                          $possibles->{$syval} = 1;
                   13678:                                      }
                   13679:                                  }
1.1172.2.66  raeburn  13680:                              }
1.39      www      13681: 			 }
1.191     harris41 13682:                      }
1.39      www      13683: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13684:                  } else {
                   13685:                      $syval='';
1.37      www      13686:                  }
                   13687: 	      }
1.1172.2.66  raeburn  13688:               untie(%bighash);
1.481     raeburn  13689:            }
1.31      www      13690:         }
1.62      www      13691:         if ($syval) {
1.1172.2.128  raeburn  13692: 	    return $env{$cache_str}=$syval;
1.62      www      13693:         }
1.31      www      13694:     }
1.949     raeburn  13695:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13696:     return $env{$cache_str}='';
1.31      www      13697: }
                   13698: 
                   13699: # ---------------------------------------------------------- Return random seed
                   13700: 
1.32      www      13701: sub numval {
                   13702:     my $txt=shift;
                   13703:     $txt=~tr/A-J/0-9/;
                   13704:     $txt=~tr/a-j/0-9/;
                   13705:     $txt=~tr/K-T/0-9/;
                   13706:     $txt=~tr/k-t/0-9/;
                   13707:     $txt=~tr/U-Z/0-5/;
                   13708:     $txt=~tr/u-z/0-5/;
                   13709:     $txt=~s/\D//g;
1.564     albertel 13710:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13711:     return int($txt);
1.368     albertel 13712: }
                   13713: 
1.484     albertel 13714: sub numval2 {
                   13715:     my $txt=shift;
                   13716:     $txt=~tr/A-J/0-9/;
                   13717:     $txt=~tr/a-j/0-9/;
                   13718:     $txt=~tr/K-T/0-9/;
                   13719:     $txt=~tr/k-t/0-9/;
                   13720:     $txt=~tr/U-Z/0-5/;
                   13721:     $txt=~tr/u-z/0-5/;
                   13722:     $txt=~s/\D//g;
                   13723:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13724:     my $total;
                   13725:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13726:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13727:     return int($total);
                   13728: }
                   13729: 
1.575     albertel 13730: sub numval3 {
                   13731:     use integer;
                   13732:     my $txt=shift;
                   13733:     $txt=~tr/A-J/0-9/;
                   13734:     $txt=~tr/a-j/0-9/;
                   13735:     $txt=~tr/K-T/0-9/;
                   13736:     $txt=~tr/k-t/0-9/;
                   13737:     $txt=~tr/U-Z/0-5/;
                   13738:     $txt=~tr/u-z/0-5/;
                   13739:     $txt=~s/\D//g;
                   13740:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13741:     my $total;
                   13742:     foreach my $val (@txts) { $total+=$val; }
                   13743:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13744:     return $total;
                   13745: }
                   13746: 
1.675     albertel 13747: sub digest {
                   13748:     my ($data)=@_;
                   13749:     my $digest=&Digest::MD5::md5($data);
                   13750:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13751:     my ($e,$f);
                   13752:     {
                   13753:         use integer;
                   13754:         $e=($a+$b);
                   13755:         $f=($c+$d);
                   13756:         if ($_64bit) {
                   13757:             $e=(($e<<32)>>32);
                   13758:             $f=(($f<<32)>>32);
                   13759:         }
                   13760:     }
                   13761:     if (wantarray) {
                   13762: 	return ($e,$f);
                   13763:     } else {
                   13764: 	my $g;
                   13765: 	{
                   13766: 	    use integer;
                   13767: 	    $g=($e+$f);
                   13768: 	    if ($_64bit) {
                   13769: 		$g=(($g<<32)>>32);
                   13770: 	    }
                   13771: 	}
                   13772: 	return $g;
                   13773:     }
                   13774: }
                   13775: 
1.368     albertel 13776: sub latest_rnd_algorithm_id {
1.675     albertel 13777:     return '64bit5';
1.366     albertel 13778: }
1.32      www      13779: 
1.503     albertel 13780: sub get_rand_alg {
                   13781:     my ($courseid)=@_;
1.790     albertel 13782:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13783:     if ($courseid) {
1.620     albertel 13784: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13785:     }
                   13786:     return &latest_rnd_algorithm_id();
                   13787: }
                   13788: 
1.562     albertel 13789: sub validCODE {
                   13790:     my ($CODE)=@_;
                   13791:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13792:     return 0;
                   13793: }
                   13794: 
1.491     albertel 13795: sub getCODE {
1.620     albertel 13796:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13797:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13798: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13799: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13800: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13801:     }
                   13802:     return undef;
                   13803: }
1.1133    foxr     13804: #
                   13805: #  Determines the random seed for a specific context:
                   13806: #
                   13807: # parameters:
                   13808: #   symb      - in course context the symb for the seed.
                   13809: #   course_id - The course id of the form domain_coursenum.
                   13810: #   domain    - Domain for the user.
                   13811: #   course    - Course for the user.
                   13812: #   cenv      - environment of the course.
                   13813: #
                   13814: # NOTE:
                   13815: #   All parameters are picked out of the environment if missing
                   13816: #   or not defined.
                   13817: #   If a symb cannot be determined the current time is used instead.
                   13818: #
                   13819: #  For a given well defined symb, courside, domain, username,
                   13820: #  and course environment, the seed is reproducible.
                   13821: #
1.31      www      13822: sub rndseed {
1.1133    foxr     13823:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13824:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13825:     if (!defined($symb)) {
1.366     albertel 13826: 	unless ($symb=$wsymb) { return time; }
                   13827:     }
1.1146    foxr     13828:     if (!defined $courseid) { 
                   13829: 	$courseid=$wcourseid; 
                   13830:     }
                   13831:     if (!defined $domain) { $domain=$wdomain; }
                   13832:     if (!defined $username) { $username=$wusername }
1.1133    foxr     13833: 
                   13834:     my $which;
                   13835:     if (defined($cenv->{'rndseed'})) {
                   13836: 	$which = $cenv->{'rndseed'};
                   13837:     } else {
                   13838: 	$which =&get_rand_alg($courseid);
                   13839:     }
1.491     albertel 13840:     if (defined(&getCODE())) {
1.675     albertel 13841: 	if ($which eq '64bit5') {
                   13842: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   13843: 	} elsif ($which eq '64bit4') {
1.575     albertel 13844: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   13845: 	} else {
                   13846: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   13847: 	}
1.675     albertel 13848:     } elsif ($which eq '64bit5') {
                   13849: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 13850:     } elsif ($which eq '64bit4') {
                   13851: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 13852:     } elsif ($which eq '64bit3') {
                   13853: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 13854:     } elsif ($which eq '64bit2') {
                   13855: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13856:     } elsif ($which eq '64bit') {
                   13857: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13858:     }
                   13859:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13860: }
                   13861: 
                   13862: sub rndseed_32bit {
                   13863:     my ($symb,$courseid,$domain,$username)=@_;
                   13864:     {
                   13865: 	use integer;
                   13866: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13867: 	my $symbseed=numval($symb) << 22;
                   13868: 	my $namechck=unpack("%32C*",$username) << 17;
                   13869: 	my $nameseed=numval($username) << 12;
                   13870: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13871: 	my $courseseed=unpack("%32C*",$courseid);
                   13872: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13873: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13874: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13875: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13876: 	return $num;
                   13877:     }
                   13878: }
                   13879: 
                   13880: sub rndseed_64bit {
                   13881:     my ($symb,$courseid,$domain,$username)=@_;
                   13882:     {
                   13883: 	use integer;
                   13884: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13885: 	my $symbseed=numval($symb) << 10;
                   13886: 	my $namechck=unpack("%32S*",$username);
                   13887: 	
                   13888: 	my $nameseed=numval($username) << 21;
                   13889: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13890: 	my $courseseed=unpack("%32S*",$courseid);
                   13891: 	
                   13892: 	my $num1=$symbchck+$symbseed+$namechck;
                   13893: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13894: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13895: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13896: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13897: 	return "$num1,$num2";
1.155     albertel 13898:     }
1.366     albertel 13899: }
                   13900: 
1.443     albertel 13901: sub rndseed_64bit2 {
                   13902:     my ($symb,$courseid,$domain,$username)=@_;
                   13903:     {
                   13904: 	use integer;
                   13905: 	# strings need to be an even # of cahracters long, it it is odd the
                   13906:         # last characters gets thrown away
                   13907: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13908: 	my $symbseed=numval($symb) << 10;
                   13909: 	my $namechck=unpack("%32S*",$username.' ');
                   13910: 	
                   13911: 	my $nameseed=numval($username) << 21;
1.501     albertel 13912: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13913: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13914: 	
                   13915: 	my $num1=$symbchck+$symbseed+$namechck;
                   13916: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13917: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13918: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13919: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13920: 	return "$num1,$num2";
                   13921:     }
                   13922: }
                   13923: 
                   13924: sub rndseed_64bit3 {
                   13925:     my ($symb,$courseid,$domain,$username)=@_;
                   13926:     {
                   13927: 	use integer;
                   13928: 	# strings need to be an even # of cahracters long, it it is odd the
                   13929:         # last characters gets thrown away
                   13930: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13931: 	my $symbseed=numval2($symb) << 10;
                   13932: 	my $namechck=unpack("%32S*",$username.' ');
                   13933: 	
                   13934: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13935: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13936: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13937: 	
                   13938: 	my $num1=$symbchck+$symbseed+$namechck;
                   13939: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13940: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13941: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13942: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13943: 	
1.503     albertel 13944: 	return "$num1:$num2";
1.443     albertel 13945:     }
                   13946: }
                   13947: 
1.575     albertel 13948: sub rndseed_64bit4 {
                   13949:     my ($symb,$courseid,$domain,$username)=@_;
                   13950:     {
                   13951: 	use integer;
                   13952: 	# strings need to be an even # of cahracters long, it it is odd the
                   13953:         # last characters gets thrown away
                   13954: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13955: 	my $symbseed=numval3($symb) << 10;
                   13956: 	my $namechck=unpack("%32S*",$username.' ');
                   13957: 	
                   13958: 	my $nameseed=numval3($username) << 21;
                   13959: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13960: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13961: 	
                   13962: 	my $num1=$symbchck+$symbseed+$namechck;
                   13963: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13964: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13965: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13966: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13967: 	
1.575     albertel 13968: 	return "$num1:$num2";
                   13969:     }
                   13970: }
                   13971: 
1.675     albertel 13972: sub rndseed_64bit5 {
                   13973:     my ($symb,$courseid,$domain,$username)=@_;
                   13974:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13975:     return "$num1:$num2";
                   13976: }
                   13977: 
1.366     albertel 13978: sub rndseed_CODE_64bit {
                   13979:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13980:     {
1.366     albertel 13981: 	use integer;
1.443     albertel 13982: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13983: 	my $symbseed=numval2($symb);
1.491     albertel 13984: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13985: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13986: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13987: 	my $num1=$symbseed+$CODEchck;
                   13988: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13989: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13990: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13991: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13992: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13993: 	return "$num1:$num2";
1.366     albertel 13994:     }
                   13995: }
                   13996: 
1.575     albertel 13997: sub rndseed_CODE_64bit4 {
                   13998:     my ($symb,$courseid,$domain,$username)=@_;
                   13999:     {
                   14000: 	use integer;
                   14001: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   14002: 	my $symbseed=numval3($symb);
                   14003: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   14004: 	my $CODEseed=numval3(&getCODE());
                   14005: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14006: 	my $num1=$symbseed+$CODEchck;
                   14007: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 14008: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   14009: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 14010: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   14011: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   14012: 	return "$num1:$num2";
                   14013:     }
                   14014: }
                   14015: 
1.675     albertel 14016: sub rndseed_CODE_64bit5 {
                   14017:     my ($symb,$courseid,$domain,$username)=@_;
                   14018:     my $code = &getCODE();
                   14019:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   14020:     return "$num1:$num2";
                   14021: }
                   14022: 
1.366     albertel 14023: sub setup_random_from_rndseed {
                   14024:     my ($rndseed)=@_;
1.503     albertel 14025:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  14026: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   14027:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   14028:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   14029:         } else {
                   14030:             &Math::Random::random_set_seed($num1,$num2);
                   14031:         }
1.366     albertel 14032:     } else {
                   14033: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 14034:     }
1.36      albertel 14035: }
                   14036: 
1.474     albertel 14037: sub latest_receipt_algorithm_id {
1.835     albertel 14038:     return 'receipt3';
1.474     albertel 14039: }
                   14040: 
1.480     www      14041: sub recunique {
                   14042:     my $fucourseid=shift;
                   14043:     my $unique;
1.835     albertel 14044:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   14045: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 14046: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      14047:     } else {
                   14048: 	$unique=$perlvar{'lonReceipt'};
                   14049:     }
                   14050:     return unpack("%32C*",$unique);
                   14051: }
                   14052: 
                   14053: sub recprefix {
                   14054:     my $fucourseid=shift;
                   14055:     my $prefix;
1.835     albertel 14056:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   14057: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 14058: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      14059:     } else {
                   14060: 	$prefix=$perlvar{'lonHostID'};
                   14061:     }
                   14062:     return unpack("%32C*",$prefix);
                   14063: }
                   14064: 
1.76      www      14065: sub ireceipt {
1.474     albertel 14066:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 14067: 
                   14068:     my $return =&recprefix($fucourseid).'-';
                   14069: 
                   14070:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   14071: 	$env{'request.state'} eq 'construct') {
                   14072: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   14073: 	return $return;
                   14074:     }
                   14075: 
1.76      www      14076:     my $cuname=unpack("%32C*",$funame);
                   14077:     my $cudom=unpack("%32C*",$fudom);
                   14078:     my $cucourseid=unpack("%32C*",$fucourseid);
                   14079:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      14080:     my $cunique=&recunique($fucourseid);
1.474     albertel 14081:     my $cpart=unpack("%32S*",$part);
1.835     albertel 14082:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   14083: 
1.790     albertel 14084: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 14085: 			       
                   14086: 	$return.= ($cunique%$cuname+
                   14087: 		   $cunique%$cudom+
                   14088: 		   $cusymb%$cuname+
                   14089: 		   $cusymb%$cudom+
                   14090: 		   $cucourseid%$cuname+
                   14091: 		   $cucourseid%$cudom+
                   14092: 		   $cpart%$cuname+
                   14093: 		   $cpart%$cudom);
                   14094:     } else {
                   14095: 	$return.= ($cunique%$cuname+
                   14096: 		   $cunique%$cudom+
                   14097: 		   $cusymb%$cuname+
                   14098: 		   $cusymb%$cudom+
                   14099: 		   $cucourseid%$cuname+
                   14100: 		   $cucourseid%$cudom);
                   14101:     }
                   14102:     return $return;
1.76      www      14103: }
                   14104: 
                   14105: sub receipt {
1.474     albertel 14106:     my ($part)=@_;
1.790     albertel 14107:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 14108:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      14109: }
1.260     ng       14110: 
1.790     albertel 14111: sub whichuser {
                   14112:     my ($passedsymb)=@_;
                   14113:     my ($symb,$courseid,$domain,$name,$publicuser);
                   14114:     if (defined($env{'form.grade_symb'})) {
                   14115: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   14116: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   14117: 	if (!$allowed &&
                   14118: 	    exists($env{'request.course.sec'}) &&
                   14119: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   14120: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   14121: 			      '/'.$env{'request.course.sec'});
                   14122: 	}
                   14123: 	if ($allowed) {
                   14124: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   14125: 	    $courseid=$tmp_courseid;
                   14126: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   14127: 	    ($name)=&get_env_multiple('form.grade_username');
                   14128: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   14129: 	}
                   14130:     }
                   14131:     if (!$passedsymb) {
                   14132: 	$symb=&symbread();
                   14133:     } else {
                   14134: 	$symb=$passedsymb;
                   14135:     }
                   14136:     $courseid=$env{'request.course.id'};
                   14137:     $domain=$env{'user.domain'};
                   14138:     $name=$env{'user.name'};
                   14139:     if ($name eq 'public' && $domain eq 'public') {
                   14140: 	if (!defined($env{'form.username'})) {
                   14141: 	    $env{'form.username'}.=time.rand(10000000);
                   14142: 	}
                   14143: 	$name.=$env{'form.username'};
                   14144:     }
                   14145:     return ($symb,$courseid,$domain,$name,$publicuser);
                   14146: 
                   14147: }
                   14148: 
1.36      albertel 14149: # ------------------------------------------------------------ Serves up a file
1.472     albertel 14150: # returns either the contents of the file or 
                   14151: # -1 if the file doesn't exist
1.481     raeburn  14152: #
                   14153: # if the target is a file that was uploaded via DOCS, 
                   14154: # a check will be made to see if a current copy exists on the local server,
                   14155: # if it does this will be served, otherwise a copy will be retrieved from
                   14156: # the home server for the course and stored in /home/httpd/html/userfiles on
                   14157: # the local server.   
1.472     albertel 14158: 
1.36      albertel 14159: sub getfile {
1.538     albertel 14160:     my ($file) = @_;
1.609     banghart 14161:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 14162:     &repcopy($file);
                   14163:     return &readfile($file);
                   14164: }
                   14165: 
                   14166: sub repcopy_userfile {
                   14167:     my ($file)=@_;
1.1142    raeburn  14168:     my $londocroot = $perlvar{'lonDocRoot'};
                   14169:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  14170:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 14171:     my ($cdom,$cnum,$filename) = 
1.811     albertel 14172: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 14173:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   14174:     if (-e "$file") {
1.828     www      14175: # we already have a local copy, check it out
1.538     albertel 14176: 	my @fileinfo = stat($file);
1.828     www      14177: 	my $rtncode;
                   14178: 	my $info;
1.538     albertel 14179: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 14180: 	if ($lwpresp ne 'ok') {
1.828     www      14181: # there is no such file anymore, even though we had a local copy
1.482     albertel 14182: 	    if ($rtncode eq '404') {
1.538     albertel 14183: 		unlink($file);
1.482     albertel 14184: 	    }
                   14185: 	    return -1;
                   14186: 	}
                   14187: 	if ($info < $fileinfo[9]) {
1.828     www      14188: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  14189: 	    return 'ok';
1.828     www      14190: 	} else {
                   14191: # the file is outdated, get rid of it
                   14192: 	    unlink($file);
1.482     albertel 14193: 	}
1.828     www      14194:     }
                   14195: # one way or the other, at this point, we don't have the file
                   14196: # construct the correct path for the file
                   14197:     my @parts = ($cdom,$cnum); 
                   14198:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   14199: 	push @parts, split(/\//,$1);
                   14200:     }
                   14201:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   14202:     foreach my $part (@parts) {
                   14203: 	$path .= '/'.$part;
                   14204: 	if (!-e $path) {
                   14205: 	    mkdir($path,0770);
1.482     albertel 14206: 	}
                   14207:     }
1.828     www      14208: # now the path exists for sure
                   14209: # get a user agent
                   14210:     my $ua=new LWP::UserAgent;
                   14211:     my $transferfile=$file.'.in.transfer';
                   14212: # FIXME: this should flock
                   14213:     if (-e $transferfile) { return 'ok'; }
                   14214:     my $request;
                   14215:     $uri=~s/^\///;
1.980     raeburn  14216:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  14217:     my $hostname = &hostname($homeserver);
1.980     raeburn  14218:     my $protocol = $protocol{$homeserver};
                   14219:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  14220:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      14221:     my $response=$ua->request($request,$transferfile);
                   14222: # did it work?
                   14223:     if ($response->is_error()) {
                   14224: 	unlink($transferfile);
                   14225: 	&logthis("Userfile repcopy failed for $uri");
                   14226: 	return -1;
                   14227:     }
                   14228: # worked, rename the transfer file
                   14229:     rename($transferfile,$file);
1.607     raeburn  14230:     return 'ok';
1.481     raeburn  14231: }
                   14232: 
1.517     albertel 14233: sub tokenwrapper {
                   14234:     my $uri=shift;
1.980     raeburn  14235:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 14236:     $uri=~s|^/||;
1.620     albertel 14237:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 14238:     my $token=$1;
1.552     albertel 14239:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   14240:     if ($udom && $uname && $file) {
                   14241: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  14242:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  14243:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.120  raeburn  14244:         my $hostname = &hostname($homeserver);
1.980     raeburn  14245:         my $protocol = $protocol{$homeserver};
                   14246:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  14247:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 14248:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   14249:                                '&tokenissued='.$perlvar{'lonHostID'};
                   14250:     } else {
                   14251:         return '/adm/notfound.html';
                   14252:     }
                   14253: }
                   14254: 
1.828     www      14255: # call with reqtype HEAD: get last modification time
                   14256: # call with reqtype GET: get the file contents
                   14257: # Do not call this with reqtype GET for large files! It loads everything into memory
                   14258: #
1.481     raeburn  14259: sub getuploaded {
                   14260:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   14261:     $uri=~s/^\///;
1.980     raeburn  14262:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  14263:     my $hostname = &hostname($homeserver);
1.980     raeburn  14264:     my $protocol = $protocol{$homeserver};
                   14265:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  14266:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  14267:     my $ua=new LWP::UserAgent;
                   14268:     my $request=new HTTP::Request($reqtype,$uri);
                   14269:     my $response=$ua->request($request);
                   14270:     $$rtncode = $response->code;
1.482     albertel 14271:     if (! $response->is_success()) {
                   14272: 	return 'failed';
                   14273:     }      
                   14274:     if ($reqtype eq 'HEAD') {
1.486     www      14275: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 14276:     } elsif ($reqtype eq 'GET') {
                   14277: 	$$info = $response->content;
1.472     albertel 14278:     }
1.482     albertel 14279:     return 'ok';
1.36      albertel 14280: }
                   14281: 
1.481     raeburn  14282: sub readfile {
                   14283:     my $file = shift;
                   14284:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   14285:     my $fh;
1.1172.2.96  raeburn  14286:     open($fh,"<",$file);
1.481     raeburn  14287:     my $a='';
1.800     albertel 14288:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  14289:     return $a;
                   14290: }
                   14291: 
1.36      albertel 14292: sub filelocation {
1.590     banghart 14293:     my ($dir,$file) = @_;
                   14294:     my $location;
                   14295:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 14296: 
                   14297:     if ($file =~ m-^/adm/-) {
                   14298: 	$file=~s-^/adm/wrapper/-/-;
                   14299: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   14300:     }
1.882     albertel 14301: 
1.1139    www      14302:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  14303:         $location = $file;
1.609     banghart 14304:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 14305:         my ($udom,$uname,$filename)=
1.811     albertel 14306:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 14307:         my $home=&homeserver($uname,$udom);
                   14308:         my $is_me=0;
                   14309:         my @ids=&current_machine_ids();
                   14310:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   14311:         if ($is_me) {
1.1117    foxr     14312:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 14313:         } else {
                   14314:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   14315:   	      $udom.'/'.$uname.'/'.$filename;
                   14316:         }
1.882     albertel 14317:     } elsif ($file =~ m-^/adm/-) {
                   14318: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 14319:     } else {
                   14320:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      14321:         $file=~s:^/(res|priv)/:/:;
                   14322:         my $space=$1;
1.590     banghart 14323:         if ( !( $file =~ m:^/:) ) {
                   14324:             $location = $dir. '/'.$file;
                   14325:         } else {
1.1142    raeburn  14326:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 14327:         }
1.59      albertel 14328:     }
1.590     banghart 14329:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 14330:     while ($location=~m{/\.\./}) {
                   14331: 	if ($location =~ m{/[^/]+/\.\./}) {
                   14332: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   14333: 	} else {
                   14334: 	    $location=~ s{/\.\./}{/}g;
                   14335: 	}
                   14336:     } #remove dir/..
1.590     banghart 14337:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   14338:     return $location;
1.46      www      14339: }
1.36      albertel 14340: 
1.46      www      14341: sub hreflocation {
                   14342:     my ($dir,$file)=@_;
1.980     raeburn  14343:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 14344: 	$file=filelocation($dir,$file);
1.700     albertel 14345:     } elsif ($file=~m-^/adm/-) {
                   14346: 	$file=~s-^/adm/wrapper/-/-;
                   14347: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 14348:     }
                   14349:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   14350: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   14351:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  14352: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   14353: 	        {/uploaded/$1/$2/}x;
1.46      www      14354:     }
1.913     albertel 14355:     if ($file=~ m{^/userfiles/}) {
                   14356: 	$file =~ s{^/userfiles/}{/uploaded/};
                   14357:     }
1.462     albertel 14358:     return $file;
1.465     albertel 14359: }
                   14360: 
1.1139    www      14361: 
                   14362: 
                   14363: 
                   14364: 
1.465     albertel 14365: sub current_machine_domains {
1.853     albertel 14366:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   14367: }
                   14368: 
                   14369: sub machine_domains {
                   14370:     my ($hostname) = @_;
1.465     albertel 14371:     my @domains;
1.838     albertel 14372:     my %hostname = &all_hostnames();
1.465     albertel 14373:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  14374: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 14375: 	if ($hostname eq $name) {
1.844     albertel 14376: 	    push(@domains,&host_domain($id));
1.465     albertel 14377: 	}
                   14378:     }
                   14379:     return @domains;
                   14380: }
                   14381: 
                   14382: sub current_machine_ids {
1.853     albertel 14383:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   14384: }
                   14385: 
                   14386: sub machine_ids {
                   14387:     my ($hostname) = @_;
                   14388:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 14389:     my @ids;
1.888     albertel 14390:     my %name_to_host = &all_names();
1.889     albertel 14391:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   14392: 	return @{ $name_to_host{$hostname} };
                   14393:     }
                   14394:     return;
1.31      www      14395: }
                   14396: 
1.824     raeburn  14397: sub additional_machine_domains {
                   14398:     my @domains;
1.1172.2.142  raeburn  14399:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
                   14400:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
                   14401:             while( my $line = <$fh>) {
                   14402:                 chomp($line);
                   14403:                 $line =~ s/\s//g;
                   14404:                 push(@domains,$line);
                   14405:             }
                   14406:             close($fh);
                   14407:         }
1.824     raeburn  14408:     }
                   14409:     return @domains;
                   14410: }
                   14411: 
                   14412: sub default_login_domain {
                   14413:     my $domain = $perlvar{'lonDefDomain'};
                   14414:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   14415:     foreach my $posdom (&current_machine_domains(),
                   14416:                         &additional_machine_domains()) {
                   14417:         if (lc($posdom) eq lc($testdomain)) {
                   14418:             $domain=$posdom;
                   14419:             last;
                   14420:         }
                   14421:     }
                   14422:     return $domain;
                   14423: }
                   14424: 
1.1172.2.106  raeburn  14425: sub shared_institution {
1.1172.2.136  raeburn  14426:     my ($dom,$lonhost) = @_;
                   14427:     if ($lonhost eq '') {
                   14428:         $lonhost = $perlvar{'lonHostID'};
                   14429:     }
1.1172.2.106  raeburn  14430:     my $same_intdom;
1.1172.2.136  raeburn  14431:     my $hostintdom = &internet_dom($lonhost);
1.1172.2.106  raeburn  14432:     if ($hostintdom ne '') {
                   14433:         my %iphost = &get_iphost();
                   14434:         my $primary_id = &domain($dom,'primary');
                   14435:         my $primary_ip = &get_host_ip($primary_id);
                   14436:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   14437:             foreach my $id (@{$iphost{$primary_ip}}) {
                   14438:                 my $intdom = &internet_dom($id);
                   14439:                 if ($intdom eq $hostintdom) {
                   14440:                     $same_intdom = 1;
                   14441:                     last;
                   14442:                 }
                   14443:             }
                   14444:         }
                   14445:     }
                   14446:     return $same_intdom;
                   14447: }
                   14448: 
1.1172.2.120  raeburn  14449: sub uses_sts {
                   14450:     my ($ignore_cache) = @_;
                   14451:     my $lonhost = $perlvar{'lonHostID'};
                   14452:     my $hostname = &hostname($lonhost);
                   14453:     my $sts_on;
                   14454:     if ($protocol{$lonhost} eq 'https') {
                   14455:         my $cachetime = 12*3600;
                   14456:         if (!$ignore_cache) {
                   14457:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   14458:             if (defined($cached)) {
                   14459:                 return $sts_on;
                   14460:             }
                   14461:         }
1.1172.2.121  raeburn  14462:         my $ua=new LWP::UserAgent;
1.1172.2.120  raeburn  14463:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   14464:         my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121  raeburn  14465:         my $response=$ua->request($request);
1.1172.2.120  raeburn  14466:         if ($response->is_success) {
                   14467:             my $has_sts = $response->header('Strict-Transport-Security');
                   14468:             if ($has_sts eq '') {
                   14469:                 $sts_on = 0;
                   14470:             } else {
                   14471:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   14472:                     my $maxage = $1;
                   14473:                     if ($maxage) {
                   14474:                         $sts_on = 1;
                   14475:                     } else {
                   14476:                         $sts_on = 0;
                   14477:                     }
                   14478:                 } else {
                   14479:                     $sts_on = 0;
                   14480:                 }
                   14481:             }
                   14482:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   14483:         }
                   14484:     }
                   14485:     return;
                   14486: }
                   14487: 
1.1172.2.142  raeburn  14488: sub waf_allssl {
                   14489:     my ($host_name) = @_;
                   14490:     my $alias = &get_proxy_alias();
                   14491:     if ($host_name eq '') {
                   14492:         $host_name = $ENV{'SERVER_NAME'};
                   14493:     }
                   14494:     if (($host_name ne '') && ($alias eq $host_name)) {
                   14495:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   14496:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   14497:         if ($defdomdefaults{'waf_sslopt'}) {
                   14498:             return $defdomdefaults{'waf_sslopt'};
                   14499:         }
                   14500:     }
                   14501:     return;
                   14502: }
                   14503: 
1.1172.2.134  raeburn  14504: sub get_requestor_ip {
                   14505:     my ($r,$nolookup,$noproxy) = @_;
                   14506:     my $from_ip;
                   14507:     if (ref($r)) {
1.1172.2.142  raeburn  14508:         if ($r->can('useragent_ip')) {
                   14509:             if ($noproxy && $r->can('client_ip')) {
                   14510:                 $from_ip = $r->client_ip();
                   14511:             } else {
                   14512:                 $from_ip = $r->useragent_ip();
                   14513:             }
                   14514:         } elsif ($r->connection->can('remote_ip')) {
                   14515:             $from_ip = $r->connection->remote_ip();
                   14516:         } else {
                   14517:             $from_ip = $r->get_remote_host($nolookup);
                   14518:         }
1.1172.2.134  raeburn  14519:     } else {
                   14520:         $from_ip = $ENV{'REMOTE_ADDR'};
                   14521:     }
1.1172.2.142  raeburn  14522:     return $from_ip if ($noproxy);
                   14523:    # Who controls proxy settings for server
                   14524:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14525:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   14526:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
                   14527:         if ($proxyinfo->{'vpnint'}) {
                   14528:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
                   14529:                 return $from_ip;
                   14530:             }
                   14531:         }
                   14532:         if ($proxyinfo->{'trusted'}) {
                   14533:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   14534:                 my $ipheader = $proxyinfo->{'ipheader'};
                   14535:                 my ($ip,$xfor);
                   14536:                 if (ref($r)) {
                   14537:                     if ($ipheader) {
                   14538:                         $ip = $r->headers_in->{$ipheader};
                   14539:                     }
                   14540:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   14541:                 } else {
                   14542:                     if ($ipheader) {
                   14543:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   14544:                     }
                   14545:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   14546:                 }
                   14547:                 if (($ip eq '') && ($xfor ne '')) {
                   14548:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   14549:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   14550:                             $ip = $poss_ip;
                   14551:                             last;
                   14552:                         }
                   14553:                     }
                   14554:                 }
                   14555:                 if ($ip ne '') {
                   14556:                     return $ip;
                   14557:                 }
                   14558:             }
                   14559:         }
                   14560:     }
1.1172.2.134  raeburn  14561:     return $from_ip;
                   14562: }
                   14563: 
1.1172.2.142  raeburn  14564: sub get_proxy_settings {
                   14565:     my ($dom_in_use) = @_;
                   14566:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   14567:     my $proxyinfo = {
                   14568:                        ipheader => $domdefaults{'waf_ipheader'},
                   14569:                        trusted  => $domdefaults{'waf_trusted'},
                   14570:                        vpnint   => $domdefaults{'waf_vpnint'},
                   14571:                        vpnext   => $domdefaults{'waf_vpnext'},
                   14572:                        sslopt   => $domdefaults{'waf_sslopt'},
                   14573:                     };
                   14574:     return $proxyinfo;
                   14575: }
                   14576: 
                   14577: sub ip_match {
                   14578:     my ($ip,$pattern_str) = @_;
                   14579:     $ip=Net::CIDR::cidrvalidate($ip);
                   14580:     if ($ip) {
                   14581:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   14582:     }
                   14583:     return;
                   14584: }
                   14585: 
                   14586: sub get_proxy_alias {
                   14587:     my ($lonid) = @_;
                   14588:     if ($lonid eq '') {
                   14589:         $lonid = $perlvar{'lonHostID'};
                   14590:     }
                   14591:     if (!defined(&hostname($lonid))) {
                   14592:         return;
                   14593:     }
                   14594:     if ($lonid ne '') {
                   14595:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
                   14596:         if ($cached) {
                   14597:             return $alias;
                   14598:         }
                   14599:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14600:         if ($dom ne '') {
                   14601:             my $cachetime = 60*60*24;
                   14602:             my %domconfig =
                   14603:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14604:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14605:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
                   14606:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   14607:                 }
                   14608:             }
                   14609:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   14610:         }
                   14611:     }
                   14612:     return;
                   14613: }
                   14614: 
                   14615: sub use_proxy_alias {
                   14616:     my ($r,$lonid) = @_;
                   14617:     my $alias = &get_proxy_alias($lonid);
                   14618:     if ($alias) {
                   14619:         my $dom = &host_domain($lonid);
                   14620:         if ($dom ne '') {
                   14621:             my $proxyinfo = &get_proxy_settings($dom);
                   14622:             my ($vpnint,$remote_ip);
                   14623:             if (ref($proxyinfo) eq 'HASH') {
                   14624:                 $vpnint = $proxyinfo->{'vpnint'};
                   14625:                 if ($vpnint) {
                   14626:                     $remote_ip = &get_requestor_ip($r,1,1);
                   14627:                 }
                   14628:             }
                   14629:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   14630:                 return $alias;
                   14631:             }
                   14632:         }
                   14633:     }
                   14634:     return;
                   14635: }
                   14636: 
                   14637: sub alias_sso {
                   14638:     my ($lonid) = @_;
                   14639:     if ($lonid eq '') {
                   14640:         $lonid = $perlvar{'lonHostID'};
                   14641:     }
                   14642:     if (!defined(&hostname($lonid))) {
                   14643:         return;
                   14644:     }
                   14645:     if ($lonid ne '') {
                   14646:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
                   14647:         if ($cached) {
                   14648:             return $use_alias;
                   14649:         }
                   14650:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14651:         if ($dom ne '') {
                   14652:             my $cachetime = 60*60*24;
                   14653:             my %domconfig =
                   14654:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14655:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14656:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
                   14657:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
                   14658:                 }
                   14659:             }
                   14660:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
                   14661:         }
                   14662:     }
                   14663:     return;
                   14664: }
                   14665: 
                   14666: sub get_saml_landing {
                   14667:     my ($lonid) = @_;
                   14668:     if ($lonid eq '') {
                   14669:         my $defdom = &default_login_domain();
                   14670:         my @hosts = &current_machine_ids();
                   14671:         if (@hosts > 1) {
                   14672:             foreach my $hostid (@hosts) {
                   14673:                 if (&host_domain($hostid) eq $defdom) {
                   14674:                     $lonid = $hostid;
                   14675:                     last;
                   14676:                 }
                   14677:             }
                   14678:         } else {
                   14679:             $lonid = $perlvar{'lonHostID'};
                   14680:         }
                   14681:         if ($lonid) {
                   14682:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
                   14683:                 return;
                   14684:             }
                   14685:         } else {
                   14686:             return;
                   14687:         }
                   14688:     } elsif (!defined(&hostname($lonid))) {
                   14689:         return;
                   14690:     }
                   14691:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   14692:     if ($cached) {
                   14693:         return $landing;
                   14694:     }
                   14695:     my $dom = &Apache::lonnet::host_domain($lonid);
                   14696:     if ($dom ne '') {
                   14697:         my $cachetime = 60*60*24;
                   14698:         my %domconfig =
                   14699:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
                   14700:         if (ref($domconfig{'login'}) eq 'HASH') {
                   14701:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   14702:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   14703:                     $landing = 1;
                   14704:                 }
                   14705:             }
                   14706:         }
                   14707:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   14708:     }
                   14709:     return;
                   14710: }
                   14711: 
1.31      www      14712: # ------------------------------------------------------------- Declutters URLs
                   14713: 
                   14714: sub declutter {
                   14715:     my $thisfn=shift;
1.569     albertel 14716:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  14717:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   14718:         $thisfn=~s{^/home/httpd/html}{};
                   14719:     }
1.31      www      14720:     $thisfn=~s/^\///;
1.697     albertel 14721:     $thisfn=~s|^adm/wrapper/||;
                   14722:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      14723:     $thisfn=~s/^res\///;
1.1172    bisitz   14724:     $thisfn=~s/^priv\///;
1.1032    raeburn  14725:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   14726:         $thisfn=~s/\?.+$//;
                   14727:     }
1.268     www      14728:     return $thisfn;
                   14729: }
                   14730: 
                   14731: # ------------------------------------------------------------- Clutter up URLs
                   14732: 
                   14733: sub clutter {
                   14734:     my $thisfn='/'.&declutter(shift);
1.887     albertel 14735:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 14736: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      14737:        $thisfn='/res'.$thisfn; 
                   14738:     }
1.1031    raeburn  14739:     if ($thisfn !~m|^/adm|) {
                   14740: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 14741: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 14742: 	} else {
                   14743: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   14744: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 14745: 	    if ($embstyle eq 'ssi'
                   14746: 		|| ($embstyle eq 'hdn')
                   14747: 		|| ($embstyle eq 'rat')
                   14748: 		|| ($embstyle eq 'prv')
                   14749: 		|| ($embstyle eq 'ign')) {
                   14750: 		#do nothing with these
                   14751: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 14752: 		|| ($embstyle eq 'emb')
                   14753: 		|| ($embstyle eq 'wrp')) {
                   14754: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 14755: 	    } elsif ($embstyle eq 'unk'
                   14756: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 14757: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 14758: 	    } else {
1.718     www      14759: #		&logthis("Got a blank emb style");
1.695     albertel 14760: 	    }
1.694     albertel 14761: 	}
1.1172.2.146.  .1(raebu 14762:22):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   14763:22):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 14764:     }
1.31      www      14765:     return $thisfn;
1.12      www      14766: }
                   14767: 
1.787     albertel 14768: sub clutter_with_no_wrapper {
                   14769:     my $uri = &clutter(shift);
                   14770:     if ($uri =~ m-^/adm/-) {
                   14771: 	$uri =~ s-^/adm/wrapper/-/-;
                   14772: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14773:     }
                   14774:     return $uri;
                   14775: }
                   14776: 
1.557     albertel 14777: sub freeze_escape {
                   14778:     my ($value)=@_;
                   14779:     if (ref($value)) {
                   14780: 	$value=&nfreeze($value);
                   14781: 	return '__FROZEN__'.&escape($value);
                   14782:     }
                   14783:     return &escape($value);
                   14784: }
                   14785: 
1.11      www      14786: 
1.557     albertel 14787: sub thaw_unescape {
                   14788:     my ($value)=@_;
                   14789:     if ($value =~ /^__FROZEN__/) {
                   14790: 	substr($value,0,10,undef);
                   14791: 	$value=&unescape($value);
                   14792: 	return &thaw($value);
                   14793:     }
                   14794:     return &unescape($value);
                   14795: }
                   14796: 
1.436     albertel 14797: sub correct_line_ends {
                   14798:     my ($result)=@_;
                   14799:     $$result =~s/\r\n/\n/mg;
                   14800:     $$result =~s/\r/\n/mg;
1.415     albertel 14801: }
1.1       albertel 14802: # ================================================================ Main Program
                   14803: 
1.184     www      14804: sub goodbye {
1.204     albertel 14805:    &logthis("Starting Shut down");
1.443     albertel 14806: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14807:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14808: #converted
1.599     albertel 14809: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14810:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14811: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   14812: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 14813: #1.1 only
1.870     albertel 14814: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   14815: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   14816: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   14817: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   14818:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 14819:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   14820:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      14821:    &flushcourselogs();
                   14822:    &logthis("Shutting down");
                   14823: }
                   14824: 
1.852     albertel 14825: sub get_dns {
1.1172.2.17  raeburn  14826:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 14827:     if (!$ignore_cache) {
                   14828: 	my ($content,$cached)=
                   14829: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   14830: 	if ($cached) {
1.1172.2.17  raeburn  14831: 	    &$func($content,$hashref);
1.869     albertel 14832: 	    return;
                   14833: 	}
                   14834:     }
                   14835: 
                   14836:     my %alldns;
1.1172.2.96  raeburn  14837:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   14838:         foreach my $dns (<$config>) {
                   14839: 	    next if ($dns !~ /^\^(\S*)/x);
                   14840:             my $line = $1;
                   14841:             my ($host,$protocol) = split(/:/,$line);
                   14842:             if ($protocol ne 'https') {
                   14843:                 $protocol = 'http';
                   14844:             }
                   14845: 	    $alldns{$host} = $protocol;
1.979     raeburn  14846:         }
1.1172.2.96  raeburn  14847:         close($config);
1.869     albertel 14848:     }
                   14849:     while (%alldns) {
1.1172.2.52  raeburn  14850: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142  raeburn  14851:         my @content;
                   14852:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   14853:             my $command = (split('/',$url))[3];
                   14854:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   14855:             delete($alldns{$dns});
                   14856:             next if (($dir eq '') || ($file eq ''));
                   14857:             if (open(my $config,'<',"$dir/$file")) {
                   14858:                 @content = <$config>;
                   14859:                 close($config);
                   14860:             }
                   14861:         } else {
                   14862: 	    my $ua=new LWP::UserAgent;
                   14863:             $ua->timeout(30);
                   14864: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   14865: 	    my $response=$ua->request($request);
                   14866:             delete($alldns{$dns});
                   14867: 	    next if ($response->is_error());
                   14868: 	    @content = split("\n",$response->content);
                   14869:         }
1.1172.2.17  raeburn  14870:         unless ($nocache) {
1.1172.2.23  raeburn  14871: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  14872:         }
                   14873: 	&$func(\@content,$hashref);
1.869     albertel 14874: 	return;
1.852     albertel 14875:     }
1.871     albertel 14876:     my $which = (split('/',$url))[3];
                   14877:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  14878:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   14879:         my @content = <$config>;
                   14880:         &$func(\@content,$hashref);
                   14881:     }
1.1172.2.17  raeburn  14882:     return;
                   14883: }
                   14884: 
                   14885: # ------------------------------------------------------Get DNS checksums file
                   14886: sub parse_dns_checksums_tab {
                   14887:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  14888:     my $lonhost = $perlvar{'lonHostID'};
                   14889:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  14890:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  14891:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14892:     my $webconfdir = '/etc/httpd/conf';
                   14893:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14894:         $webconfdir = '/etc/apache2';
                   14895:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14896:         if ($1 >= 10) {
                   14897:             $webconfdir = '/etc/apache2';
                   14898:         }
                   14899:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14900:         if ($1 >= 10.0) {
                   14901:             $webconfdir = '/etc/apache2';
                   14902:         }
                   14903:     }
1.1172.2.17  raeburn  14904:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14905:     my (%chksum,%revnum);
                   14906:     if (ref($lines) eq 'ARRAY') {
                   14907:         chomp(@{$lines});
1.1172.2.34  raeburn  14908:         my $version = shift(@{$lines});
                   14909:         if ($version eq $release) {
1.1172.2.17  raeburn  14910:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  14911:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  14912:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14913:                     if ($webconfdir eq '/etc/apache2') {
                   14914:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14915:                     }
                   14916:                 }
1.1172.2.34  raeburn  14917:                 $chksum{$file} = $shasum;
                   14918:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  14919:             }
                   14920:             if (ref($hashref) eq 'HASH') {
                   14921:                 %{$hashref} = (
                   14922:                                 sums     => \%chksum,
                   14923:                                 versions => \%revnum,
                   14924:                               );
                   14925:             }
                   14926:         }
                   14927:     }
1.869     albertel 14928:     return;
1.852     albertel 14929: }
1.1172.2.17  raeburn  14930: 
                   14931: sub fetch_dns_checksums {
                   14932:     my %checksums;
1.1172.2.34  raeburn  14933:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  14934:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  14935:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14936:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  14937:              \%checksums);
                   14938:     return \%checksums;
                   14939: }
                   14940: 
1.1172.2.142  raeburn  14941: sub parse_getdns_url {
                   14942:     my ($command,$url) = @_;
                   14943:     my $dir = $perlvar{'lonTabDir'};
                   14944:     my $file;
                   14945:     if ($command eq 'hosts') {
                   14946:         $file = 'dns_hosts.tab';
                   14947:     } elsif ($command eq 'domain') {
                   14948:         $file = 'dns_domain.tab';
                   14949:     } elsif ($command eq 'checksums') {
                   14950:         my $version = (split('/',$url))[4];
                   14951:         $file = "dns_checksums/$version.tab",
                   14952:     }
                   14953:     return ($dir,$file);
                   14954: }
                   14955: 
1.327     albertel 14956: # ------------------------------------------------------------ Read domain file
                   14957: {
1.852     albertel 14958:     my $loaded;
1.846     albertel 14959:     my %domain;
                   14960: 
1.852     albertel 14961:     sub parse_domain_tab {
                   14962: 	my ($lines) = @_;
                   14963: 	foreach my $line (@$lines) {
                   14964: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      14965: 
1.846     albertel 14966: 	    chomp($line);
1.852     albertel 14967: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 14968: 	    my %this_domain;
                   14969: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   14970: 			       'lang_def', 'city', 'longi', 'lati',
                   14971: 			       'primary') {
                   14972: 		$this_domain{$field} = shift(@elements);
                   14973: 	    }
                   14974: 	    $domain{$name} = \%this_domain;
1.852     albertel 14975: 	}
                   14976:     }
1.864     albertel 14977: 
                   14978:     sub reset_domain_info {
                   14979: 	undef($loaded);
                   14980: 	undef(%domain);
                   14981:     }
                   14982: 
1.852     albertel 14983:     sub load_domain_tab {
1.1172.2.70  raeburn  14984: 	my ($ignore_cache,$nocache) = @_;
                   14985: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 14986: 	my $fh;
1.1172.2.96  raeburn  14987: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 14988: 	    my @lines = <$fh>;
                   14989: 	    &parse_domain_tab(\@lines);
1.448     albertel 14990: 	}
1.852     albertel 14991: 	close($fh);
                   14992: 	$loaded = 1;
1.327     albertel 14993:     }
1.846     albertel 14994: 
                   14995:     sub domain {
1.852     albertel 14996: 	&load_domain_tab() if (!$loaded);
                   14997: 
1.846     albertel 14998: 	my ($name,$what) = @_;
                   14999: 	return if ( !exists($domain{$name}) );
                   15000: 
                   15001: 	if (!$what) {
                   15002: 	    return $domain{$name}{'description'};
                   15003: 	}
                   15004: 	return $domain{$name}{$what};
                   15005:     }
1.974     raeburn  15006: 
                   15007:     sub domain_info {
                   15008:         &load_domain_tab() if (!$loaded);
                   15009:         return %domain;
                   15010:     }
                   15011: 
1.327     albertel 15012: }
                   15013: 
                   15014: 
1.1       albertel 15015: # ------------------------------------------------------------- Read hosts file
                   15016: {
1.838     albertel 15017:     my %hostname;
1.844     albertel 15018:     my %hostdom;
1.845     albertel 15019:     my %libserv;
1.852     albertel 15020:     my $loaded;
1.888     albertel 15021:     my %name_to_host;
1.1074    raeburn  15022:     my %internetdom;
1.1107    raeburn  15023:     my %LC_dns_serv;
1.852     albertel 15024: 
                   15025:     sub parse_hosts_tab {
                   15026: 	my ($file) = @_;
                   15027: 	foreach my $configline (@$file) {
                   15028: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  15029:             chomp($configline);
                   15030: 	    if ($configline =~ /^\^/) {
                   15031:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   15032:                     $LC_dns_serv{$1} = 1;
                   15033:                 }
                   15034:                 next;
                   15035:             }
1.1074    raeburn  15036: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 15037: 	    $name=~s/\s//g;
                   15038: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  15039:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   15040:                     my $curr = $hostname{$id};
                   15041:                     my $skip;
                   15042:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   15043:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   15044:                             $skip = 1;
                   15045:                         } else {
                   15046:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   15047:                         }
                   15048:                     }
                   15049:                     unless ($skip) {
                   15050:                         push(@{$name_to_host{$name}},$id);
                   15051:                     }
                   15052:                 } else {
                   15053:                     push(@{$name_to_host{$name}},$id);
                   15054:                 }
1.852     albertel 15055: 		$hostname{$id}=$name;
                   15056: 		$hostdom{$id}=$domain;
                   15057: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  15058:                 if (defined($protocol)) {
                   15059:                     if ($protocol eq 'https') {
                   15060:                         $protocol{$id} = $protocol;
                   15061:                     } else {
                   15062:                         $protocol{$id} = 'http'; 
                   15063:                     }
1.968     raeburn  15064:                 } else {
1.969     raeburn  15065:                     $protocol{$id} = 'http';
1.968     raeburn  15066:                 }
1.1074    raeburn  15067:                 if (defined($intdom)) {
                   15068:                     $internetdom{$id} = $intdom;
                   15069:                 }
1.852     albertel 15070: 	    }
                   15071: 	}
                   15072:     }
1.864     albertel 15073:     
                   15074:     sub reset_hosts_info {
1.897     albertel 15075: 	&purge_remembered();
1.864     albertel 15076: 	&reset_domain_info();
                   15077: 	&reset_hosts_ip_info();
1.892     albertel 15078: 	undef(%name_to_host);
1.864     albertel 15079: 	undef(%hostname);
                   15080: 	undef(%hostdom);
                   15081: 	undef(%libserv);
                   15082: 	undef($loaded);
                   15083:     }
1.1       albertel 15084: 
1.852     albertel 15085:     sub load_hosts_tab {
1.1172.2.70  raeburn  15086: 	my ($ignore_cache,$nocache) = @_;
                   15087: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  15088: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 15089: 	my @config = <$config>;
                   15090: 	&parse_hosts_tab(\@config);
                   15091: 	close($config);
                   15092: 	$loaded=1;
1.1       albertel 15093:     }
1.852     albertel 15094: 
1.838     albertel 15095:     sub hostname {
1.852     albertel 15096: 	&load_hosts_tab() if (!$loaded);
                   15097: 
1.838     albertel 15098: 	my ($lonid) = @_;
                   15099: 	return $hostname{$lonid};
                   15100:     }
1.845     albertel 15101: 
1.838     albertel 15102:     sub all_hostnames {
1.852     albertel 15103: 	&load_hosts_tab() if (!$loaded);
                   15104: 
1.838     albertel 15105: 	return %hostname;
                   15106:     }
1.845     albertel 15107: 
1.888     albertel 15108:     sub all_names {
1.1172.2.70  raeburn  15109:         my ($ignore_cache,$nocache) = @_;
                   15110: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 15111: 
                   15112: 	return %name_to_host;
                   15113:     }
                   15114: 
1.974     raeburn  15115:     sub all_host_domain {
                   15116:         &load_hosts_tab() if (!$loaded);
                   15117:         return %hostdom;
                   15118:     }
                   15119: 
1.845     albertel 15120:     sub is_library {
1.852     albertel 15121: 	&load_hosts_tab() if (!$loaded);
                   15122: 
1.845     albertel 15123: 	return exists($libserv{$_[0]});
                   15124:     }
                   15125: 
                   15126:     sub all_library {
1.852     albertel 15127: 	&load_hosts_tab() if (!$loaded);
                   15128: 
1.845     albertel 15129: 	return %libserv;
                   15130:     }
                   15131: 
1.1062    droeschl 15132:     sub unique_library {
                   15133: 	#2x reverse removes all hostnames that appear more than once
                   15134:         my %unique = reverse &all_library();
                   15135:         return reverse %unique;
                   15136:     }
                   15137: 
1.841     albertel 15138:     sub get_servers {
1.852     albertel 15139: 	&load_hosts_tab() if (!$loaded);
                   15140: 
1.841     albertel 15141: 	my ($domain,$type) = @_;
                   15142: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   15143: 	                                          : %hostname;
                   15144: 	my %result;
1.842     albertel 15145: 	if (ref($domain) eq 'ARRAY') {
                   15146: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 15147: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 15148: 		    $result{$host} = $hostname;
                   15149: 		}
                   15150: 	    }
                   15151: 	} else {
                   15152: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   15153: 		if ($hostdom{$host} eq $domain) {
                   15154: 		    $result{$host} = $hostname;
                   15155: 		}
1.841     albertel 15156: 	    }
                   15157: 	}
                   15158: 	return %result;
                   15159:     }
1.845     albertel 15160: 
1.1062    droeschl 15161:     sub get_unique_servers {
                   15162:         my %unique = reverse &get_servers(@_);
                   15163: 	return reverse %unique;
                   15164:     }
                   15165: 
1.844     albertel 15166:     sub host_domain {
1.852     albertel 15167: 	&load_hosts_tab() if (!$loaded);
                   15168: 
1.844     albertel 15169: 	my ($lonid) = @_;
                   15170: 	return $hostdom{$lonid};
                   15171:     }
                   15172: 
1.841     albertel 15173:     sub all_domains {
1.852     albertel 15174: 	&load_hosts_tab() if (!$loaded);
                   15175: 
1.841     albertel 15176: 	my %seen;
                   15177: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   15178: 	return @uniq;
                   15179:     }
1.1074    raeburn  15180: 
                   15181:     sub internet_dom {
                   15182:         &load_hosts_tab() if (!$loaded);
                   15183: 
                   15184:         my ($lonid) = @_;
                   15185:         return $internetdom{$lonid};
                   15186:     }
1.1107    raeburn  15187: 
                   15188:     sub is_LC_dns {
                   15189:         &load_hosts_tab() if (!$loaded);
                   15190: 
                   15191:         my ($hostname) = @_;
                   15192:         return exists($LC_dns_serv{$hostname});
                   15193:     }
                   15194: 
1.1       albertel 15195: }
                   15196: 
1.847     albertel 15197: { 
                   15198:     my %iphost;
1.856     albertel 15199:     my %name_to_ip;
                   15200:     my %lonid_to_ip;
1.869     albertel 15201: 
1.847     albertel 15202:     sub get_hosts_from_ip {
                   15203: 	my ($ip) = @_;
                   15204: 	my %iphosts = &get_iphost();
                   15205: 	if (ref($iphosts{$ip})) {
                   15206: 	    return @{$iphosts{$ip}};
                   15207: 	}
                   15208: 	return;
1.839     albertel 15209:     }
1.864     albertel 15210:     
                   15211:     sub reset_hosts_ip_info {
                   15212: 	undef(%iphost);
                   15213: 	undef(%name_to_ip);
                   15214: 	undef(%lonid_to_ip);
                   15215:     }
1.856     albertel 15216: 
                   15217:     sub get_host_ip {
                   15218: 	my ($lonid) = @_;
                   15219: 	if (exists($lonid_to_ip{$lonid})) {
                   15220: 	    return $lonid_to_ip{$lonid};
                   15221: 	}
                   15222: 	my $name=&hostname($lonid);
                   15223:    	my $ip = gethostbyname($name);
                   15224: 	return if (!$ip || length($ip) ne 4);
                   15225: 	$ip=inet_ntoa($ip);
                   15226: 	$name_to_ip{$name}   = $ip;
                   15227: 	$lonid_to_ip{$lonid} = $ip;
                   15228: 	return $ip;
                   15229:     }
1.847     albertel 15230:     
                   15231:     sub get_iphost {
1.1172.2.70  raeburn  15232: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 15233: 
1.869     albertel 15234: 	if (!$ignore_cache) {
                   15235: 	    if (%iphost) {
                   15236: 		return %iphost;
                   15237: 	    }
                   15238: 	    my ($ip_info,$cached)=
                   15239: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   15240: 	    if ($cached) {
                   15241: 		%iphost      = %{$ip_info->[0]};
                   15242: 		%name_to_ip  = %{$ip_info->[1]};
                   15243: 		%lonid_to_ip = %{$ip_info->[2]};
                   15244: 		return %iphost;
                   15245: 	    }
                   15246: 	}
1.894     albertel 15247: 
                   15248: 	# get yesterday's info for fallback
                   15249: 	my %old_name_to_ip;
                   15250: 	my ($ip_info,$cached)=
                   15251: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   15252: 	if ($cached) {
                   15253: 	    %old_name_to_ip = %{$ip_info->[1]};
                   15254: 	}
                   15255: 
1.1172.2.70  raeburn  15256: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 15257: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 15258: 	    my $ip;
                   15259: 	    if (!exists($name_to_ip{$name})) {
                   15260: 		$ip = gethostbyname($name);
                   15261: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 15262: 		    if (defined($old_name_to_ip{$name})) {
                   15263: 			$ip = $old_name_to_ip{$name};
                   15264: 			&logthis("Can't find $name defaulting to old $ip");
                   15265: 		    } else {
                   15266: 			&logthis("Name $name no IP found");
                   15267: 			next;
                   15268: 		    }
                   15269: 		} else {
                   15270: 		    $ip=inet_ntoa($ip);
1.847     albertel 15271: 		}
                   15272: 		$name_to_ip{$name} = $ip;
                   15273: 	    } else {
                   15274: 		$ip = $name_to_ip{$name};
1.653     albertel 15275: 	    }
1.888     albertel 15276: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   15277: 		$lonid_to_ip{$id} = $ip;
                   15278: 	    }
                   15279: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 15280: 	}
1.1172.2.70  raeburn  15281:         unless ($nocache) {
                   15282: 	    &do_cache_new('iphost','iphost',
                   15283: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   15284: 		          48*60*60);
                   15285:         }
1.869     albertel 15286: 
1.847     albertel 15287: 	return %iphost;
1.598     albertel 15288:     }
                   15289: 
1.992     raeburn  15290:     #
                   15291:     #  Given a DNS returns the loncapa host name for that DNS 
                   15292:     # 
                   15293:     sub host_from_dns {
                   15294:         my ($dns) = @_;
                   15295:         my @hosts;
                   15296:         my $ip;
                   15297: 
1.993     raeburn  15298:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  15299:             $ip = $name_to_ip{$dns};
                   15300:         }
                   15301:         if (!$ip) {
                   15302:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   15303:             if (length($ip) == 4) { 
                   15304: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   15305:             }
                   15306:         }
                   15307:         if ($ip) {
                   15308: 	    @hosts = get_hosts_from_ip($ip);
                   15309: 	    return $hosts[0];
                   15310:         }
                   15311:         return undef;
1.986     foxr     15312:     }
1.992     raeburn  15313: 
1.1074    raeburn  15314:     sub get_internet_names {
                   15315:         my ($lonid) = @_;
                   15316:         return if ($lonid eq '');
                   15317:         my ($idnref,$cached)=
                   15318:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   15319:         if ($cached) {
                   15320:             return $idnref;
                   15321:         }
                   15322:         my $ip = &get_host_ip($lonid);
                   15323:         my @hosts = &get_hosts_from_ip($ip);
                   15324:         my %iphost = &get_iphost();
                   15325:         my (@idns,%seen);
                   15326:         foreach my $id (@hosts) {
                   15327:             my $dom = &host_domain($id);
                   15328:             my $prim_id = &domain($dom,'primary');
                   15329:             my $prim_ip = &get_host_ip($prim_id);
                   15330:             next if ($seen{$prim_ip});
                   15331:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   15332:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   15333:                     my $intdom = &internet_dom($id);
                   15334:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   15335:                         push(@idns,$intdom);
                   15336:                     }
                   15337:                 }
                   15338:             }
                   15339:             $seen{$prim_ip} = 1;
                   15340:         }
1.1172.2.23  raeburn  15341:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  15342:     }
                   15343: 
1.986     foxr     15344: }
                   15345: 
1.1079    raeburn  15346: sub all_loncaparevs {
1.1172.2.39  raeburn  15347:     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  15348: }
                   15349: 
1.1172.2.27  raeburn  15350: # ------------------------------------------------------- Read loncaparev table
                   15351: {
                   15352:     sub load_loncaparevs {
                   15353:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  15354:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  15355:                 while (my $configline=<$config>) {
                   15356:                     chomp($configline);
                   15357:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   15358:                     $loncaparevs{$hostid}=$loncaparev;
                   15359:                 }
                   15360:                 close($config);
                   15361:             }
                   15362:         }
                   15363:     }
                   15364: }
                   15365: 
                   15366: # ----------------------------------------------------- Read serverhostID table
                   15367: {
                   15368:     sub load_serverhomeIDs {
                   15369:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  15370:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  15371:                 while (my $configline=<$config>) {
                   15372:                     chomp($configline);
                   15373:                     my ($name,$id)=split(/:/,$configline);
                   15374:                     $serverhomeIDs{$name}=$id;
                   15375:                 }
                   15376:                 close($config);
                   15377:             }
                   15378:         }
                   15379:     }
                   15380: }
                   15381: 
                   15382: 
1.862     albertel 15383: BEGIN {
                   15384: 
                   15385: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   15386:     unless ($readit) {
                   15387: {
                   15388:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   15389:     %perlvar = (%perlvar,%{$configvars});
                   15390: }
                   15391: 
                   15392: 
1.1       albertel 15393: # ------------------------------------------------------ Read spare server file
                   15394: {
1.1172.2.96  raeburn  15395:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 15396: 
                   15397:     while (my $configline=<$config>) {
                   15398:        chomp($configline);
1.284     matthew  15399:        if ($configline) {
1.784     albertel 15400: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 15401: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 15402: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 15403:        }
                   15404:     }
1.448     albertel 15405:     close($config);
1.1       albertel 15406: }
1.11      www      15407: # ------------------------------------------------------------ Read permissions
                   15408: {
1.1172.2.96  raeburn  15409:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      15410: 
                   15411:     while (my $configline=<$config>) {
1.448     albertel 15412: 	chomp($configline);
                   15413: 	if ($configline) {
                   15414: 	    my ($role,$perm)=split(/ /,$configline);
                   15415: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   15416: 	}
1.11      www      15417:     }
1.448     albertel 15418:     close($config);
1.11      www      15419: }
                   15420: 
                   15421: # -------------------------------------------- Read plain texts for permissions
                   15422: {
1.1172.2.96  raeburn  15423:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      15424: 
                   15425:     while (my $configline=<$config>) {
1.448     albertel 15426: 	chomp($configline);
                   15427: 	if ($configline) {
1.742     raeburn  15428: 	    my ($short,@plain)=split(/:/,$configline);
                   15429:             %{$prp{$short}} = ();
                   15430: 	    if (@plain > 0) {
                   15431:                 $prp{$short}{'std'} = $plain[0];
                   15432:                 for (my $i=1; $i<@plain; $i++) {
                   15433:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   15434:                 }
                   15435:             }
1.448     albertel 15436: 	}
1.135     www      15437:     }
1.448     albertel 15438:     close($config);
1.135     www      15439: }
                   15440: 
                   15441: # ---------------------------------------------------------- Read package table
                   15442: {
1.1172.2.96  raeburn  15443:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      15444: 
                   15445:     while (my $configline=<$config>) {
1.483     albertel 15446: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 15447: 	chomp($configline);
                   15448: 	my ($short,$plain)=split(/:/,$configline);
                   15449: 	my ($pack,$name)=split(/\&/,$short);
                   15450: 	if ($plain ne '') {
                   15451: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   15452: 	    $packagetab{$short}=$plain; 
                   15453: 	}
1.11      www      15454:     }
1.448     albertel 15455:     close($config);
1.329     matthew  15456: }
                   15457: 
1.1172.2.27  raeburn  15458: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  15459: 
1.1172.2.27  raeburn  15460: &load_loncaparevs();
                   15461: 
                   15462: # ------------------------------------------------------- Read serverhostID table
                   15463: 
                   15464: &load_serverhomeIDs();
1.1074    raeburn  15465: 
1.1172.2.27  raeburn  15466: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  15467: {
                   15468:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   15469:     if (-e $file) {
                   15470:         my $parser = HTML::LCParser->new($file);
                   15471:         while (my $token = $parser->get_token()) {
                   15472:             if ($token->[0] eq 'S') {
                   15473:                 my $item = $token->[1];
                   15474:                 my $name = $token->[2]{'name'};
                   15475:                 my $value = $token->[2]{'value'};
                   15476:                 if ($item ne '' && $name ne '' && $value ne '') {
                   15477:                     my $release = $parser->get_text();
                   15478:                     $release =~ s/(^\s*|\s*$ )//gx;
                   15479:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   15480:                 }
                   15481:             }
                   15482:         }
                   15483:     }
1.1073    raeburn  15484: }
                   15485: 
1.1138    raeburn  15486: # ---------------------------------------------------------- Read managers table
                   15487: {
                   15488:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  15489:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  15490:             while (my $configline=<$config>) {
                   15491:                 chomp($configline);
                   15492:                 next if ($configline =~ /^\#/);
                   15493:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   15494:                     $managerstab{$configline} = 1;
                   15495:                 }
                   15496:             }
                   15497:             close($config);
                   15498:         }
                   15499:     }
                   15500: }
                   15501: 
1.329     matthew  15502: # ------------- set up temporary directory
                   15503: {
1.1117    foxr     15504:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  15505: 
1.11      www      15506: }
                   15507: 
1.1172.2.104  raeburn  15508: # ------------- set default texengine (domain default overrides this)
                   15509: {
                   15510:     $deftex = LONCAPA::texengine();
                   15511: }
                   15512: 
1.1172.2.114  raeburn  15513: # ------------- set default minimum length for passwords for internal auth users
                   15514: {
                   15515:     $passwdmin = LONCAPA::passwd_min();
                   15516: }
                   15517: 
1.794     albertel 15518: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   15519: 				'compress_threshold'=> 20_000,
                   15520:  			        });
1.185     www      15521: 
1.281     www      15522: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      15523: $dumpcount=0;
1.958     www      15524: $locknum=0;
1.22      www      15525: 
1.163     harris41 15526: &logtouch();
1.672     albertel 15527: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      15528: $readit=1;
1.564     albertel 15529:     {
                   15530: 	use integer;
                   15531: 	my $test=(2**32)+1;
1.568     albertel 15532: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 15533: 	&logthis(" Detected 64bit platform ($_64bit)");
                   15534:     }
1.195     www      15535: }
1.1       albertel 15536: }
1.179     www      15537: 
1.1       albertel 15538: 1;
1.191     harris41 15539: __END__
                   15540: 
1.243     albertel 15541: =pod
                   15542: 
1.191     harris41 15543: =head1 NAME
                   15544: 
1.243     albertel 15545: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 15546: 
                   15547: =head1 SYNOPSIS
                   15548: 
1.243     albertel 15549: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 15550: 
                   15551:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   15552: 
1.243     albertel 15553: Common parameters:
                   15554: 
                   15555: =over 4
                   15556: 
                   15557: =item *
                   15558: 
                   15559: $uname : an internal username (if $cname expecting a course Id specifically)
                   15560: 
                   15561: =item *
                   15562: 
                   15563: $udom : a domain (if $cdom expecting a course's domain specifically)
                   15564: 
                   15565: =item *
                   15566: 
                   15567: $symb : a resource instance identifier
                   15568: 
                   15569: =item *
                   15570: 
                   15571: $namespace : the name of a .db file that contains the data needed or
                   15572: being set.
                   15573: 
                   15574: =back
                   15575: 
1.394     bowersj2 15576: =head1 OVERVIEW
1.191     harris41 15577: 
1.394     bowersj2 15578: lonnet provides subroutines which interact with the
                   15579: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   15580: about classes, users, and resources.
1.243     albertel 15581: 
                   15582: For many of these objects you can also use this to store data about
                   15583: them or modify them in various ways.
1.191     harris41 15584: 
1.394     bowersj2 15585: =head2 Symbs
1.191     harris41 15586: 
1.394     bowersj2 15587: To identify a specific instance of a resource, LON-CAPA uses symbols
                   15588: or "symbs"X<symb>. These identifiers are built from the URL of the
                   15589: map, the resource number of the resource in the map, and the URL of
                   15590: the resource itself. The latter is somewhat redundant, but might help
                   15591: if maps change.
                   15592: 
                   15593: An example is
                   15594: 
                   15595:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   15596: 
                   15597: The respective map entry is
                   15598: 
                   15599:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   15600:   title="Problem 2">
                   15601:  </resource>
                   15602: 
                   15603: Symbs are used by the random number generator, as well as to store and
                   15604: restore data specific to a certain instance of for example a problem.
                   15605: 
                   15606: =head2 Storing And Retrieving Data
                   15607: 
                   15608: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   15609: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   15610: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   15611: is is the non-critical message twin of cstore. These functions are for
                   15612: handlers to store a perl hash to a user's permanent data space in an
                   15613: easy manner, and to retrieve it again on another call. It is expected
                   15614: that a handler would use this once at the beginning to retrieve data,
                   15615: and then again once at the end to send only the new data back.
                   15616: 
                   15617: The data is stored in the user's data directory on the user's
                   15618: homeserver under the ID of the course.
                   15619: 
                   15620: The hash that is returned by restore will have all of the previous
                   15621: value for all of the elements of the hash.
                   15622: 
                   15623: Example:
                   15624: 
                   15625:  #creating a hash
                   15626:  my %hash;
                   15627:  $hash{'foo'}='bar';
                   15628: 
                   15629:  #storing it
                   15630:  &Apache::lonnet::cstore(\%hash);
                   15631: 
                   15632:  #changing a value
                   15633:  $hash{'foo'}='notbar';
                   15634: 
                   15635:  #adding a new value
                   15636:  $hash{'bar'}='foo';
                   15637:  &Apache::lonnet::cstore(\%hash);
                   15638: 
                   15639:  #retrieving the hash
                   15640:  my %history=&Apache::lonnet::restore();
                   15641: 
                   15642:  #print the hash
                   15643:  foreach my $key (sort(keys(%history))) {
                   15644:    print("\%history{$key} = $history{$key}");
                   15645:  }
                   15646: 
                   15647: Will print out:
1.191     harris41 15648: 
1.394     bowersj2 15649:  %history{1:foo} = bar
                   15650:  %history{1:keys} = foo:timestamp
                   15651:  %history{1:timestamp} = 990455579
                   15652:  %history{2:bar} = foo
                   15653:  %history{2:foo} = notbar
                   15654:  %history{2:keys} = foo:bar:timestamp
                   15655:  %history{2:timestamp} = 990455580
                   15656:  %history{bar} = foo
                   15657:  %history{foo} = notbar
                   15658:  %history{timestamp} = 990455580
                   15659:  %history{version} = 2
                   15660: 
                   15661: Note that the special hash entries C<keys>, C<version> and
                   15662: C<timestamp> were added to the hash. C<version> will be equal to the
                   15663: total number of versions of the data that have been stored. The
                   15664: C<timestamp> attribute will be the UNIX time the hash was
                   15665: stored. C<keys> is available in every historical section to list which
                   15666: keys were added or changed at a specific historical revision of a
                   15667: hash.
                   15668: 
                   15669: B<Warning>: do not store the hash that restore returns directly. This
                   15670: will cause a mess since it will restore the historical keys as if the
                   15671: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 15672: 
1.394     bowersj2 15673: Calling convention:
1.191     harris41 15674: 
1.1172.2.27  raeburn  15675:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  15676:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 15677: 
1.394     bowersj2 15678: For more detailed information, see lonnet specific documentation.
1.191     harris41 15679: 
1.394     bowersj2 15680: =head1 RETURN MESSAGES
1.191     harris41 15681: 
1.394     bowersj2 15682: =over 4
1.191     harris41 15683: 
1.394     bowersj2 15684: =item * B<con_lost>: unable to contact remote host
1.191     harris41 15685: 
1.394     bowersj2 15686: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   15687: when the connection is brought back up
1.191     harris41 15688: 
1.394     bowersj2 15689: =item * B<con_failed>: unable to contact remote host and unable to save message
                   15690: for later delivery
1.191     harris41 15691: 
1.967     bisitz   15692: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 15693: 
1.394     bowersj2 15694: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 15695: that was requested
1.191     harris41 15696: 
1.243     albertel 15697: =back
1.191     harris41 15698: 
1.243     albertel 15699: =head1 PUBLIC SUBROUTINES
1.191     harris41 15700: 
1.243     albertel 15701: =head2 Session Environment Functions
1.191     harris41 15702: 
1.243     albertel 15703: =over 4
1.191     harris41 15704: 
1.394     bowersj2 15705: =item * 
                   15706: X<appenv()>
1.949     raeburn  15707: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 15708: the user envirnoment file, and will be restored for each access this
1.620     albertel 15709: user makes during this session, also modifies the %env for the current
1.949     raeburn  15710: process. Optional rolesarrayref - if defined contains a reference to an array
                   15711: of roles which are exempt from the restriction on modifying user.role entries 
                   15712: in the user's environment.db and in %env.    
1.191     harris41 15713: 
                   15714: =item *
1.394     bowersj2 15715: X<delenv()>
1.987     raeburn  15716: B<delenv($delthis,$regexp)>: removes all items from the session
                   15717: environment file that begin with $delthis. If the 
                   15718: optional second arg - $regexp - is true, $delthis is treated as a 
                   15719: regular expression, otherwise \Q$delthis\E is used. 
                   15720: The values are also deleted from the current processes %env.
1.191     harris41 15721: 
1.795     albertel 15722: =item * get_env_multiple($name) 
                   15723: 
                   15724: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   15725: values may be defined and end up as an array ref.
                   15726: 
                   15727: returns an array of values
                   15728: 
1.243     albertel 15729: =back
                   15730: 
                   15731: =head2 User Information
1.191     harris41 15732: 
1.243     albertel 15733: =over 4
1.191     harris41 15734: 
                   15735: =item *
1.394     bowersj2 15736: X<queryauthenticate()>
                   15737: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 15738: authentication scheme
                   15739: 
                   15740: =item *
1.394     bowersj2 15741: X<authenticate()>
1.1073    raeburn  15742: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 15743: authenticate user from domain's lib servers (first use the current
                   15744: one). C<$upass> should be the users password.
1.1073    raeburn  15745: $checkdefauth is optional (value is 1 if a check should be made to
                   15746:    authenticate user using default authentication method, and allow
                   15747:    account creation if username does not have account in the domain).
                   15748: $clientcancheckhost is optional (value is 1 if checking whether the
                   15749:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 15750: 
                   15751: =item *
1.394     bowersj2 15752: X<homeserver()>
                   15753: B<homeserver($uname,$udom)>: find the server which has
                   15754: the user's directory and files (there must be only one), this caches
                   15755: the answer, and also caches if there is a borken connection.
1.191     harris41 15756: 
                   15757: =item *
1.394     bowersj2 15758: X<idget()>
                   15759: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   15760: (IDs are a unique resource in a domain, there must be only 1 ID per
                   15761: username, and only 1 username per ID in a specific domain) (returns
                   15762: hash: id=>name,id=>name)
1.191     harris41 15763: 
                   15764: =item *
1.394     bowersj2 15765: X<idrget()>
                   15766: B<idrget($udom,@unames)>: find the IDs behind a list of
                   15767: usernames (returns hash: name=>id,name=>id)
1.191     harris41 15768: 
                   15769: =item *
1.394     bowersj2 15770: X<idput()>
                   15771: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 15772: 
                   15773: =item *
1.394     bowersj2 15774: X<rolesinit()>
1.1169    droeschl 15775: B<rolesinit($udom,$username)>: get user privileges.
                   15776: returns user role, first access and timer interval hashes
1.243     albertel 15777: 
                   15778: =item *
1.1171    droeschl 15779: X<privileged()>
                   15780: B<privileged($username,$domain)>: returns a true if user has a
                   15781: privileged and active role (i.e. su or dc), false otherwise.
                   15782: 
                   15783: =item *
1.551     albertel 15784: X<getsection()>
                   15785: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 15786: course $cname, return section name/number or '' for "not in course"
                   15787: and '-1' for "no section"
                   15788: 
                   15789: =item *
1.394     bowersj2 15790: X<userenvironment()>
                   15791: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 15792: passed in @what from the requested user's environment, returns a hash
                   15793: 
1.858     raeburn  15794: =item * 
                   15795: X<userlog_query()>
1.859     albertel 15796: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   15797: activity.log file. %filters defines filters applied when parsing the
                   15798: log file. These can be start or end timestamps, or the type of action
                   15799: - log to look for Login or Logout events, check for Checkin or
                   15800: Checkout, role for role selection. The response is in the form
                   15801: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   15802: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  15803: 
1.243     albertel 15804: =back
                   15805: 
                   15806: =head2 User Roles
                   15807: 
                   15808: =over 4
                   15809: 
                   15810: =item *
                   15811: 
1.1172.2.65  raeburn  15812: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   15813: returns codes for allowed actions.
                   15814: 
                   15815: The first argument is required, all others are optional.
                   15816: 
                   15817: $priv is the privilege being checked.
                   15818: $uri contains additional information about what is being checked for access (e.g.,
                   15819: URL, course ID etc.).
                   15820: $symb is the unique resource instance identifier in a course; if needed,
                   15821: but not provided, it will be retrieved via a call to &symbread().
                   15822: $role is the role for which a priv is being checked (only used if priv is evb).
                   15823: $clientip is the user's IP address (only used when checking for access to portfolio
                   15824: files).
                   15825: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   15826: prevents recursive calls to &allowed.
                   15827: 
1.243     albertel 15828:  F: full access
                   15829:  U,I,K: authentication modes (cxx only)
                   15830:  '': forbidden
                   15831:  1: user needs to choose course
                   15832:  2: browse allowed
1.766     albertel 15833:  A: passphrase authentication needed
1.1172.2.65  raeburn  15834:  B: access temporarily blocked because of a blocking event in a course.
1.1172.2.146.  .1(raebu 15835:22):  D: access blocked because access is required via session initiated via deep-link
1.243     albertel 15836: 
                   15837: =item *
                   15838: 
1.1172.2.13  raeburn  15839: constructaccess($url,$setpriv) : check for access to construction space URL
                   15840: 
                   15841: See if the owner domain and name in the URL match those in the
                   15842: expected environment.  If so, return three element list
                   15843: ($ownername,$ownerdomain,$ownerhome).
                   15844: 
                   15845: Otherwise return the null string.
                   15846: 
                   15847: If second argument 'setpriv' is true, it assigns the privileges,
                   15848: and returns the same three element list, unless the owner has
                   15849: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   15850: in which case the null string is returned.
                   15851: 
                   15852: =item *
                   15853: 
1.1172.2.84  raeburn  15854: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   15855: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   15856: for system, domain, and course level. $uname and $udom are optional (current
                   15857: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 15858: 
                   15859: =item *
                   15860: 
1.988     raeburn  15861: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   15862: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  15863: $type is Course (default) or Community.
1.988     raeburn  15864: If $forcedefault evaluates to true, text returned will be default 
                   15865: text for $type. Otherwise, if this is a course, the text returned 
                   15866: will be a custom name for the role (if defined in the course's 
                   15867: environment).  If no custom name is defined the default is returned.
                   15868:    
1.832     raeburn  15869: =item *
                   15870: 
1.1172.2.23  raeburn  15871: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  15872: All arguments are optional. Returns a hash of a roles, either for
                   15873: co-author/assistant author roles for a user's Construction Space
1.906     albertel 15874: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  15875: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   15876: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   15877: For each key, value is set to colon-separated start and end times for
                   15878: the role.  If no username and domain are specified, will default to
1.934     raeburn  15879: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  15880: of role statuses (active, future or previous), roles 
                   15881: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   15882: to restrict the list of roles reported. If no array ref is 
                   15883: provided for types, will default to return only active roles.
1.834     albertel 15884: 
1.1172.2.13  raeburn  15885: =item *
                   15886: 
                   15887: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   15888: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   15889: 
                   15890: Additional optional arguments are: $type (if role checking is to be restricted
                   15891: to certain user status types -- previous (expired roles), active (currently
                   15892: available roles) or future (roles available in the future), and
                   15893: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  15894: have active Domain Coordinator role in course's domain or in additional
                   15895: domains (specified in 'Domains to check for privileged users' in course
                   15896: environment -- set via:  Course Settings -> Classlists and staff listing).
                   15897: 
                   15898: =item *
                   15899: 
                   15900: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   15901: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   15902: $possdomains and $possroles are optional array refs -- to domains to check and
                   15903: roles to check.  If $possdomains is not specified, a dump will be done of the
                   15904: users' roles.db to check for a dc or su role in any domain. This can be
                   15905: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   15906: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   15907: this then allows &privileged_by_domain() to be used, which caches the identity
                   15908: of privileged users, eliminating the need for repeated calls to &dump().
                   15909: 
                   15910: =item *
                   15911: 
                   15912: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15913: where the outer hash keys are domains specified in the $possdomains array ref,
                   15914: next inner hash keys are privileged roles specified in the $roles array ref,
                   15915: and the innermost hash contains key = value pairs for username:domain = end:start
                   15916: for active or future "privileged" users with that role in that domain. To avoid
                   15917: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15918: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  15919: 
1.243     albertel 15920: =back
                   15921: 
                   15922: =head2 User Modification
                   15923: 
                   15924: =over 4
                   15925: 
                   15926: =item *
                   15927: 
1.957     raeburn  15928: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15929: user for the level given by URL.  Optional start and end dates (leave empty
                   15930: string or zero for "no date")
1.191     harris41 15931: 
                   15932: =item *
                   15933: 
1.243     albertel 15934: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15935: change a users, password, possible return values are: ok,
                   15936: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15937: refused
1.191     harris41 15938: 
                   15939: =item *
                   15940: 
1.243     albertel 15941: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15942: 
                   15943: =item *
                   15944: 
1.1058    raeburn  15945: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   15946:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   15947: 
                   15948: will update user information (firstname,middlename,lastname,generation,
                   15949: permanentemail), and if forceid is true, student/employee ID also.
                   15950: A user's institutional affiliation(s) can also be updated.
                   15951: User information fields will not be overwritten with empty entries 
                   15952: unless the field is included in the $candelete array reference.
                   15953: This array is included when a single user is modified via "Manage Users",
                   15954: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 15955: 
                   15956: =item *
                   15957: 
1.286     matthew  15958: modifystudent
                   15959: 
1.957     raeburn  15960: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  15961: The course id is resolved based on the current user's environment.  
                   15962: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  15963: associated with a course.
                   15964: 
1.297     matthew  15965: This call is essentially a wrapper for lonnet::modifyuser and
                   15966: lonnet::modify_student_enrollment
1.286     matthew  15967: 
                   15968: Inputs: 
                   15969: 
                   15970: =over 4
                   15971: 
1.957     raeburn  15972: =item B<$udom> Student's loncapa domain
1.286     matthew  15973: 
1.957     raeburn  15974: =item B<$uname> Student's loncapa login name
1.286     matthew  15975: 
1.964     bisitz   15976: =item B<$uid> Student/Employee ID
1.286     matthew  15977: 
1.957     raeburn  15978: =item B<$umode> Student's authentication mode
1.286     matthew  15979: 
1.957     raeburn  15980: =item B<$upass> Student's password
1.286     matthew  15981: 
1.957     raeburn  15982: =item B<$first> Student's first name
1.286     matthew  15983: 
1.957     raeburn  15984: =item B<$middle> Student's middle name
1.286     matthew  15985: 
1.957     raeburn  15986: =item B<$last> Student's last name
1.286     matthew  15987: 
1.957     raeburn  15988: =item B<$gene> Student's generation
1.286     matthew  15989: 
1.957     raeburn  15990: =item B<$usec> Student's section in course
1.286     matthew  15991: 
                   15992: =item B<$end> Unix time of the roles expiration
                   15993: 
                   15994: =item B<$start> Unix time of the roles start date
                   15995: 
                   15996: =item B<$forceid> If defined, allow $uid to be changed
                   15997: 
                   15998: =item B<$desiredhome> server to use as home server for student
                   15999: 
1.957     raeburn  16000: =item B<$email> Student's permanent e-mail address
                   16001: 
                   16002: =item B<$type> Type of enrollment (auto or manual)
                   16003: 
1.963     raeburn  16004: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   16005: 
                   16006: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  16007: 
1.963     raeburn  16008: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  16009: 
1.963     raeburn  16010: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  16011: 
1.1172.2.19  raeburn  16012: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   16013: 
                   16014: =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  16015: 
1.286     matthew  16016: =back
1.297     matthew  16017: 
                   16018: =item *
                   16019: 
                   16020: modify_student_enrollment
                   16021: 
1.1172.2.31  raeburn  16022: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  16023: 'role.request.course' must be defined for this function to proceed.
                   16024: 
                   16025: Inputs:
                   16026: 
                   16027: =over 4
                   16028: 
1.1172.2.31  raeburn  16029: =item $udom, student's domain
1.297     matthew  16030: 
1.1172.2.31  raeburn  16031: =item $uname, student's name
1.297     matthew  16032: 
1.1172.2.31  raeburn  16033: =item $uid, student's user id
1.297     matthew  16034: 
1.1172.2.31  raeburn  16035: =item $first, student's first name
1.297     matthew  16036: 
                   16037: =item $middle
                   16038: 
                   16039: =item $last
                   16040: 
                   16041: =item $gene
                   16042: 
                   16043: =item $usec
                   16044: 
                   16045: =item $end
                   16046: 
                   16047: =item $start
                   16048: 
1.957     raeburn  16049: =item $type
                   16050: 
                   16051: =item $locktype
                   16052: 
                   16053: =item $cid
                   16054: 
                   16055: =item $selfenroll
                   16056: 
                   16057: =item $context
                   16058: 
1.1172.2.19  raeburn  16059: =item $credits, number of credits student will earn from this class
                   16060: 
1.1172.2.76  raeburn  16061: =item $instsec, institutional course section code for student
                   16062: 
1.297     matthew  16063: =back
                   16064: 
1.191     harris41 16065: 
                   16066: =item *
                   16067: 
1.243     albertel 16068: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   16069: custom role; give a custom role to a user for the level given by URL.  Specify
                   16070: name and domain of role author, and role name
1.191     harris41 16071: 
                   16072: =item *
                   16073: 
1.243     albertel 16074: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 16075: 
                   16076: =item *
                   16077: 
1.243     albertel 16078: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   16079: 
                   16080: =back
                   16081: 
                   16082: =head2 Course Infomation
                   16083: 
                   16084: =over 4
1.191     harris41 16085: 
                   16086: =item *
                   16087: 
1.1118    foxr     16088: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 16089: specified course id, including all environment settings for the
                   16090: course, the description of the course will be in the hash under the
                   16091: key 'description'
1.191     harris41 16092: 
1.1118    foxr     16093: $options is an optional parameter that if supplied is a hash reference that controls
                   16094: what how this function works.  It has the following key/values:
                   16095: 
                   16096: =over 4
                   16097: 
                   16098: =item freshen_cache
                   16099: 
                   16100: If defined, and the environment cache for the course is valid, it is 
                   16101: returned in the returned hash.
                   16102: 
                   16103: =item one_time
                   16104: 
                   16105: If defined, the last cache time is set to _now_
                   16106: 
                   16107: =item user
                   16108: 
                   16109: If defined, the supplied username is used instead of the current user.
                   16110: 
                   16111: 
                   16112: =back
                   16113: 
1.191     harris41 16114: =item *
                   16115: 
1.624     albertel 16116: resdata($name,$domain,$type,@which) : request for current parameter
                   16117: setting for a specific $type, where $type is either 'course' or 'user',
                   16118: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  16119: answers for 10 minutes.
1.243     albertel 16120: 
1.877     foxr     16121: =item *
                   16122: 
                   16123: get_courseresdata($courseid, $domain) : dump the entire course resource
                   16124: data base, returning a hash that is keyed by the resource name and has
                   16125: values that are the resource value.  I believe that the timestamps and
                   16126: versions are also returned.
                   16127: 
1.243     albertel 16128: =back
                   16129: 
                   16130: =head2 Course Modification
                   16131: 
                   16132: =over 4
1.191     harris41 16133: 
                   16134: =item *
                   16135: 
1.243     albertel 16136: writecoursepref($courseid,%prefs) : write preferences (environment
                   16137: database) for a course
1.191     harris41 16138: 
                   16139: =item *
                   16140: 
1.1011    raeburn  16141: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   16142: 
                   16143: =item *
                   16144: 
1.1038    raeburn  16145: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 16146: 
1.1167    droeschl 16147: =item *
                   16148: 
                   16149: is_course($courseid), is_course($cdom, $cnum)
                   16150: 
                   16151: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   16152: two component version $cdom, $cnum. It checks if the specified course exists.
                   16153: 
                   16154: Returns:
                   16155:     undef if the course doesn't exist, otherwise
                   16156:     in scalar context the combined courseid.
                   16157:     in list context the two components of the course identifier, domain and 
                   16158:     courseid.    
                   16159: 
1.243     albertel 16160: =back
                   16161: 
1.1172.2.109  raeburn  16162: =head2 Bubblesheet Configuration
                   16163: 
                   16164: =over 4
                   16165: 
                   16166: =item *
                   16167: 
                   16168: get_scantron_config($which)
                   16169: 
                   16170: $which - the name of the configuration to parse from the file.
                   16171: 
                   16172: Parses and returns the bubblesheet configuration line selected as a
                   16173: hash of configuration file fields.
                   16174: 
                   16175: 
                   16176: Returns:
                   16177:     If the named configuration is not in the file, an empty
                   16178:     hash is returned.
                   16179: 
                   16180:     a hash with the fields
                   16181:       name         - internal name for the this configuration setup
                   16182:       description  - text to display to operator that describes this config
                   16183:       CODElocation - if 0 or the string 'none'
                   16184:                           - no CODE exists for this config
                   16185:                      if -1 || the string 'letter'
                   16186:                           - a CODE exists for this config and is
                   16187:                             a string of letters
                   16188:                      Unsupported value (but planned for future support)
                   16189:                           if a positive integer
                   16190:                                - The CODE exists as the first n items from
                   16191:                                  the question section of the form
                   16192:                           if the string 'number'
                   16193:                                - The CODE exists for this config and is
                   16194:                                  a string of numbers
                   16195:       CODEstart   - (only matter if a CODE exists) column in the line where
                   16196:                      the CODE starts
                   16197:       CODElength  - length of the CODE
                   16198:       IDstart     - column where the student/employee ID starts
                   16199:       IDlength    - length of the student/employee ID info
                   16200:       Qstart      - column where the information from the bubbled
                   16201:                     'questions' start
                   16202:       Qlength     - number of columns comprising a single bubble line from
                   16203:                     the sheet. (usually either 1 or 10)
                   16204:       Qon         - either a single character representing the character used
                   16205:                     to signal a bubble was chosen in the positional setup, or
                   16206:                     the string 'letter' if the letter of the chosen bubble is
                   16207:                     in the final, or 'number' if a number representing the
                   16208:                     chosen bubble is in the file (1->A 0->J)
                   16209:       Qoff        - the character used to represent that a bubble was
                   16210:                     left blank
                   16211:       PaperID     - if the scanning process generates a unique number for each
                   16212:                     sheet scanned the column that this ID number starts in
                   16213:       PaperIDlength - number of columns that comprise the unique ID number
                   16214:                       for the sheet of paper
                   16215:       FirstName   - column that the first name starts in
                   16216:       FirstNameLength - number of columns that the first name spans
                   16217:       LastName    - column that the last name starts in
                   16218:       LastNameLength - number of columns that the last name spans
                   16219:       BubblesPerRow - number of bubbles available in each row used to
                   16220:                       bubble an answer. (If not specified, 10 assumed).
                   16221: 
                   16222: 
                   16223: =item *
                   16224: 
                   16225: get_scantronformat_file($cdom)
                   16226: 
                   16227: $cdom - the course's domain (optional); if not supplied, uses
                   16228: domain for current $env{'request.course.id'}.
                   16229: 
                   16230: Returns an array containing lines from the scantron format file for
                   16231: the domain of the course.
                   16232: 
                   16233: If a url for a custom.tab file is listed in domain's configuration.db,
                   16234: lines are from this file.
                   16235: 
                   16236: Otherwise, if a default.tab has been published in RES space by the
                   16237: domainconfig user, lines are from this file.
                   16238: 
                   16239: Otherwise, fall back to getting lines from the legacy file on the
                   16240: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   16241: 
                   16242: =back
                   16243: 
1.243     albertel 16244: =head2 Resource Subroutines
                   16245: 
                   16246: =over 4
1.191     harris41 16247: 
                   16248: =item *
                   16249: 
1.243     albertel 16250: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 16251: 
                   16252: =item *
                   16253: 
1.243     albertel 16254: repcopy($filename) : subscribes to the requested file, and attempts to
                   16255: replicate from the owning library server, Might return
1.607     raeburn  16256: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   16257: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 16258: resource. Expects the local filesystem pathname
                   16259: (/home/httpd/html/res/....)
                   16260: 
                   16261: =back
                   16262: 
                   16263: =head2 Resource Information
                   16264: 
                   16265: =over 4
1.191     harris41 16266: 
                   16267: =item *
                   16268: 
1.1172.2.28  raeburn  16269: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   16270: and returns the value of a variety of different possible values,
                   16271: $varname should be a request string, and the other parameters can be
                   16272: used to specify who and what one is asking about. Ordinarily, $cid 
                   16273: does not need to be specified, as it is retrived from 
                   16274: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   16275: within lonuserstate::loadmap() when initializing a course, before
                   16276: $env{'request.course.id'} has been set, so it needs to be provided
                   16277: in that one case.
1.243     albertel 16278: 
                   16279: Possible values for $varname are environment.lastname (or other item
                   16280: from the envirnment hash), user.name (or someother aspect about the
                   16281: user), resource.0.maxtries (or some other part and parameter of a
                   16282: resource)
1.204     albertel 16283: 
                   16284: =item *
                   16285: 
1.243     albertel 16286: directcondval($number) : get current value of a condition; reads from a state
                   16287: string
1.204     albertel 16288: 
                   16289: =item *
                   16290: 
1.243     albertel 16291: condval($condidx) : value of condition index based on state
1.204     albertel 16292: 
                   16293: =item *
                   16294: 
1.1172.2.146.  .13(raeb 16295:-23): metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 16296: resource's metadata, $what should be either a specific key, or either
                   16297: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1172.2.146.  .13(raeb 16298:-23): packages that this resource currently uses, the last 3 arguments are
                   16299:-23): only used internally for recursive metadata.
                   16300:-23): 
                   16301:-23): the toolsymb is only used where the uri is for an external tool (for which
                   16302:-23): the uri as well as the symb are guaranteed to be unique).
1.243     albertel 16303: 
                   16304: this function automatically caches all requests
1.191     harris41 16305: 
                   16306: =item *
                   16307: 
1.243     albertel 16308: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   16309: network of library servers; returns file handle of where SQL and regex results
                   16310: will be stored for query
1.191     harris41 16311: 
                   16312: =item *
                   16313: 
1.1172.2.66  raeburn  16314: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   16315: return symbolic list entry (all arguments optional).
                   16316: 
                   16317: Args: filename is the filename (including path) for the file for which a symb
                   16318: is required; donotrecurse, if true will prevent calls to allowed() being made
                   16319: to check access status if more than one resource was found in the bighash
                   16320: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   16321: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   16322: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   16323: cause possible symbs to be checked to determine if they are subject to content
                   16324: blocking, if so they will not be included as possible symbs; possibles is a
                   16325: ref to a hash, which, as a side effect, will be populated with all possible
                   16326: symbs (content blocking not tested).
                   16327: 
1.243     albertel 16328: returns the data handle
1.191     harris41 16329: 
                   16330: =item *
                   16331: 
1.1172.2.17  raeburn  16332: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  16333: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 16334: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  16335: on failure, user must be in a course, as it assumes the existence of
                   16336: the course initial hash, and uses $env('request.course.id'}.  The third
                   16337: arg is an optional reference to a scalar.  If this arg is passed in the
                   16338: call to symbverify, it will be set to 1 if the symb has been set to be 
                   16339: encrypted; otherwise it will be null.
1.243     albertel 16340: 
1.191     harris41 16341: =item *
                   16342: 
1.243     albertel 16343: symbclean($symb) : removes versions numbers from a symb, returns the
                   16344: cleaned symb
1.191     harris41 16345: 
                   16346: =item *
                   16347: 
1.243     albertel 16348: is_on_map($uri) : checks if the $uri is somewhere on the current
                   16349: course map, user must be in a course for it to work.
1.191     harris41 16350: 
                   16351: =item *
                   16352: 
1.243     albertel 16353: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 16354: 
                   16355: =item *
                   16356: 
1.243     albertel 16357: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   16358: a random seed, all arguments are optional, if they aren't sent it uses the
                   16359: environment to derive them. Note: if symb isn't sent and it can't get one
                   16360: from &symbread it will use the current time as its return value
1.191     harris41 16361: 
                   16362: =item *
                   16363: 
1.243     albertel 16364: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   16365: unfakeable, receipt
1.191     harris41 16366: 
                   16367: =item *
                   16368: 
1.620     albertel 16369: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 16370: 
                   16371: =item *
                   16372: 
1.243     albertel 16373: countacc($url) : count the number of accesses to a given URL
1.191     harris41 16374: 
                   16375: =item *
                   16376: 
1.243     albertel 16377: 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 16378: 
                   16379: =item *
                   16380: 
1.243     albertel 16381: 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 16382: 
                   16383: =item *
                   16384: 
1.243     albertel 16385: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 16386: 
                   16387: =item *
                   16388: 
1.243     albertel 16389: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   16390: forcing spreadsheet to reevaluate the resource scores next time.
                   16391: 
1.1172.2.13  raeburn  16392: =item *
                   16393: 
                   16394: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   16395: when viewing in course context.
                   16396: 
                   16397:  input: six args -- filename (decluttered), course number, course domain,
                   16398:                     url, symb (if registered) and group (if this is a
                   16399:                     group item -- e.g., bulletin board, group page etc.).
                   16400: 
                   16401:  output: array of five scalars --
                   16402:          $cfile -- url for file editing if editable on current server
                   16403:          $home -- homeserver of resource (i.e., for author if published,
                   16404:                                           or course if uploaded.).
                   16405:          $switchserver --  1 if server switch will be needed.
                   16406:          $forceedit -- 1 if icon/link should be to go to edit mode
                   16407:          $forceview -- 1 if icon/link should be to go to view mode
                   16408: 
                   16409: =item *
                   16410: 
                   16411: is_course_upload($file,$cnum,$cdom)
                   16412: 
                   16413: Used in course context to determine if current file was uploaded to
                   16414: the course (i.e., would be found in /userfiles/docs on the course's
                   16415: homeserver.
                   16416: 
                   16417:   input: 3 args -- filename (decluttered), course number and course domain.
                   16418:   output: boolean -- 1 if file was uploaded.
                   16419: 
1.243     albertel 16420: =back
                   16421: 
                   16422: =head2 Storing/Retreiving Data
                   16423: 
                   16424: =over 4
1.191     harris41 16425: 
                   16426: =item *
                   16427: 
1.1172.2.64  raeburn  16428: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   16429: permanently for this url; hashref needs to be given and should be a \%hashname;
                   16430: the remaining args aren't required and if they aren't passed or are '' they will
                   16431: be derived from the env (with the exception of $laststore, which is an
                   16432: optional arg used when a user's submission is stored in grading).
                   16433: $laststore is $version=$timestamp, where $version is the most recent version
                   16434: number retrieved for the corresponding $symb in the $namespace db file, and
                   16435: $timestamp is the timestamp for that transaction (UNIX time).
                   16436: $laststore is currently only passed when cstore() is called by
                   16437: structuretags::finalize_storage().
1.191     harris41 16438: 
                   16439: =item *
                   16440: 
1.1172.2.64  raeburn  16441: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   16442: but uses critical subroutine
1.191     harris41 16443: 
                   16444: =item *
                   16445: 
1.243     albertel 16446: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   16447: all args are optional
1.191     harris41 16448: 
                   16449: =item *
                   16450: 
1.717     albertel 16451: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   16452: dumps the complete (or key matching regexp) namespace into a hash
                   16453: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   16454: normally &store()ed into
                   16455: 
                   16456: $range should be either an integer '100' (give me the first 100
                   16457:                                            matching records)
                   16458:               or be  two integers sperated by a - with no spaces
                   16459:                  '30-50' (give me the 30th through the 50th matching
                   16460:                           records)
                   16461: 
                   16462: 
                   16463: =item *
                   16464: 
1.1172.2.59  raeburn  16465: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 16466: replaces a &store() version of data with a replacement set of data
                   16467: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  16468: reference. If $tolog is true, the transaction is logged in the courselog
                   16469: with an action=PUTSTORE.
1.717     albertel 16470: 
                   16471: =item *
                   16472: 
1.243     albertel 16473: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   16474: works very similar to store/cstore, but all data is stored in a
                   16475: temporary location and can be reset using tmpreset, $storehash should
                   16476: be a hash reference, returns nothing on success
1.191     harris41 16477: 
                   16478: =item *
                   16479: 
1.243     albertel 16480: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   16481: similar to restore, but all data is stored in a temporary location and
                   16482: can be reset using tmpreset. Returns a hash of values on success,
                   16483: error string otherwise.
1.191     harris41 16484: 
                   16485: =item *
                   16486: 
1.243     albertel 16487: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   16488: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 16489: 
                   16490: =item *
                   16491: 
1.243     albertel 16492: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16493: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 16494: 
                   16495: =item *
                   16496: 
1.243     albertel 16497: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   16498: namesp ($udom and $uname are optional)
1.191     harris41 16499: 
                   16500: =item *
                   16501: 
1.702     albertel 16502: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 16503: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 16504: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  16505: 
1.702     albertel 16506: $range should be either an integer '100' (give me the first 100
                   16507:                                            matching records)
                   16508:               or be  two integers sperated by a - with no spaces
                   16509:                  '30-50' (give me the 30th through the 50th matching
                   16510:                           records)
1.449     matthew  16511: =item *
                   16512: 
                   16513: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   16514: $store can be a scalar, an array reference, or if the amount to be 
                   16515: incremented is > 1, a hash reference.
                   16516: 
                   16517: ($udom and $uname are optional)
1.191     harris41 16518: 
                   16519: =item *
                   16520: 
1.243     albertel 16521: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   16522: ($udom and $uname are optional)
1.191     harris41 16523: 
                   16524: =item *
                   16525: 
1.243     albertel 16526: cput($namespace,$storehash,$udom,$uname) : critical put
                   16527: ($udom and $uname are optional)
1.191     harris41 16528: 
                   16529: =item *
                   16530: 
1.748     albertel 16531: newput($namespace,$storehash,$udom,$uname) :
                   16532: 
                   16533: Attempts to store the items in the $storehash, but only if they don't
                   16534: currently exist, if this succeeds you can be certain that you have 
                   16535: successfully created a new key value pair in the $namespace db.
                   16536: 
                   16537: 
                   16538: Args:
                   16539:  $namespace: name of database to store values to
                   16540:  $storehash: hashref to store to the db
                   16541:  $udom: (optional) domain of user containing the db
                   16542:  $uname: (optional) name of user caontaining the db
                   16543: 
                   16544: Returns:
                   16545:  'ok' -> succeeded in storing all keys of $storehash
                   16546:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   16547:                         least <key> already existed in the db (other
                   16548:                         requested keys may also already exist)
1.967     bisitz   16549:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 16550:  'con_lost' -> unable to contact request server
                   16551:  'refused' -> action was not allowed by remote machine
                   16552: 
                   16553: 
                   16554: =item *
                   16555: 
1.243     albertel 16556: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16557: reference filled in from namesp (encrypts the return communication)
                   16558: ($udom and $uname are optional)
1.191     harris41 16559: 
                   16560: =item *
                   16561: 
1.243     albertel 16562: log($udom,$name,$home,$message) : write to permanent log for user; use
                   16563: critical subroutine
                   16564: 
1.806     raeburn  16565: =item *
                   16566: 
1.860     raeburn  16567: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   16568: array reference filled in from namespace found in domain level on either
                   16569: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  16570: 
                   16571: =item *
                   16572: 
1.860     raeburn  16573: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   16574: domain level either on specified domain server ($uhome) or primary domain 
                   16575: server ($udom and $uhome are optional)
1.806     raeburn  16576: 
1.943     raeburn  16577: =item * 
                   16578: 
1.1172.2.35  raeburn  16579: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   16580: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   16581: the target domain.
                   16582: 
                   16583: May also include additional key => value pairs for the following groups:
                   16584: 
                   16585: =over
                   16586: 
                   16587: =item
                   16588: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   16589: 
                   16590: =over
                   16591: 
                   16592: =item defaultquota, authorquota
                   16593: 
                   16594: =back
                   16595: 
                   16596: =item
                   16597: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   16598: portfolio for users).
                   16599: 
                   16600: =over
                   16601: 
                   16602: =item
                   16603: aboutme, blog, webdav, portfolio
                   16604: 
                   16605: =back
                   16606: 
                   16607: =item
                   16608: requestcourses: ability to request courses, and how requests are processed.
                   16609: 
                   16610: =over
                   16611: 
                   16612: =item
1.1172.2.37  raeburn  16613: official, unofficial, community, textbook
1.1172.2.35  raeburn  16614: 
                   16615: =back
                   16616: 
                   16617: =item
                   16618: inststatus: types of institutional affiliation, and order in which they are displayed.
                   16619: 
                   16620: =over
                   16621: 
                   16622: =item
1.1172.2.44  raeburn  16623: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  16624: 
                   16625: =back
                   16626: 
                   16627: =item
                   16628: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   16629: for course's uploaded content.
                   16630: 
                   16631: =over
                   16632: 
                   16633: =item
1.1172.2.68  raeburn  16634: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   16635: communityquota, textbookquota
1.1172.2.35  raeburn  16636: 
                   16637: =back
                   16638: 
                   16639: =item
                   16640: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   16641: on your servers.
                   16642: 
                   16643: =over
                   16644: 
                   16645: =item
                   16646: remotesessions, hostedsessions
                   16647: 
                   16648: =back
                   16649: 
                   16650: =back
                   16651: 
                   16652: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   16653: utility to create a configuration.db file on a domain's primary library server
                   16654: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   16655: -- corresponding values are authentication type (internal, krb4, krb5,
                   16656: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   16657: will be available. Values are retrieved from cache (if current), unless the
                   16658: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   16659: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   16660: 
                   16661: Typical usage:
1.943     raeburn  16662: 
1.1172.2.35  raeburn  16663: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  16664: 
1.243     albertel 16665: =back
                   16666: 
                   16667: =head2 Network Status Functions
                   16668: 
                   16669: =over 4
1.191     harris41 16670: 
                   16671: =item *
                   16672: 
1.1137    raeburn  16673: dirlist() : return directory list based on URI (first arg).
                   16674: 
                   16675: Inputs: 1 required, 5 optional.
                   16676: 
                   16677: =over
                   16678: 
                   16679: =item 
                   16680: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   16681: 
                   16682: =item
                   16683: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   16684: 
                   16685: =item
                   16686: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   16687: 
                   16688: =item
                   16689: $getpropath - boolean: 1 if prepend path using &propath(). 
                   16690: 
                   16691: =item
                   16692: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   16693: 
                   16694: =item 
                   16695: $alternateRoot - path to prepend in place of path from $uri.
                   16696: 
                   16697: =back
                   16698: 
                   16699: Returns: Array of up to two items.
                   16700: 
                   16701: =over
                   16702: 
                   16703: a reference to an array of files/subdirectories
                   16704: 
                   16705: =over
                   16706: 
                   16707: Each element in the array of files/subdirectories is a & separated list of
                   16708: item name and the result of running stat on the item.  If dirlist was requested
                   16709: for a file instead of a directory, the item name will be ''. For a directory 
                   16710: listing, if the item is a metadata file, the element will end &N&M 
                   16711: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   16712: default copyright set (1).  
                   16713: 
                   16714: =back
                   16715: 
                   16716: a scalar containing error condition (if encountered).
                   16717: 
                   16718: =over
                   16719: 
                   16720: =item 
                   16721: no_host (no homeserver identified for $username:$domain).
                   16722: 
                   16723: =item 
                   16724: no_such_host (server contacted for listing not identified as valid host).
                   16725: 
                   16726: =item 
                   16727: con_lost (connection to remote server failed).
                   16728: 
                   16729: =item 
                   16730: refused (invalid $username:$domain received on lond side).
                   16731: 
                   16732: =item 
                   16733: no_such_dir (directory at specified path on lond side does not exist). 
                   16734: 
                   16735: =item 
                   16736: empty (directory at specified path on lond side is empty).
                   16737: 
                   16738: =over
                   16739: 
                   16740: This is currently not encountered because the &ls3, &ls2, 
                   16741: &ls (_handler) routines on the lond side do not filter out
                   16742: . and .. from a directory listing. 
                   16743: 
                   16744: =back
                   16745: 
                   16746: =back
                   16747: 
                   16748: =back
1.191     harris41 16749: 
                   16750: =item *
                   16751: 
1.243     albertel 16752: spareserver() : find server with least workload from spare.tab
                   16753: 
1.986     foxr     16754: 
                   16755: =item *
                   16756: 
                   16757: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   16758: if there is no corresponding loncapa host.
                   16759: 
1.243     albertel 16760: =back
                   16761: 
1.986     foxr     16762: 
1.243     albertel 16763: =head2 Apache Request
                   16764: 
                   16765: =over 4
1.191     harris41 16766: 
                   16767: =item *
                   16768: 
1.243     albertel 16769: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   16770: localhost, posts hash
                   16771: 
                   16772: =back
                   16773: 
                   16774: =head2 Data to String to Data
                   16775: 
                   16776: =over 4
1.191     harris41 16777: 
                   16778: =item *
                   16779: 
1.243     albertel 16780: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   16781: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 16782: 
                   16783: =item *
                   16784: 
1.243     albertel 16785: hashref2str($hashref) : convert a hashref into a string complete with
                   16786: escaping and '=' and '&' separators, supports elements that are
                   16787: arrayrefs and hashrefs
1.191     harris41 16788: 
                   16789: =item *
                   16790: 
1.243     albertel 16791: arrayref2str($arrayref) : convert an arrayref into a string complete
                   16792: with escaping and '&' separators, supports elements that are arrayrefs
                   16793: and hashrefs
1.191     harris41 16794: 
                   16795: =item *
                   16796: 
1.243     albertel 16797: str2hash($string) : convert string to hash using unescaping and
                   16798: splitting on '=' and '&', supports elements that are arrayrefs and
                   16799: hashrefs
1.191     harris41 16800: 
                   16801: =item *
                   16802: 
1.243     albertel 16803: str2array($string) : convert string to hash using unescaping and
                   16804: splitting on '&', supports elements that are arrayrefs and hashrefs
                   16805: 
                   16806: =back
                   16807: 
                   16808: =head2 Logging Routines
                   16809: 
                   16810: 
                   16811: These routines allow one to make log messages in the lonnet.log and
                   16812: lonnet.perm logfiles.
1.191     harris41 16813: 
1.1119    foxr     16814: =over 4
                   16815: 
1.191     harris41 16816: =item *
                   16817: 
1.243     albertel 16818: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 16819: 
                   16820: =item *
                   16821: 
1.243     albertel 16822: logthis() : append message to the normal lonnet.log file, it gets
                   16823: preiodically rolled over and deleted.
1.191     harris41 16824: 
                   16825: =item *
                   16826: 
1.243     albertel 16827: logperm() : append a permanent message to lonnet.perm.log, this log
                   16828: file never gets deleted by any automated portion of the system, only
                   16829: messages of critical importance should go in here.
                   16830: 
1.1119    foxr     16831: 
1.243     albertel 16832: =back
                   16833: 
                   16834: =head2 General File Helper Routines
                   16835: 
                   16836: =over 4
1.191     harris41 16837: 
                   16838: =item *
                   16839: 
1.481     raeburn  16840: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   16841: (a) files in /uploaded
                   16842:   (i) If a local copy of the file exists - 
                   16843:       compares modification date of local copy with last-modified date for 
                   16844:       definitive version stored on home server for course. If local copy is 
                   16845:       stale, requests a new version from the home server and stores it. 
                   16846:       If the original has been removed from the home server, then local copy 
                   16847:       is unlinked.
                   16848:   (ii) If local copy does not exist -
                   16849:       requests the file from the home server and stores it. 
                   16850:   
                   16851:   If $caller is 'uploadrep':  
                   16852:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   16853:     for request for files originally uploaded via DOCS. 
                   16854:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   16855:   
                   16856:   Otherwise:
                   16857:      This indicates a call from the content generation phase of the request.
                   16858:      -  returns the entire contents of the file or -1.
                   16859:      
                   16860: (b) files in /res
                   16861:    - returns the entire contents of a file or -1; 
                   16862:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 16863: 
1.712     albertel 16864: 
                   16865: =item *
                   16866: 
                   16867: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   16868:                   reference
                   16869: 
                   16870: returns either a stat() list of data about the file or an empty list
                   16871: if the file doesn't exist or couldn't find out about it (connection
                   16872: problems or user unknown)
                   16873: 
1.191     harris41 16874: =item *
                   16875: 
1.243     albertel 16876: filelocation($dir,$file) : returns file system location of a file
                   16877: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   16878: directory that relative $file lookups are to looked in ($dir of /a/dir
                   16879: and a file of ../bob will become /a/bob)
1.191     harris41 16880: 
                   16881: =item *
                   16882: 
                   16883: hreflocation($dir,$file) : returns file system location or a URL; same as
                   16884: filelocation except for hrefs
                   16885: 
                   16886: =item *
                   16887: 
1.1172.2.49  raeburn  16888: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   16889: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 16890: 
1.243     albertel 16891: =back
                   16892: 
1.608     albertel 16893: =head2 Usererfile file routines (/uploaded*)
                   16894: 
                   16895: =over 4
                   16896: 
                   16897: =item *
                   16898: 
                   16899: userfileupload(): main rotine for putting a file in a user or course's
                   16900:                   filespace, arguments are,
                   16901: 
1.620     albertel 16902:  formname - required - this is the name of the element in $env where the
1.608     albertel 16903:            filename, and the contents of the file to create/modifed exist
1.620     albertel 16904:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   16905:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  16906:  context - if coursedoc, store the file in the course of the active role
                   16907:              of the current user; 
                   16908:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   16909:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 16910:  subdir - required - subdirectory to put the file in under ../userfiles/
                   16911:          if undefined, it will be placed in "unknown"
                   16912: 
                   16913:  (This routine calls clean_filename() to remove any dangerous
                   16914:  characters from the filename, and then calls finuserfileupload() to
                   16915:  complete the transaction)
                   16916: 
                   16917:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16918:  and /adm/notfound.html if unsuccessful
                   16919: 
                   16920: =item *
                   16921: 
                   16922: clean_filename(): routine for cleaing a filename up for storage in
                   16923:                  userfile space, argument is:
                   16924: 
                   16925:  filename - proposed filename
                   16926: 
                   16927: returns: the new clean filename
                   16928: 
                   16929: =item *
                   16930: 
1.1090    raeburn  16931: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16932: userspace, probably shouldn't be called directly
                   16933: 
                   16934:   docuname: username or courseid of destination for the file
                   16935:   docudom: domain of user/course of destination for the file
                   16936:   formname: same as for userfileupload()
1.1090    raeburn  16937:   fname: filename (including subdirectories) for the file
                   16938:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  16939:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16940:   allfiles: reference to hash used to store objects found by parser
                   16941:   codebase: reference to hash used for codebases of java objects found by parser
                   16942:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16943:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16944:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   16945:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   16946:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   16947:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  16948:   mimetype: reference to scalar to accommodate mime type determined
                   16949:             from File::MMagic if $parser = parse.
1.608     albertel 16950: 
                   16951:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  16952:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   16953:  was 'overwrite').
                   16954:  
1.608     albertel 16955: 
                   16956: =item *
                   16957: 
                   16958: renameuserfile(): renames an existing userfile to a new name
                   16959: 
                   16960:   Args:
                   16961:    docuname: username or courseid of destination for the file
                   16962:    docudom: domain of user/course of destination for the file
                   16963:    old: current file name (including any subdirs under userfiles)
                   16964:    new: desired file name (including any subdirs under userfiles)
                   16965: 
                   16966: =item *
                   16967: 
                   16968: mkdiruserfile(): creates a directory is a userfiles dir
                   16969: 
                   16970:   Args:
                   16971:    docuname: username or courseid of destination for the file
                   16972:    docudom: domain of user/course of destination for the file
                   16973:    dir: dir to create (including any subdirs under userfiles)
                   16974: 
                   16975: =item *
                   16976: 
                   16977: removeuserfile(): removes a file that exists in userfiles
                   16978: 
                   16979:   Args:
                   16980:    docuname: username or courseid of destination for the file
                   16981:    docudom: domain of user/course of destination for the file
                   16982:    fname: filname to delete (including any subdirs under userfiles)
                   16983: 
                   16984: =item *
                   16985: 
                   16986: removeuploadedurl(): convience function for removeuserfile()
                   16987: 
                   16988:   Args:
                   16989:    url:  a full /uploaded/... url to delete
                   16990: 
1.747     albertel 16991: =item * 
                   16992: 
                   16993: get_portfile_permissions():
                   16994:   Args:
                   16995:     domain: domain of user or course contain the portfolio files
                   16996:     user: name of user or num of course contain the portfolio files
                   16997:   Returns:
                   16998:     hashref of a dump of the proper file_permissions.db
                   16999:    
                   17000: 
                   17001: =item * 
                   17002: 
                   17003: get_access_controls():
                   17004: 
                   17005: Args:
                   17006:   current_permissions: the hash ref returned from get_portfile_permissions()
                   17007:   group: (optional) the group you want the files associated with
                   17008:   file: (optional) the file you want access info on
                   17009: 
                   17010: Returns:
1.749     raeburn  17011:     a hash (keys are file names) of hashes containing
                   17012:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   17013:         values are XML containing access control settings (see below) 
1.747     albertel 17014: 
                   17015: Internal notes:
                   17016: 
1.749     raeburn  17017:  access controls are stored in file_permissions.db as key=value pairs.
                   17018:     key -> path to file/file_name\0uniqueID:scope_end_start
                   17019:         where scope -> public,guest,course,group,domains or users.
                   17020:               end -> UNIX time for end of access (0 -> no end date)
                   17021:               start -> UNIX time for start of access
                   17022: 
                   17023:     value -> XML description of access control
                   17024:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   17025:             <start></start>
                   17026:             <end></end>
                   17027: 
                   17028:             <password></password>  for scope type = guest
                   17029: 
                   17030:             <domain></domain>     for scope type = course or group
                   17031:             <number></number>
                   17032:             <roles id="">
                   17033:              <role></role>
                   17034:              <access></access>
                   17035:              <section></section>
                   17036:              <group></group>
                   17037:             </roles>
                   17038: 
                   17039:             <dom></dom>         for scope type = domains
                   17040: 
                   17041:             <users>             for scope type = users
                   17042:              <user>
                   17043:               <uname></uname>
                   17044:               <udom></udom>
                   17045:              </user>
                   17046:             </users>
                   17047:            </scope> 
                   17048:               
                   17049:  Access data is also aggregated for each file in an additional key=value pair:
                   17050:  key -> path to file/file_name\0accesscontrol 
                   17051:  value -> reference to hash
                   17052:           hash contains key = value pairs
                   17053:           where key = uniqueID:scope_end_start
                   17054:                 value = UNIX time record was last updated
                   17055: 
                   17056:           Used to improve speed of look-ups of access controls for each file.  
                   17057:  
                   17058:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   17059: 
1.1172.2.13  raeburn  17060: =item *
                   17061: 
1.749     raeburn  17062: modify_access_controls():
                   17063: 
                   17064: Modifies access controls for a portfolio file
                   17065: Args
                   17066: 1. file name
                   17067: 2. reference to hash of required changes,
                   17068: 3. domain
                   17069: 4. username
                   17070:   where domain,username are the domain of the portfolio owner 
                   17071:   (either a user or a course) 
                   17072: 
                   17073: Returns:
                   17074: 1. result of additions or updates ('ok' or 'error', with error message). 
                   17075: 2. result of deletions ('ok' or 'error', with error message).
                   17076: 3. reference to hash of any new or updated access controls.
                   17077: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   17078:    key = integer (inbound ID)
1.1172.2.13  raeburn  17079:    value = uniqueID
                   17080: 
                   17081: =item *
                   17082: 
                   17083: get_timebased_id():
                   17084: 
                   17085: Attempts to get a unique timestamp-based suffix for use with items added to a
                   17086: course via the Course Editor (e.g., folders, composite pages,
                   17087: group bulletin boards).
                   17088: 
                   17089: Args: (first three required; six others optional)
                   17090: 
                   17091: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   17092:    docssequence, or name of group
                   17093: 
                   17094: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   17095:    e.g., num, boardids
                   17096: 
                   17097: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   17098:    file will be named nohist_namespace.db
                   17099: 
                   17100: 4. cdom: domain of course; default is current course domain from %env
                   17101: 
                   17102: 5. cnum: course number; default is current course number from %env
                   17103: 
                   17104: 6. idtype: set to concat if an additional digit is to be appended to the
                   17105:    unix timestamp to form the suffix, if the plain timestamp is already
                   17106:    in use.  Default is to not do this, but simply increment the unix
                   17107:    timestamp by 1 until a unique key is obtained.
                   17108: 
                   17109: 7. who: holder of locking key; defaults to user:domain for user.
                   17110: 
                   17111: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   17112:    retrying); default is 3.
                   17113: 
                   17114: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   17115: 
                   17116: Returns:
                   17117: 
                   17118: 1. suffix obtained (numeric)
                   17119: 
                   17120: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   17121: 
                   17122: 3. error: contains (localized) error message if an error occurred.
                   17123: 
1.747     albertel 17124: 
1.608     albertel 17125: =back
                   17126: 
1.243     albertel 17127: =head2 HTTP Helper Routines
                   17128: 
                   17129: =over 4
                   17130: 
1.191     harris41 17131: =item *
                   17132: 
                   17133: escape() : unpack non-word characters into CGI-compatible hex codes
                   17134: 
                   17135: =item *
                   17136: 
                   17137: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   17138: 
1.243     albertel 17139: =back
                   17140: 
                   17141: =head1 PRIVATE SUBROUTINES
                   17142: 
                   17143: =head2 Underlying communication routines (Shouldn't call)
                   17144: 
                   17145: =over 4
                   17146: 
                   17147: =item *
                   17148: 
                   17149: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   17150: 
                   17151: =item *
                   17152: 
                   17153: reply() : uses subreply to send a message to remote machine, logs all failures
                   17154: 
                   17155: =item *
                   17156: 
                   17157: critical() : passes a critical message to another server; if cannot
                   17158: get through then place message in connection buffer directory and
                   17159: returns con_delayed, if incapable of saving message, returns
                   17160: con_failed
                   17161: 
                   17162: =item *
                   17163: 
                   17164: reconlonc() : tries to reconnect lonc client processes.
                   17165: 
                   17166: =back
                   17167: 
                   17168: =head2 Resource Access Logging
                   17169: 
                   17170: =over 4
                   17171: 
                   17172: =item *
                   17173: 
                   17174: flushcourselogs() : flush (save) buffer logs and access logs
                   17175: 
                   17176: =item *
                   17177: 
                   17178: courselog($what) : save message for course in hash
                   17179: 
                   17180: =item *
                   17181: 
                   17182: courseacclog($what) : save message for course using &courselog().  Perform
                   17183: special processing for specific resource types (problems, exams, quizzes, etc).
                   17184: 
1.191     harris41 17185: =item *
                   17186: 
                   17187: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   17188: as a PerlChildExitHandler
1.243     albertel 17189: 
                   17190: =back
                   17191: 
                   17192: =head2 Other
                   17193: 
                   17194: =over 4
                   17195: 
                   17196: =item *
                   17197: 
                   17198: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 17199: 
                   17200: =back
                   17201: 
                   17202: =cut
1.877     foxr     17203: 

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