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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.146.  .18(raeb    4:-24): # $Id: lonnet.pm,v 1.1172.2.146.2.17 2024/02/25 05:55:09 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
1.1172.2.107  raeburn    77: use CGI::Cookie;
1.977     amueller   78: 
1.1172.2.104  raeburn    79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138    raeburn    80:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1172.2.114  raeburn    81:             %managerstab $passwdmin);
1.871     albertel   82: 
                     83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     84:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     85:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        86:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        87: 
1.1       albertel   88: use IO::Socket;
1.31      www        89: use GDBM_File;
1.208     albertel   90: use HTML::LCParser;
1.88      www        91: use Fcntl qw(:flock);
1.870     albertel   92: use Storable qw(thaw nfreeze);
1.1172.2.79  raeburn    93: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   94: use Cache::Memcached;
1.676     albertel   95: use Digest::MD5;
1.790     albertel   96: use Math::Random;
1.1024    raeburn    97: use File::MMagic;
1.1172.2.142  raeburn    98: use Net::CIDR;
                     99: use Sys::Hostname::FQDN();
1.807     albertel  100: use LONCAPA qw(:DEFAULT :match);
1.740     www       101: use LONCAPA::Configuration;
1.1160    www       102: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   103: use LONCAPA::Lond;
1.1172.2.110  raeburn   104: use LONCAPA::transliterate;
1.1117    foxr      105: 
1.1090    raeburn   106: use File::Copy;
1.676     albertel  107: 
1.195     www       108: my $readit;
1.1172.2.79  raeburn   109: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  110: 
1.619     albertel  111: require Exporter;
                    112: 
                    113: our @ISA = qw (Exporter);
                    114: our @EXPORT = qw(%env);
                    115: 
1.1172.2.9  raeburn   116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       117: {
                    118:     my $logid;
1.1172.2.9  raeburn   119:     sub write_log {
                    120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    121:         if ($context eq 'course') {
                    122:             if (($cnum eq '') || ($cdom eq '')) {
                    123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    125:             }
1.957     raeburn   126:         }
1.1172.2.13  raeburn   127: 	$logid ++;
1.957     raeburn   128:         my $now = time();
                    129: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.146.  .1(raebu  130:22):         my $ip = &get_requestor_ip();
1.1172.2.9  raeburn   131:         my $logentry = {
                    132:                          $id => {
                    133:                                   'exe_uname' => $env{'user.name'},
                    134:                                   'exe_udom'  => $env{'user.domain'},
                    135:                                   'exe_time'  => $now,
1.1172.2.134  raeburn   136:                                   'exe_ip'    => $ip,
1.1172.2.9  raeburn   137:                                   'delflag'   => $delflag,
                    138:                                   'logentry'  => $storehash,
                    139:                                   'uname'     => $uname,
                    140:                                   'udom'      => $udom,
                    141:                                 }
                    142:                        };
                    143:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       144:     }
                    145: }
1.1       albertel  146: 
1.163     harris41  147: sub logtouch {
                    148:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  149:     unless (-e "$execdir/logs/lonnet.log") {	
1.1172.2.96  raeburn   150: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  151: 	close $fh;
                    152:     }
                    153:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    154:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    155: }
                    156: 
1.1       albertel  157: sub logthis {
                    158:     my $message=shift;
                    159:     my $execdir=$perlvar{'lonDaemons'};
                    160:     my $now=time;
                    161:     my $local=localtime($now);
1.1172.2.96  raeburn   162:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      163: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    164: 	print $fh $logstring;
1.448     albertel  165: 	close($fh);
                    166:     }
1.1       albertel  167:     return 1;
                    168: }
                    169: 
                    170: sub logperm {
                    171:     my $message=shift;
                    172:     my $execdir=$perlvar{'lonDaemons'};
                    173:     my $now=time;
                    174:     my $local=localtime($now);
1.1172.2.96  raeburn   175:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  176: 	print $fh "$now:$message:$local\n";
                    177: 	close($fh);
                    178:     }
1.1       albertel  179:     return 1;
                    180: }
                    181: 
1.850     albertel  182: sub create_connection {
1.853     albertel  183:     my ($hostname,$lonid) = @_;
1.851     albertel  184:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  185: 				     Type    => SOCK_STREAM,
                    186: 				     Timeout => 10);
                    187:     return 0 if (!$client);
1.890     albertel  188:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  189:     my $result = <$client>;
                    190:     chomp($result);
                    191:     return 1 if ($result eq 'done');
                    192:     return 0;
                    193: }
                    194: 
1.983     raeburn   195: sub get_server_timezone {
                    196:     my ($cnum,$cdom) = @_;
                    197:     my $home=&homeserver($cnum,$cdom);
                    198:     if ($home ne 'no_host') {
                    199:         my $cachetime = 24*3600;
                    200:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    201:         if (defined($cached)) {
                    202:             return $timezone;
                    203:         } else {
                    204:             my $timezone = &reply('servertimezone',$home);
                    205:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    206:         }
                    207:     }
                    208: }
1.850     albertel  209: 
1.1106    raeburn   210: sub get_server_distarch {
                    211:     my ($lonhost,$ignore_cache) = @_;
                    212:     if (defined($lonhost)) {
                    213:         if (!defined(&hostname($lonhost))) {
                    214:             return;
                    215:         }
                    216:         my $cachetime = 12*3600;
                    217:         if (!$ignore_cache) {
                    218:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    219:             if (defined($cached)) {
                    220:                 return $distarch;
                    221:             }
                    222:         }
                    223:         my $rep = &reply('serverdistarch',$lonhost);
                    224:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    225:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    226:                 $rep eq '') {
                    227:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    228:         }
                    229:     }
                    230:     return;
                    231: }
                    232: 
1.993     raeburn   233: sub get_server_loncaparev {
1.1073    raeburn   234:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   235:     if (defined($lonhost)) {
                    236:         if (!defined(&hostname($lonhost))) {
                    237:             undef($lonhost);
                    238:         }
                    239:     }
                    240:     if (!defined($lonhost)) {
                    241:         if (defined(&domain($dom,'primary'))) {
                    242:             $lonhost=&domain($dom,'primary');
                    243:             if ($lonhost eq 'no_host') {
                    244:                 undef($lonhost);
                    245:             }
                    246:         }
                    247:     }
                    248:     if (defined($lonhost)) {
1.1073    raeburn   249:         my $cachetime = 12*3600;
                    250:         if (!$ignore_cache) {
                    251:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    252:             if (defined($cached)) {
                    253:                 return $loncaparev;
                    254:             }
                    255:         }
                    256:         my ($answer,$loncaparev);
                    257:         my @ids=&current_machine_ids();
                    258:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    259:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   260:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   261:                 $loncaparev = $1;
                    262:             }
                    263:         } else {
                    264:             $answer = &reply('serverloncaparev',$lonhost);
                    265:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    266:                 if ($caller eq 'loncron') {
                    267:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   268:                     $ua->timeout(4);
1.1172.2.120  raeburn   269:                     my $hostname = &hostname($lonhost);
1.1073    raeburn   270:                     my $protocol = $protocol{$lonhost};
                    271:                     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn   272:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   273:                     my $request=new HTTP::Request('GET',$url);
                    274:                     my $response=$ua->request($request);
                    275:                     unless ($response->is_error()) {
                    276:                         my $content = $response->content;
1.1081    raeburn   277:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   278:                             $loncaparev = $1;
                    279:                         }
                    280:                     }
                    281:                 } else {
                    282:                     $loncaparev = $loncaparevs{$lonhost};
                    283:                 }
1.1081    raeburn   284:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   285:                 $loncaparev = $1;
                    286:             }
1.993     raeburn   287:         }
1.1073    raeburn   288:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   289:     }
                    290: }
                    291: 
1.1074    raeburn   292: sub get_server_homeID {
                    293:     my ($hostname,$ignore_cache,$caller) = @_;
                    294:     unless ($ignore_cache) {
                    295:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    296:         if (defined($cached)) {
                    297:             return $serverhomeID;
                    298:         }
                    299:     }
                    300:     my $cachetime = 12*3600;
                    301:     my $serverhomeID;
                    302:     if ($caller eq 'loncron') { 
                    303:         my @machine_ids = &machine_ids($hostname);
                    304:         foreach my $id (@machine_ids) {
                    305:             my $response = &reply('serverhomeID',$id);
                    306:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    307:                 $serverhomeID = $response;
                    308:                 last;
                    309:             }
                    310:         }
                    311:         if ($serverhomeID eq '') {
                    312:             $serverhomeID = $machine_ids[-1];
                    313:         }
                    314:     } else {
                    315:         $serverhomeID = $serverhomeIDs{$hostname};
                    316:     }
                    317:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    318: }
                    319: 
1.1121    raeburn   320: sub get_remote_globals {
                    321:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   322:     my ($result,%returnhash,%whatneeded);
                    323:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   324:         foreach my $what (sort(keys(%{$whathash}))) {
                    325:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   326:             my ($response,$cached);
1.1121    raeburn   327:             unless ($ignore_cache) {
1.1125    raeburn   328:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   329:             }
                    330:             if (defined($cached)) {
1.1125    raeburn   331:                 $returnhash{$what} = $response;
1.1121    raeburn   332:             } else {
1.1125    raeburn   333:                 $whatneeded{$what} = 1;
1.1121    raeburn   334:             }
                    335:         }
1.1125    raeburn   336:         if (keys(%whatneeded) == 0) {
                    337:             $result = 'ok';
                    338:         } else {
1.1121    raeburn   339:             my $requested = &freeze_escape(\%whatneeded);
                    340:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   341:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    342:                 ($rep eq 'unknown_cmd')) {
                    343:                 $result = $rep;
                    344:             } else {
                    345:                 $result = 'ok';
1.1121    raeburn   346:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   347:                 foreach my $item (@pairs) {
                    348:                     my ($key,$value)=split(/=/,$item,2);
                    349:                     my $what = &unescape($key);
                    350:                     my $hashid = $lonhost.'-'.$what;
                    351:                     $returnhash{$what}=&thaw_unescape($value);
                    352:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   353:                 }
                    354:             }
                    355:         }
                    356:     }
1.1125    raeburn   357:     return ($result,\%returnhash);
1.1121    raeburn   358: }
                    359: 
1.1124    raeburn   360: sub remote_devalidate_cache {
1.1172.2.35  raeburn   361:     my ($lonhost,$cachekeys) = @_;
                    362:     my $items;
                    363:     return unless (ref($cachekeys) eq 'ARRAY');
                    364:     my $cachestr = join('&',@{$cachekeys});
                    365:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   366: }
                    367: 
1.1172.2.146.  .13(raeb  368:-23): sub sign_lti {
                    369:-23):     my ($cdom,$cnum,$crsdef,$type,$context,$url,$ltinum,$keynum,$paramsref,$inforef) = @_;
                    370:-23):     my $chome;
                    371:-23):     if (&domain($cdom) ne '') {
                    372:-23):         if ($crsdef) {
                    373:-23):             $chome = &homeserver($cnum,$cdom);
                    374:-23):         } else {
                    375:-23):             $chome = &domain($cdom,'primary');
                    376:-23):         }
                    377:-23):     }
                    378:-23):     if ($cdom && $chome && ($chome ne 'no_host')) {
                    379:-23):         if ((ref($paramsref) eq 'HASH') &&
                    380:-23):             (ref($inforef) eq 'HASH')) {
                    381:-23):             my $rep;
                    382:-23):             if (grep { $_ eq $chome } &current_machine_ids()) {
                    383:-23):                 # domain information is hosted on this machine
                    384:-23):                 $rep =
                    385:-23):                     &LONCAPA::Lond::sign_lti_payload($cdom,$cnum,$crsdef,$type,
                    386:-23):                                                      $context,$url,$ltinum,$keynum,
                    387:-23):                                                      $perlvar{'lonVersion'},
                    388:-23):                                                      $paramsref,$inforef);
                    389:-23):                 if (ref($rep) eq 'HASH') {
                    390:-23):                     return ('ok',$rep);
                    391:-23):                 }
                    392:-23):             } else {
                    393:-23):                 my ($escurl,$params,$info);
                    394:-23):                 $escurl = &escape($url);
                    395:-23):                 if (ref($paramsref) eq 'HASH') {
                    396:-23):                     $params = &freeze_escape($paramsref);
                    397:-23):                 }
                    398:-23):                 if (ref($inforef) eq 'HASH') {
                    399:-23):                     $info = &freeze_escape($inforef);
                    400:-23):                 }
                    401:-23):                 $rep=&reply("encrypt:signlti:$cdom:$cnum:$crsdef:$type:$context:$escurl:$ltinum:$keynum:$params:$info",$chome);
                    402:-23):             }
                    403:-23):             if (($rep eq '') || ($rep =~ /^con_lost|error|no_such_host|unknown_cmd/i)) {
                    404:-23):                 return ();
                    405:-23):             } elsif (($inforef->{'respfmt'} eq 'to_post_body') ||
                    406:-23):                      ($inforef->{'respfmt'} eq 'to_authorization_header')) {
                    407:-23):                 return ('ok',$rep);
                    408:-23):             } else {
                    409:-23):                 my %returnhash;
                    410:-23):                 foreach my $item (split(/\&/,$rep)) {
                    411:-23):                     my ($name,$value)=split(/\=/,$item);
                    412:-23):                     $returnhash{&unescape($name)}=&thaw_unescape($value);
                    413:-23):                 }
                    414:-23):                 return('ok',\%returnhash);
                    415:-23):             }
                    416:-23):         } else {
                    417:-23):             return ();
                    418:-23):         }
                    419:-23):     } else {
                    420:-23):         return ();
                    421:-23):         &logthis("sign_lti failed - no homeserver and/or domain ($cdom) ($chome)");
                    422:-23):     }
                    423:-23): }
                    424:-23): 
1.1       albertel  425: # -------------------------------------------------- Non-critical communication
                    426: sub subreply {
                    427:     my ($cmd,$server)=@_;
1.838     albertel  428:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      429:     #
                    430:     #  With loncnew process trimming, there's a timing hole between lonc server
                    431:     #  process exit and the master server picking up the listen on the AF_UNIX
                    432:     #  socket.  In that time interval, a lock file will exist:
                    433: 
                    434:     my $lockfile=$peerfile.".lock";
                    435:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   436: 	sleep(0.1);
1.549     foxr      437:     }
                    438:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      439:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      440:     #
1.550     foxr      441:     #   We'll give the connection a few tries before abandoning it.  If
                    442:     #   connection is not possible, we'll con_lost back to the client.
                    443:     #   
                    444:     my $client;
                    445:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    446: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    447: 				      Type    => SOCK_STREAM,
                    448: 				      Timeout => 10);
1.869     albertel  449: 	if ($client) {
1.550     foxr      450: 	    last;		# Connected!
1.850     albertel  451: 	} else {
1.853     albertel  452: 	    &create_connection(&hostname($server),$server);
1.550     foxr      453: 	}
1.1172.2.79  raeburn   454:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      455:     }
                    456:     my $answer;
                    457:     if ($client) {
1.704     albertel  458: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      459: 	$answer=<$client>;
                    460: 	if (!$answer) { $answer="con_lost"; }
                    461: 	chomp($answer);
                    462:     } else {
                    463: 	$answer = 'con_lost';	# Failed connection.
                    464:     }
1.1       albertel  465:     return $answer;
                    466: }
                    467: 
                    468: sub reply {
                    469:     my ($cmd,$server)=@_;
1.838     albertel  470:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  471:     my $answer=subreply($cmd,$server);
1.65      www       472:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111  raeburn   473:         my $logged = $cmd;
                    474:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    475:             my $subcmd = $1;
                    476:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    477:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1172.2.146.  .13(raeb  478:-23):                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
                    479:-23):                 ($subcmd eq 'put')) {
1.1172.2.111  raeburn   480:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    481:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    482:                     splice(@rest,2,1,'Hidden');
                    483:                 } elsif ($subcmd eq 'passwd') {
                    484:                     splice(@rest,2,2,('Hidden','Hidden'));
                    485:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1172.2.146.  .13(raeb  486:-23):                          ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
1.1172.2.111  raeburn   487:                     splice(@rest,3,1,'Hidden');
                    488:                 }
                    489:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    490:             }
                    491:         }
                    492:         &logthis("<font color=\"blue\">WARNING:".
                    493:                  " $logged to $server returned $answer</font>");
1.12      www       494:     }
1.1       albertel  495:     return $answer;
                    496: }
                    497: 
                    498: # ----------------------------------------------------------- Send USR1 to lonc
                    499: 
                    500: sub reconlonc {
1.891     albertel  501:     my ($lonid) = @_;
                    502:     if ($lonid) {
1.1172.2.72  raeburn   503:         my $hostname = &hostname($lonid);
1.891     albertel  504: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    505: 	if ($hostname && -e $peerfile) {
                    506: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    507: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    508: 					     Type    => SOCK_STREAM,
                    509: 					     Timeout => 10);
                    510: 	    if ($client) {
                    511: 		print $client ("reset_retries\n");
                    512: 		my $answer=<$client>;
                    513: 		#reset just this one.
                    514: 	    }
                    515: 	}
                    516: 	return;
                    517:     }
                    518: 
1.836     www       519:     &logthis("Trying to reconnect lonc");
1.1       albertel  520:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96  raeburn   521:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  522: 	my $loncpid=<$fh>;
                    523:         chomp($loncpid);
                    524:         if (kill 0 => $loncpid) {
                    525: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    526:             kill USR1 => $loncpid;
                    527:             sleep 1;
1.836     www       528:          } else {
1.12      www       529: 	    &logthis(
1.672     albertel  530:                "<font color=\"blue\">WARNING:".
1.12      www       531:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  532:         }
                    533:     } else {
1.836     www       534: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  535:     }
                    536: }
                    537: 
                    538: # ------------------------------------------------------ Critical communication
1.12      www       539: 
1.1       albertel  540: sub critical {
                    541:     my ($cmd,$server)=@_;
1.838     albertel  542:     unless (&hostname($server)) {
1.672     albertel  543:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       544:                " Critical message to unknown server ($server)</font>");
                    545:         return 'no_such_host';
                    546:     }
1.1       albertel  547:     my $answer=reply($cmd,$server);
                    548:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   549: 	&reconlonc($server);
1.589     albertel  550: 	my $answer=reply($cmd,$server);
1.1       albertel  551:         if ($answer eq 'con_lost') {
                    552:             my $now=time;
                    553:             my $middlename=$cmd;
1.5       www       554:             $middlename=substr($middlename,0,16);
1.1       albertel  555:             $middlename=~s/\W//g;
                    556:             my $dfilename=
1.305     www       557:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    558:             $dumpcount++;
1.1       albertel  559:             {
1.448     albertel  560: 		my $dfh;
1.1172.2.96  raeburn   561: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  562: 		    print $dfh "$cmd\n"; 
                    563: 		    close($dfh);
                    564: 		}
1.1       albertel  565:             }
1.1172.2.79  raeburn   566:             sleep 1;
1.1       albertel  567:             my $wcmd='';
                    568:             {
1.448     albertel  569: 		my $dfh;
1.1172.2.96  raeburn   570: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  571: 		    $wcmd=<$dfh>; 
                    572: 		    close($dfh);
                    573: 		}
1.1       albertel  574:             }
                    575:             chomp($wcmd);
1.7       www       576:             if ($wcmd eq $cmd) {
1.672     albertel  577: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       578:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  579:                 &logperm("D:$server:$cmd");
                    580: 	        return 'con_delayed';
                    581:             } else {
1.672     albertel  582:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       583:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  584:                 &logperm("F:$server:$cmd");
                    585:                 return 'con_failed';
                    586:             }
                    587:         }
                    588:     }
                    589:     return $answer;
1.405     albertel  590: }
                    591: 
1.755     albertel  592: # ------------------------------------------- check if return value is an error
                    593: 
                    594: sub error {
                    595:     my ($result) = @_;
1.756     albertel  596:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  597: 	if ($2 == 2) { return undef; }
                    598: 	return $1;
                    599:     }
                    600:     return undef;
                    601: }
                    602: 
1.783     albertel  603: sub convert_and_load_session_env {
                    604:     my ($lonidsdir,$handle)=@_;
                    605:     my @profile;
                    606:     {
1.917     albertel  607: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    608: 	if (!$opened) {
1.915     albertel  609: 	    return 0;
                    610: 	}
1.783     albertel  611: 	flock($idf,LOCK_SH);
                    612: 	@profile=<$idf>;
                    613: 	close($idf);
                    614:     }
                    615:     my %temp_env;
                    616:     foreach my $line (@profile) {
1.786     albertel  617: 	if ($line !~ m/=/) {
                    618: 	    return 0;
                    619: 	}
1.783     albertel  620: 	chomp($line);
                    621: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    622: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    623:     }
                    624:     unlink("$lonidsdir/$handle.id");
                    625:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    626: 	    0640)) {
                    627: 	%disk_env = %temp_env;
                    628: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    629: 	untie(%disk_env);
                    630:     }
1.786     albertel  631:     return 1;
1.783     albertel  632: }
                    633: 
1.374     www       634: # ------------------------------------------- Transfer profile into environment
1.780     albertel  635: my $env_loaded;
                    636: sub transfer_profile_to_env {
1.788     albertel  637:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    638:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       639: 
1.720     albertel  640:     if (!defined($lonidsdir)) {
                    641: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    642:     }
                    643:     if (!defined($handle)) {
                    644:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    645:     }
                    646: 
1.786     albertel  647:     my $convert;
                    648:     {
1.917     albertel  649:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    650: 	if (!$opened) {
1.915     albertel  651: 	    return;
                    652: 	}
1.786     albertel  653: 	flock($idf,LOCK_SH);
                    654: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    655: 		&GDBM_READER(),0640)) {
                    656: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    657: 	    untie(%disk_env);
                    658: 	} else {
                    659: 	    $convert = 1;
                    660: 	}
                    661:     }
                    662:     if ($convert) {
                    663: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    664: 	    &logthis("Failed to load session, or convert session.");
                    665: 	}
1.374     www       666:     }
1.783     albertel  667: 
1.786     albertel  668:     my %remove;
1.783     albertel  669:     while ( my $envname = each(%env) ) {
1.433     matthew   670:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    671:             if ($time < time-300) {
1.783     albertel  672:                 $remove{$key}++;
1.433     matthew   673:             }
                    674:         }
                    675:     }
1.783     albertel  676: 
1.619     albertel  677:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  678:     $env_loaded=1;
1.783     albertel  679:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   680:         &delenv($expired_key);
1.374     www       681:     }
1.1       albertel  682: }
                    683: 
1.916     albertel  684: # ---------------------------------------------------- Check for valid session 
                    685: sub check_for_valid_session {
1.1172.2.96  raeburn   686:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  687:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108  raeburn   688:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155    raeburn   689:     if ($name eq 'lonDAV') {
                    690:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    691:     } else {
                    692:         $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108  raeburn   693:         if ($name eq '') {
                    694:             $name = 'lonID';
                    695:         }
                    696:     }
                    697:     if ($name eq 'lonID') {
                    698:         $secure = 'lonSID';
                    699:         $linkname = 'lonLinkID';
                    700:         $pubname = 'lonPubID';
                    701:         if (exists($cookies{$secure})) {
                    702:             $lonid=$cookies{$secure};
                    703:         } elsif (exists($cookies{$name})) {
                    704:             $lonid=$cookies{$name};
                    705:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
                    706:             $lonid=$cookies{$linkname};
                    707:         } elsif (exists($cookies{$pubname})) {
                    708:             $lonid=$cookies{$pubname};
                    709:         }
                    710:     } else {
                    711:         $lonid=$cookies{$name};
                    712:     }
                    713:     return undef if (!$lonid);
                    714: 
                    715:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    716:     if (-l "$lonidsdir/$handle.id") {
                    717:         my $link = readlink("$lonidsdir/$handle.id");
                    718:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    719:             $handle = $1;
                    720:         }
1.1155    raeburn   721:     }
1.1172.2.96  raeburn   722:     if (!-e "$lonidsdir/$handle.id") {
                    723:         if ((ref($domref)) && ($name eq 'lonID') &&
                    724:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    725:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    726:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    727:                 $$domref = $possudom;
                    728:             }
                    729:         }
                    730:         return undef;
                    731:     }
1.916     albertel  732: 
1.917     albertel  733:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    734:     return undef if (!$opened);
1.916     albertel  735: 
                    736:     flock($idf,LOCK_SH);
                    737:     my %disk_env;
                    738:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    739: 	    &GDBM_READER(),0640)) {
                    740: 	return undef;	
                    741:     }
                    742: 
                    743:     if (!defined($disk_env{'user.name'})
                    744: 	|| !defined($disk_env{'user.domain'})) {
1.1172.2.107  raeburn   745:         untie(%disk_env);
1.916     albertel  746: 	return undef;
                    747:     }
1.1172.2.18  raeburn   748: 
1.1172.2.36  raeburn   749:     if (ref($userhashref) eq 'HASH') {
                    750:         $userhashref->{'name'} = $disk_env{'user.name'};
                    751:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.142  raeburn   752:         if ($disk_env{'request.role'}) {
                    753:             $userhashref->{'role'} = $disk_env{'request.role'};
                    754:         }
1.1172.2.146.  .13(raeb  755:-23):         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
                    756:-23):         if ($userhashref->{'lti'}) {
                    757:-23):             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
                    758:-23):             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
                    759:-23):         }
1.1172.2.18  raeburn   760:     }
1.1172.2.107  raeburn   761:     untie(%disk_env);
1.1172.2.18  raeburn   762: 
1.916     albertel  763:     return $handle;
                    764: }
                    765: 
1.830     albertel  766: sub timed_flock {
                    767:     my ($file,$lock_type) = @_;
                    768:     my $failed=0;
                    769:     eval {
                    770: 	local $SIG{__DIE__}='DEFAULT';
                    771: 	local $SIG{ALRM}=sub {
                    772: 	    $failed=1;
                    773: 	    die("failed lock");
                    774: 	};
                    775: 	alarm(13);
                    776: 	flock($file,$lock_type);
                    777: 	alarm(0);
                    778:     };
                    779:     if ($failed) {
                    780: 	return undef;
                    781:     } else {
                    782: 	return 1;
                    783:     }
                    784: }
                    785: 
1.1172.2.107  raeburn   786: sub get_sessionfile_vars {
                    787:     my ($handle,$lonidsdir,$storearr) = @_;
                    788:     my %returnhash;
                    789:     unless (ref($storearr) eq 'ARRAY') {
                    790:         return %returnhash;
                    791:     }
                    792:     if (-l "$lonidsdir/$handle.id") {
                    793:         my $link = readlink("$lonidsdir/$handle.id");
                    794:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    795:             $handle = $1;
                    796:         }
                    797:     }
                    798:     if ((-e "$lonidsdir/$handle.id") &&
                    799:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    800:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    801:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    802:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    803:                 flock($idf,LOCK_SH);
                    804:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    805:                         &GDBM_READER(),0640)) {
                    806:                     foreach my $item (@{$storearr}) {
                    807:                         $returnhash{$item} = $disk_env{$item};
                    808:                     }
                    809:                     untie(%disk_env);
                    810:                 }
                    811:             }
                    812:         }
                    813:     }
                    814:     return %returnhash;
                    815: }
                    816: 
1.5       www       817: # ---------------------------------------------------------- Append Environment
                    818: 
                    819: sub appenv {
1.949     raeburn   820:     my ($newenv,$roles) = @_;
                    821:     if (ref($newenv) eq 'HASH') {
                    822:         foreach my $key (keys(%{$newenv})) {
                    823:             my $refused = 0;
                    824: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    825:                 $refused = 1;
                    826:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   827:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   828:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    829:                         $refused = 0;
                    830:                     }
                    831:                 }
                    832:             }
                    833:             if ($refused) {
                    834:                 &logthis("<font color=\"blue\">WARNING: ".
                    835:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    836:                          .'</font>');
                    837: 	        delete($newenv->{$key});
                    838:             } else {
                    839:                 $env{$key}=$newenv->{$key};
                    840:             }
                    841:         }
1.1172.2.96  raeburn   842:         my $lonids = $perlvar{'lonIDsDir'};
                    843:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    844:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    845:             if ($opened
                    846: 	        && &timed_flock($env_file,LOCK_EX)
                    847: 	        &&
                    848: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    849: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    850: 	        while (my ($key,$value) = each(%{$newenv})) {
                    851: 	            $disk_env{$key} = $value;
                    852: 	        }
                    853: 	        untie(%disk_env);
                    854:             }
1.35      www       855:         }
1.191     harris41  856:     }
1.56      www       857:     return 'ok';
                    858: }
                    859: # ----------------------------------------------------- Delete from Environment
                    860: 
                    861: sub delenv {
1.1104    raeburn   862:     my ($delthis,$regexp,$roles) = @_;
                    863:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    864:         my $refused = 1;
                    865:         if (ref($roles) eq 'ARRAY') {
                    866:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    867:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    868:                 $refused = 0;
                    869:             }
                    870:         }
                    871:         if ($refused) {
                    872:             &logthis("<font color=\"blue\">WARNING: ".
                    873:                      "Attempt to delete from environment ".$delthis);
                    874:             return 'error';
                    875:         }
1.56      www       876:     }
1.917     albertel  877:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    878:     if ($opened
1.915     albertel  879: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  880: 	&&
                    881: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    882: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  883: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   884: 	    if ($regexp) {
                    885:                 if ($key=~/^$delthis/) {
                    886:                     delete($env{$key});
                    887:                     delete($disk_env{$key});
                    888:                 } 
                    889:             } else {
                    890:                 if ($key=~/^\Q$delthis\E/) {
                    891: 		    delete($env{$key});
                    892: 		    delete($disk_env{$key});
                    893: 	        }
                    894:             }
1.448     albertel  895: 	}
1.783     albertel  896: 	untie(%disk_env);
1.5       www       897:     }
                    898:     return 'ok';
1.369     albertel  899: }
                    900: 
1.790     albertel  901: sub get_env_multiple {
                    902:     my ($name) = @_;
                    903:     my @values;
                    904:     if (defined($env{$name})) {
                    905:         # exists is it an array
                    906:         if (ref($env{$name})) {
                    907:             @values=@{ $env{$name} };
                    908:         } else {
                    909:             $values[0]=$env{$name};
                    910:         }
                    911:     }
                    912:     return(@values);
                    913: }
                    914: 
1.958     www       915: # ------------------------------------------------------------------- Locking
                    916: 
                    917: sub set_lock {
                    918:     my ($text)=@_;
                    919:     $locknum++;
                    920:     my $id=$$.'-'.$locknum;
                    921:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    922:              'session.lock.'.$id => $text});
                    923:     return $id;
                    924: }
                    925: 
                    926: sub get_locks {
                    927:     my $num=0;
                    928:     my %texts=();
                    929:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    930:        if ($lock=~/\w/) {
                    931:           $num++;
                    932:           $texts{$lock}=$env{'session.lock.'.$lock};
                    933:        }
                    934:    }
                    935:    return ($num,%texts);
                    936: }
                    937: 
                    938: sub remove_lock {
                    939:     my ($id)=@_;
                    940:     my $newlocks='';
                    941:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    942:        if (($lock=~/\w/) && ($lock ne $id)) {
                    943:           $newlocks.=','.$lock;
                    944:        }
                    945:     }
                    946:     &appenv({'session.locks' => $newlocks});
                    947:     &delenv('session.lock.'.$id);
                    948: }
                    949: 
                    950: sub remove_all_locks {
                    951:     my $activelocks=$env{'session.locks'};
                    952:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    953:        if ($lock=~/\w/) {
                    954:           &remove_lock($lock);
                    955:        }
                    956:     }
                    957: }
                    958: 
                    959: 
1.369     albertel  960: # ------------------------------------------ Find out current server userload
                    961: sub userload {
                    962:     my $numusers=0;
                    963:     {
                    964: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    965: 	my $filename;
                    966: 	my $curtime=time;
                    967: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  968: 	    next if ($filename eq '.' || $filename eq '..');
                    969: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112  raeburn   970:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  971: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  972: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  973: 	}
                    974: 	closedir(LONIDS);
                    975:     }
                    976:     my $userloadpercent=0;
                    977:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    978:     if ($maxuserload) {
1.371     albertel  979: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  980:     }
1.372     albertel  981:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  982:     return $userloadpercent;
1.283     www       983: }
                    984: 
1.1       albertel  985: # ------------------------------ Find server with least workload from spare.tab
1.11      www       986: 
1.1       albertel  987: sub spareserver {
1.1172.2.142  raeburn   988:     my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  989:     my $spare_server;
1.370     albertel  990:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  991:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    992:                                                      :  $userloadpercent;
1.1083    raeburn   993:     my ($uint_dom,$remotesessions);
                    994:     if (($udom ne '') && (&domain($udom) ne '')) {
                    995:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    996:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    997:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    998:         $remotesessions = $udomdefaults{'remotesessions'};
                    999:     }
1.1123    raeburn  1000:     my $spareshash = &this_host_spares($udom);
                   1001:     if (ref($spareshash) eq 'HASH') {
                   1002:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1003:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn  1004:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                   1005:                                              $try_server));
1.1123    raeburn  1006: 	        ($spare_server, $lowest_load) =
                   1007: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                   1008:             }
1.1083    raeburn  1009:         }
1.784     albertel 1010: 
1.1123    raeburn  1011:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                   1012: 
                   1013:         if (!$found_server) {
                   1014:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                   1015: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn  1016:                     next unless (&spare_can_host($udom,$uint_dom,
                   1017:                                                  $remotesessions,$try_server));
1.1123    raeburn  1018: 	            ($spare_server, $lowest_load) =
                   1019: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                   1020:                 }
                   1021: 	    }
                   1022:         }
1.784     albertel 1023:     }
                   1024: 
                   1025:     if (!$want_server_name) {
1.1001    raeburn  1026:         if (defined($spare_server)) {
                   1027:             my $hostname = &hostname($spare_server);
1.1083    raeburn  1028:             if (defined($hostname)) {
1.1172.2.120  raeburn  1029:                 my $protocol = 'http';
                   1030:                 if ($protocol{$spare_server} eq 'https') {
                   1031:                     $protocol = $protocol{$spare_server};
                   1032:                 }
1.1172.2.142  raeburn  1033:                 my $alias = &Apache::lonnet::use_proxy_alias($r,$spare_server);
                   1034:                 $hostname = $alias if ($alias ne '');
1.1001    raeburn  1035: 	        $spare_server = $protocol.'://'.$hostname;
                   1036:             }
                   1037:         }
1.784     albertel 1038:     }
                   1039:     return $spare_server;
                   1040: }
                   1041: 
                   1042: sub compare_server_load {
1.1172.2.41  raeburn  1043:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                   1044: 
                   1045:     if ($required) {
                   1046:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   1047:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1048:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   1049:         if (($major eq '' && $minor eq '') ||
                   1050:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   1051:             return ($spare_server,$lowest_load);
                   1052:         }
                   1053:     }
1.784     albertel 1054: 
                   1055:     my $loadans     = &reply('load',    $try_server);
                   1056:     my $userloadans = &reply('userload',$try_server);
                   1057: 
                   1058:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn  1059: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel 1060:     }
                   1061: 
                   1062:     my $load;
                   1063:     if ($loadans =~ /\d/) {
                   1064: 	if ($userloadans =~ /\d/) {
                   1065: 	    #both are numbers, pick the bigger one
                   1066: 	    $load = ($loadans > $userloadans) ? $loadans 
                   1067: 		                              : $userloadans;
1.411     albertel 1068: 	} else {
1.784     albertel 1069: 	    $load = $loadans;
1.411     albertel 1070: 	}
1.784     albertel 1071:     } else {
                   1072: 	$load = $userloadans;
                   1073:     }
                   1074: 
                   1075:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1076: 	$spare_server = $try_server;
                   1077: 	$lowest_load  = $load;
1.370     albertel 1078:     }
1.784     albertel 1079:     return ($spare_server,$lowest_load);
1.202     matthew  1080: }
1.914     albertel 1081: 
                   1082: # --------------------------- ask offload servers if user already has a session
                   1083: sub find_existing_session {
                   1084:     my ($udom,$uname) = @_;
1.1123    raeburn  1085:     my $spareshash = &this_host_spares($udom);
                   1086:     if (ref($spareshash) eq 'HASH') {
                   1087:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1088:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1089:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1090:             }
                   1091:         }
                   1092:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1093:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1094:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1095:             }
                   1096:         }
1.914     albertel 1097:     }
                   1098:     return;
                   1099: }
                   1100: 
1.1172.2.146.  .13(raeb 1101:-23): sub delusersession {
                   1102:-23):     my ($lonid,$udom,$uname) = @_;
                   1103:-23):     my $uprimary_id = &domain($udom,'primary');
                   1104:-23):     my $uintdom = &internet_dom($uprimary_id);
                   1105:-23):     my $intdom = &internet_dom($lonid);
                   1106:-23):     my $serverhomedom = &host_domain($lonid);
                   1107:-23):     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1108:-23):         return &reply(join(':','delusersession',
                   1109:-23):                             map {&escape($_)} ($udom,$uname)),$lonid);
                   1110:-23):     }
                   1111:-23):     return;
                   1112:-23): }
                   1113:-23): 
                   1114:-23): 
1.1172.2.107  raeburn  1115: # check if user's browser sent load balancer cookie and server still has session
                   1116: # and is not overloaded.
                   1117: sub check_for_balancer_cookie {
                   1118:     my ($r,$update_mtime) = @_;
                   1119:     my ($otherserver,$cookie);
                   1120:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1121:     if (exists($cookies{'balanceID'})) {
                   1122:         my $balid = $cookies{'balanceID'};
                   1123:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1124:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1125:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1126:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1127:                 my ($possudom,$possuname) = ($1,$2);
                   1128:                 my $has_session = 0;
                   1129:                 if ((&domain($possudom) ne '') &&
                   1130:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1131:                     my $try_server;
                   1132:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1133:                     if ($opened) {
                   1134:                         flock($idf,LOCK_SH);
                   1135:                         while (my $line = <$idf>) {
                   1136:                             chomp($line);
                   1137:                             if (&hostname($line) ne '') {
                   1138:                                 $try_server = $line;
                   1139:                                 last;
                   1140:                             }
                   1141:                         }
                   1142:                         close($idf);
                   1143:                         if (($try_server) &&
                   1144:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1145:                             my $lowest_load = 30000;
                   1146:                             ($otherserver,$lowest_load) =
                   1147:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1148:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1149:                                 $has_session = 1;
                   1150:                             } else {
                   1151:                                 undef($otherserver);
                   1152:                             }
                   1153:                         }
                   1154:                     }
                   1155:                 }
                   1156:                 if ($has_session) {
                   1157:                     if ($update_mtime) {
                   1158:                         my $atime = my $mtime = time;
                   1159:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1160:                     }
                   1161:                 } else {
                   1162:                     unlink("$balancedir/$cookie.id");
                   1163:                 }
                   1164:             }
                   1165:         }
                   1166:     }
                   1167:     return ($otherserver,$cookie);
                   1168: }
                   1169: 
1.1172.2.130  raeburn  1170: sub updatebalcookie {
                   1171:     my ($cookie,$balancer,$lastentry)=@_;
                   1172:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1173:         my ($udom,$uname) = ($1,$2);
                   1174:         my $uprimary_id = &domain($udom,'primary');
                   1175:         my $uintdom = &internet_dom($uprimary_id);
                   1176:         my $intdom = &internet_dom($balancer);
                   1177:         my $serverhomedom = &host_domain($balancer);
                   1178:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1179:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
                   1180:         }
                   1181:     }
                   1182:     return;
                   1183: }
                   1184: 
1.1172.2.107  raeburn  1185: sub delbalcookie {
                   1186:     my ($cookie,$balancer) =@_;
                   1187:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1188:         my ($udom,$uname) = ($1,$2);
                   1189:         my $uprimary_id = &domain($udom,'primary');
                   1190:         my $uintdom = &internet_dom($uprimary_id);
                   1191:         my $intdom = &internet_dom($balancer);
                   1192:         my $serverhomedom = &host_domain($balancer);
                   1193:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1172.2.130  raeburn  1194:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1172.2.107  raeburn  1195:         }
                   1196:     }
                   1197: }
                   1198: 
1.914     albertel 1199: # -------------------------------- ask if server already has a session for user
                   1200: sub has_user_session {
                   1201:     my ($lonid,$udom,$uname) = @_;
                   1202:     my $result = &reply(join(':','userhassession',
                   1203: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1204:     return 1 if ($result eq 'ok');
                   1205: 
                   1206:     return 0;
                   1207: }
                   1208: 
1.1076    raeburn  1209: # --------- determine least loaded server in a user's domain which allows login
                   1210: 
                   1211: sub choose_server {
1.1172.2.47  raeburn  1212:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1213:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1214:     my %servers = &get_servers($udom);
1.1076    raeburn  1215:     my $lowest_load = 30000;
1.1172.2.47  raeburn  1216:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1217:     if ($skiploadbal) {
                   1218:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1219:         unless (defined($cached)) {
                   1220:             my $cachetime = 60*60*24;
                   1221:             my %domconfig =
                   1222:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1223:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1224:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1225:                                            $cachetime);
                   1226:             }
                   1227:         }
                   1228:     }
1.1076    raeburn  1229:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn  1230:         my $loginvia;
1.1172.2.47  raeburn  1231:         if ($skiploadbal) {
                   1232:             if (ref($balancers) eq 'HASH') {
                   1233:                 next if (exists($balancers->{$lonhost}));
                   1234:             }
                   1235:         }
1.1115    raeburn  1236:         if ($checkloginvia) {
                   1237:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1238:             if ($loginvia) {
                   1239:                 my ($server,$path) = split(/:/,$loginvia);
                   1240:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1241:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1242:                 if ($login_host eq $server) {
                   1243:                     $portal_path = $path;
1.1151    raeburn  1244:                     $isredirect = 1;
1.1116    raeburn  1245:                 }
                   1246:             } else {
                   1247:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1248:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1249:                 if ($login_host eq $lonhost) {
                   1250:                     $portal_path = '';
1.1151    raeburn  1251:                     $isredirect = ''; 
1.1116    raeburn  1252:                 }
                   1253:             }
                   1254:         } else {
1.1076    raeburn  1255:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1256:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1257:         }
                   1258:     }
                   1259:     if ($login_host ne '') {
1.1116    raeburn  1260:         $hostname = &hostname($login_host);
1.1076    raeburn  1261:     }
1.1172.2.88  raeburn  1262:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1263: }
                   1264: 
1.1172.2.123  raeburn  1265: sub get_course_sessions {
                   1266:     my ($cnum,$cdom,$lastactivity) = @_;
                   1267:     my %servers = &internet_dom_servers($cdom);
                   1268:     my %returnhash;
                   1269:     foreach my $server (sort(keys(%servers))) {
                   1270:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1271:         my @pairs=split(/\&/,$rep);
                   1272:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1273:             foreach my $item (@pairs) {
                   1274:                 my ($key,$value)=split(/=/,$item,2);
                   1275:                 $key = &unescape($key);
                   1276:                 next if ($key =~ /^error: 2 /);
                   1277:                 if (exists($returnhash{$key})) {
                   1278:                     next if ($value < $returnhash{$key});
                   1279:                 }
                   1280:                 $returnhash{$key}=$value;
                   1281:             }
                   1282:         }
                   1283:     }
                   1284:     return %returnhash;
                   1285: }
                   1286: 
1.202     matthew  1287: # --------------------------------------------- Try to change a user's password
                   1288: 
                   1289: sub changepass {
1.799     raeburn  1290:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1291:     $currentpass = &escape($currentpass);
                   1292:     $newpass     = &escape($newpass);
1.1030    raeburn  1293:     my $lonhost = $perlvar{'lonHostID'};
                   1294:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1295: 		       $server);
                   1296:     if (! $answer) {
                   1297: 	&logthis("No reply on password change request to $server ".
                   1298: 		 "by $uname in domain $udom.");
                   1299:     } elsif ($answer =~ "^ok") {
                   1300:         &logthis("$uname in $udom successfully changed their password ".
                   1301: 		 "on $server.");
                   1302:     } elsif ($answer =~ "^pwchange_failure") {
                   1303: 	&logthis("$uname in $udom was unable to change their password ".
                   1304: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1305: 		 "or pwchange");
                   1306:     } elsif ($answer =~ "^non_authorized") {
                   1307:         &logthis("$uname in $udom did not get their password correct when ".
                   1308: 		 "attempting to change it on $server.");
                   1309:     } elsif ($answer =~ "^auth_mode_error") {
                   1310:         &logthis("$uname in $udom attempted to change their password despite ".
                   1311: 		 "not being locally or internally authenticated on $server.");
                   1312:     } elsif ($answer =~ "^unknown_user") {
                   1313:         &logthis("$uname in $udom attempted to change their password ".
                   1314: 		 "on $server but were unable to because $server is not ".
                   1315: 		 "their home server.");
                   1316:     } elsif ($answer =~ "^refused") {
                   1317: 	&logthis("$server refused to change $uname in $udom password because ".
                   1318: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1319:     } elsif ($answer =~ "invalid_client") {
                   1320:         &logthis("$server refused to change $uname in $udom password because ".
                   1321:                  "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113  raeburn  1322:     } elsif ($answer =~ "^prioruse") {
                   1323:        &logthis("$server refused to change $uname in $udom password because ".
                   1324:                 "the password had been used before");
1.202     matthew  1325:     }
                   1326:     return $answer;
1.1       albertel 1327: }
                   1328: 
1.169     harris41 1329: # ----------------------- Try to determine user's current authentication scheme
                   1330: 
                   1331: sub queryauthenticate {
                   1332:     my ($uname,$udom)=@_;
1.456     albertel 1333:     my $uhome=&homeserver($uname,$udom);
1.1172.2.146.  .5(raebu 1334:22):     if ((!$uhome) || ($uhome eq 'no_host')) {
1.456     albertel 1335: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1336: 	return 'no_host';
                   1337:     }
                   1338:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1339:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1340: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1341:     }
1.456     albertel 1342:     return $answer;
1.169     harris41 1343: }
                   1344: 
1.1       albertel 1345: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1346: 
1.1       albertel 1347: sub authenticate {
1.1073    raeburn  1348:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1349:     $upass=&escape($upass);
                   1350:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1351:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1352:     my $newhome;
1.836     www      1353:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1354: # Maybe the machine was offline and only re-appeared again recently?
                   1355:         &reconlonc();
                   1356: # One more
1.952     raeburn  1357: 	$uhome=&homeserver($uname,$udom,1);
                   1358:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1359:             if (defined(&domain($udom,'primary'))) {
                   1360:                 $newhome=&domain($udom,'primary');
                   1361:             }
                   1362:             if ($newhome ne '') {
                   1363:                 $uhome = $newhome;
                   1364:             }
                   1365:         }
1.836     www      1366: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1367: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1368: 	    return 'no_host';
                   1369:         }
1.1       albertel 1370:     }
1.1073    raeburn  1371:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1372:     if ($answer eq 'authorized') {
1.952     raeburn  1373:         if ($newhome) {
                   1374:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1375:             return 'no_account_on_host'; 
                   1376:         } else {
                   1377:             &logthis("User $uname at $udom authorized by $uhome");
                   1378:             return $uhome;
                   1379:         }
1.471     albertel 1380:     }
                   1381:     if ($answer eq 'non_authorized') {
                   1382: 	&logthis("User $uname at $udom rejected by $uhome");
1.1172.2.146.  .5(raebu 1383:22): 	return 'no_host';
1.9       www      1384:     }
1.471     albertel 1385:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1386:     return 'no_host';
                   1387: }
                   1388: 
1.1172.2.146.  .6(raebu 1389:22): sub can_switchserver {
                   1390:22):     my ($udom,$home) = @_;
                   1391:22):     my ($canswitch,@intdoms);
                   1392:22):     my $internet_names = &get_internet_names($home);
                   1393:22):     if (ref($internet_names) eq 'ARRAY') {
                   1394:22):         @intdoms = @{$internet_names};
                   1395:22):     }
                   1396:22):     my $uint_dom = &internet_dom(&domain($udom,'primary'));
                   1397:22):     if ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1398:22):         $canswitch = 1;
                   1399:22):     } else {
                   1400:22):          my $serverhomeID = &get_server_homeID(&hostname($home));
                   1401:22):          my $serverhomedom = &host_domain($serverhomeID);
                   1402:22):          my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1403:22):          my %udomdefaults = &get_domain_defaults($udom);
                   1404:22):          my $remoterev = &get_server_loncaparev('',$home);
                   1405:22):          $canswitch = &can_host_session($udom,$home,$remoterev,
                   1406:22):                                         $udomdefaults{'remotesessions'},
                   1407:22):                                         $defdomdefaults{'hostedsessions'});
                   1408:22):     }
                   1409:22):     return $canswitch;
                   1410:22): }
                   1411:22): 
1.1073    raeburn  1412: sub can_host_session {
1.1074    raeburn  1413:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1414:     my $canhost = 1;
1.1074    raeburn  1415:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1416:     if (ref($remotesessions) eq 'HASH') {
                   1417:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1418:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1419:                 $canhost = 0;
                   1420:             } else {
                   1421:                 $canhost = 1;
                   1422:             }
                   1423:         }
                   1424:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1425:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1426:                 $canhost = 1;
                   1427:             } else {
                   1428:                 $canhost = 0;
                   1429:             }
                   1430:         }
                   1431:         if ($canhost) {
                   1432:             if ($remotesessions->{'version'} ne '') {
                   1433:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1434:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1435:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1436:                         my $major = $1;
                   1437:                         my $minor = $2;
                   1438:                         if (($major < $reqmajor ) ||
                   1439:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1440:                             $canhost = 0;
                   1441:                         }
                   1442:                     } else {
                   1443:                         $canhost = 0;
                   1444:                     }
                   1445:                 }
                   1446:             }
                   1447:         }
                   1448:     }
                   1449:     if ($canhost) {
                   1450:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1451:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1452:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1453:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1454:                 if (($uint_dom ne '') && 
                   1455:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1456:                     $canhost = 0;
                   1457:                 } else {
                   1458:                     $canhost = 1;
                   1459:                 }
                   1460:             }
                   1461:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1462:                 if (($uint_dom ne '') && 
                   1463:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1464:                     $canhost = 1;
                   1465:                 } else {
                   1466:                     $canhost = 0;
                   1467:                 }
                   1468:             }
                   1469:         }
                   1470:     }
                   1471:     return $canhost;
                   1472: }
                   1473: 
1.1083    raeburn  1474: sub spare_can_host {
                   1475:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1476:     my $canhost=1;
1.1172.2.62  raeburn  1477:     my $try_server_hostname = &hostname($try_server);
                   1478:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1479:     my $serverhomedom = &host_domain($serverhomeID);
                   1480:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1481:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1482:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1483:             $canhost = 0;
                   1484:         }
                   1485:     }
1.1172.2.136  raeburn  1486:     if ($canhost) {
                   1487:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
                   1488:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
                   1489:                 unless (&shared_institution($udom,$try_server)) {
                   1490:                     $canhost = 0;
                   1491:                 }
                   1492:             }
                   1493:         }
                   1494:     }
1.1172.2.62  raeburn  1495:     if (($canhost) && ($uint_dom)) {
                   1496:         my @intdoms;
                   1497:         my $internet_names = &get_internet_names($try_server);
                   1498:         if (ref($internet_names) eq 'ARRAY') {
                   1499:             @intdoms = @{$internet_names};
                   1500:         }
                   1501:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1502:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1503:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1504:                                          $remotesessions,
                   1505:                                          $defdomdefaults{'hostedsessions'});
                   1506:         }
1.1083    raeburn  1507:     }
                   1508:     return $canhost;
                   1509: }
                   1510: 
1.1123    raeburn  1511: sub this_host_spares {
                   1512:     my ($dom) = @_;
1.1126    raeburn  1513:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1514:     my @hosts = &current_machine_ids();
                   1515:     foreach my $lonhost (@hosts) {
                   1516:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1517:             $dom_in_use = $dom;
                   1518:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1519:             last;
                   1520:         }
                   1521:     }
1.1126    raeburn  1522:     if ($dom_in_use ne '') {
                   1523:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1524:     }
                   1525:     if (ref($result) ne 'HASH') {
                   1526:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1527:         $dom_in_use = &host_domain($lonhost_in_use);
                   1528:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1529:         if (ref($result) ne 'HASH') {
                   1530:             $result = \%spareid;
                   1531:         }
                   1532:     }
                   1533:     return $result;
                   1534: }
                   1535: 
                   1536: sub spares_for_offload  {
                   1537:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1538:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1539:     if (defined($cached)) {
                   1540:         return $result;
                   1541:     } else {
1.1126    raeburn  1542:         my $cachetime = 60*60*24;
                   1543:         my %domconfig =
                   1544:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1545:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1546:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1547:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1548:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1549:                 }
                   1550:             }
                   1551:         }
                   1552:     }
1.1126    raeburn  1553:     return;
1.1123    raeburn  1554: }
                   1555: 
1.1129    raeburn  1556: sub get_lonbalancer_config {
                   1557:     my ($servers) = @_;
                   1558:     my ($currbalancer,$currtargets);
                   1559:     if (ref($servers) eq 'HASH') {
                   1560:         foreach my $server (keys(%{$servers})) {
                   1561:             my %what = (
                   1562:                          spareid => 1,
                   1563:                          perlvar => 1,
                   1564:                        );
                   1565:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1566:             if ($result eq 'ok') {
                   1567:                 if (ref($returnhash) eq 'HASH') {
                   1568:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1569:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1570:                             $currbalancer = $server;
                   1571:                             $currtargets = {};
                   1572:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1573:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1574:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1575:                                 }
                   1576:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1577:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1578:                                 }
                   1579:                             }
                   1580:                             last;
                   1581:                         }
                   1582:                     }
                   1583:                 }
                   1584:             }
                   1585:         }
                   1586:     }
                   1587:     return ($currbalancer,$currtargets);
                   1588: }
                   1589: 
                   1590: sub check_loadbalancing {
1.1172.2.88  raeburn  1591:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1592:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1593:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1594:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1595:     my @hosts = &current_machine_ids();
1.1129    raeburn  1596:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1597:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1598:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1599:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1600:     my $domneedscache; 
1.1129    raeburn  1601:     my $cachetime = 60*60*24;
                   1602: 
                   1603:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1604:         $dom_in_use = $udom;
                   1605:         $homeintdom = 1;
                   1606:     } else {
                   1607:         $dom_in_use = $serverhomedom;
                   1608:     }
                   1609:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1610:     unless (defined($cached)) {
                   1611:         my %domconfig =
                   1612:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1613:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1614:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1615:         } else {
                   1616:             $domneedscache = $dom_in_use;
1.1129    raeburn  1617:         }
                   1618:     }
                   1619:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1620:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1621:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1622:         if ($is_balancer) {
                   1623:             if (ref($currrules) eq 'HASH') {
                   1624:                 if ($homeintdom) {
                   1625:                     if ($uname ne '') {
                   1626:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1627:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1628:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1629:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1630:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1631:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1632:                             }
                   1633:                         }
                   1634:                         if ($rule_in_effect eq '') {
                   1635:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1636:                             if ($userenv{'inststatus'} ne '') {
                   1637:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1638:                                 my ($othertitle,$usertypes,$types) =
                   1639:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1640:                                 if (ref($types) eq 'ARRAY') {
                   1641:                                     foreach my $type (@{$types}) {
                   1642:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1643:                                             if (exists($currrules->{$type})) {
                   1644:                                                 $rule_in_effect = $currrules->{$type};
                   1645:                                             }
                   1646:                                         }
                   1647:                                     }
                   1648:                                 }
                   1649:                             } else {
                   1650:                                 if (exists($currrules->{'default'})) {
                   1651:                                     $rule_in_effect = $currrules->{'default'};
                   1652:                                 }
                   1653:                             }
                   1654:                         }
                   1655:                     } else {
                   1656:                         if (exists($currrules->{'default'})) {
                   1657:                             $rule_in_effect = $currrules->{'default'};
                   1658:                         }
                   1659:                     }
                   1660:                 } else {
                   1661:                     if ($currrules->{'_LC_external'} ne '') {
                   1662:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1663:                     }
                   1664:                 }
                   1665:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1666:                                                        $uname,$udom);
                   1667:             }
                   1668:         }
                   1669:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1670:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1671:         unless (defined($cached)) {
                   1672:             my %domconfig =
                   1673:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1674:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1675:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1676:             } else {
                   1677:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1678:             }
                   1679:         }
                   1680:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1681:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1682:                 &check_balancer_result($result,@hosts);
                   1683:             if ($is_balancer) {
1.1129    raeburn  1684:                 if (ref($currrules) eq 'HASH') {
                   1685:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1686:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1687:                     }
                   1688:                 }
                   1689:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1690:                                                        $uname,$udom);
                   1691:             }
                   1692:         } else {
                   1693:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1694:                 $is_balancer = 1;
                   1695:                 $offloadto = &this_host_spares($dom_in_use);
                   1696:             }
1.1172.2.75  raeburn  1697:             unless (defined($cached)) {
                   1698:                 $domneedscache = $serverhomedom;
                   1699:             }
1.1129    raeburn  1700:         }
                   1701:     } else {
                   1702:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1703:             $is_balancer = 1;
                   1704:             $offloadto = &this_host_spares($dom_in_use);
                   1705:         }
1.1172.2.75  raeburn  1706:         unless (defined($cached)) {
                   1707:             $domneedscache = $serverhomedom;
                   1708:         }
                   1709:     }
                   1710:     if ($domneedscache) {
                   1711:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1712:     }
1.1172.2.130  raeburn  1713:     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1172.2.5  raeburn  1714:         my $lowest_load = 30000;
                   1715:         if (ref($offloadto) eq 'HASH') {
                   1716:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1717:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1718:                     ($otherserver,$lowest_load) =
                   1719:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1720:                 }
1.1129    raeburn  1721:             }
1.1172.2.5  raeburn  1722:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1723: 
1.1172.2.5  raeburn  1724:             if (!$found_server) {
                   1725:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1726:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1727:                         ($otherserver,$lowest_load) =
                   1728:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1729:                     }
                   1730:                 }
                   1731:             }
                   1732:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1733:             if (@{$offloadto} == 1) {
                   1734:                 $otherserver = $offloadto->[0];
                   1735:             } elsif (@{$offloadto} > 1) {
                   1736:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1737:                     ($otherserver,$lowest_load) =
                   1738:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1739:                 }
                   1740:             }
                   1741:         }
1.1172.2.88  raeburn  1742:         unless ($caller eq 'login') {
                   1743:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1744:                 $is_balancer = 0;
                   1745:                 if ($uname ne '' && $udom ne '') {
                   1746:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1747:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1748:                                  'user.loadbalcheck.time' => time});
                   1749:                     }
1.1172.2.5  raeburn  1750:                 }
1.1129    raeburn  1751:             }
                   1752:         }
1.1172.2.130  raeburn  1753:     }
                   1754:     if (($is_balancer) && (!$homeintdom)) {
                   1755:         undef($setcookie);
1.1129    raeburn  1756:     }
1.1172.2.107  raeburn  1757:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1758: }
                   1759: 
1.1172.2.12  raeburn  1760: sub check_balancer_result {
                   1761:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1762:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1763:     if (ref($result) eq 'HASH') {
                   1764:         if ($result->{'lonhost'} ne '') {
                   1765:             my $currbalancer = $result->{'lonhost'};
                   1766:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1767:                 $is_balancer = 1;
                   1768:                 $currtargets = $result->{'targets'};
                   1769:                 $currrules = $result->{'rules'};
                   1770:             }
                   1771:         } else {
                   1772:             foreach my $key (keys(%{$result})) {
                   1773:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1774:                     (ref($result->{$key}) eq 'HASH')) {
                   1775:                     $is_balancer = 1;
                   1776:                     $currrules = $result->{$key}{'rules'};
                   1777:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1778:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1779:                     last;
                   1780:                 }
                   1781:             }
                   1782:         }
                   1783:     }
1.1172.2.107  raeburn  1784:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1785: }
                   1786: 
1.1129    raeburn  1787: sub get_loadbalancer_targets {
                   1788:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1789:     my $offloadto;
1.1172.2.4  raeburn  1790:     if ($rule_in_effect eq 'none') {
                   1791:         return [$perlvar{'lonHostID'}];
                   1792:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1793:         $offloadto = $currtargets;
                   1794:     } else {
                   1795:         if ($rule_in_effect eq 'homeserver') {
                   1796:             my $homeserver = &homeserver($uname,$udom);
                   1797:             if ($homeserver ne 'no_host') {
                   1798:                 $offloadto = [$homeserver];
                   1799:             }
                   1800:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1801:             my %domconfig =
                   1802:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1803:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1804:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1805:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1806:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1807:                     }
                   1808:                 }
                   1809:             } else {
1.1172.2.7  raeburn  1810:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1811:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1812:                 if (&hostname($remotebalancer) ne '') {
                   1813:                     $offloadto = [$remotebalancer];
                   1814:                 }
                   1815:             }
                   1816:         } elsif (&hostname($rule_in_effect) ne '') {
                   1817:             $offloadto = [$rule_in_effect];
                   1818:         }
                   1819:     }
                   1820:     return $offloadto;
                   1821: }
                   1822: 
1.1127    raeburn  1823: sub internet_dom_servers {
                   1824:     my ($dom) = @_;
                   1825:     my (%uniqservers,%servers);
                   1826:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1827:     my @machinedoms = &machine_domains($primaryserver);
                   1828:     foreach my $mdom (@machinedoms) {
                   1829:         my %currservers = %servers;
                   1830:         my %server = &get_servers($mdom);
                   1831:         %servers = (%currservers,%server);
                   1832:     }
                   1833:     my %by_hostname;
                   1834:     foreach my $id (keys(%servers)) {
                   1835:         push(@{$by_hostname{$servers{$id}}},$id);
                   1836:     }
                   1837:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1838:         if (@{$by_hostname{$hostname}} > 1) {
                   1839:             my $match = 0;
                   1840:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1841:                 if (&host_domain($id) eq $dom) {
                   1842:                     $uniqservers{$id} = $hostname;
                   1843:                     $match = 1;
                   1844:                 }
                   1845:             }
                   1846:             unless ($match) {
                   1847:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1848:             }
                   1849:         } else {
                   1850:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1851:         }
                   1852:     }
                   1853:     return %uniqservers;
                   1854: }
                   1855: 
1.1       albertel 1856: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1857: 
1.599     albertel 1858: my %homecache;
1.1       albertel 1859: sub homeserver {
1.230     stredwic 1860:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1861:     my $index="$uname:$udom";
1.426     albertel 1862: 
1.599     albertel 1863:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1864: 
                   1865:     my %servers = &get_servers($udom,'library');
                   1866:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1867:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1868: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1869: 
                   1870: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1871: 	if ($answer eq 'found') {
                   1872: 	    delete($badServerCache{$tryserver}); 
                   1873: 	    return $homecache{$index}=$tryserver;
                   1874: 	} elsif ($answer eq 'no_host') {
                   1875: 	    $badServerCache{$tryserver}=1;
                   1876: 	}
1.1       albertel 1877:     }    
                   1878:     return 'no_host';
1.70      www      1879: }
                   1880: 
                   1881: # ------------------------------------- Find the usernames behind a list of IDs
                   1882: 
                   1883: sub idget {
                   1884:     my ($udom,@ids)=@_;
                   1885:     my %returnhash=();
                   1886:     
1.841     albertel 1887:     my %servers = &get_servers($udom,'library');
                   1888:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1889: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1890: 	$idlist=~tr/A-Z/a-z/; 
                   1891: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1892: 	my @answer=();
                   1893: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1894: 	    @answer=split(/\&/,$reply);
                   1895: 	}                    ;
                   1896: 	my $i;
                   1897: 	for ($i=0;$i<=$#ids;$i++) {
                   1898: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1899: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1900: 	    } 
                   1901: 	}
                   1902:     } 
1.70      www      1903:     return %returnhash;
                   1904: }
                   1905: 
                   1906: # ------------------------------------- Find the IDs behind a list of usernames
                   1907: 
                   1908: sub idrget {
                   1909:     my ($udom,@unames)=@_;
                   1910:     my %returnhash=();
1.800     albertel 1911:     foreach my $uname (@unames) {
                   1912:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1913:     }
1.70      www      1914:     return %returnhash;
                   1915: }
                   1916: 
                   1917: # ------------------------------- Store away a list of names and associated IDs
                   1918: 
                   1919: sub idput {
                   1920:     my ($udom,%ids)=@_;
                   1921:     my %servers=();
1.800     albertel 1922:     foreach my $uname (keys(%ids)) {
                   1923: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1924:         my $uhom=&homeserver($uname,$udom);
1.70      www      1925:         if ($uhom ne 'no_host') {
1.800     albertel 1926:             my $id=&escape($ids{$uname});
1.70      www      1927:             $id=~tr/A-Z/a-z/;
1.800     albertel 1928:             my $esc_unam=&escape($uname);
1.70      www      1929: 	    if ($servers{$uhom}) {
1.800     albertel 1930: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1931:             } else {
1.800     albertel 1932:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1933:             }
                   1934:         }
1.191     harris41 1935:     }
1.800     albertel 1936:     foreach my $server (keys(%servers)) {
                   1937:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1938:     }
1.344     www      1939: }
                   1940: 
1.1172.2.30  raeburn  1941: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1942: 
                   1943: sub iddel {
                   1944:     my ($udom,$idshashref,$uhome)=@_;
                   1945:     my %result=();
                   1946:     unless (ref($idshashref) eq 'HASH') {
                   1947:         return %result;
                   1948:     }
                   1949:     my %servers=();
                   1950:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1951:         my $uhom;
                   1952:         if ($uhome) {
                   1953:             $uhom = $uhome;
                   1954:         } else {
                   1955:             $uhom=&homeserver($uname,$udom);
                   1956:         }
                   1957:         if ($uhom ne 'no_host') {
                   1958:             if ($servers{$uhom}) {
                   1959:                 $servers{$uhom}.='&'.&escape($id);
                   1960:             } else {
                   1961:                 $servers{$uhom}=&escape($id);
                   1962:             }
                   1963:         }
                   1964:     }
                   1965:     foreach my $server (keys(%servers)) {
                   1966:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1967:     }
                   1968:     return %result;
                   1969: }
                   1970: 
1.1023    raeburn  1971: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1972: sub dump_dom {
1.1165    droeschl 1973:     my ($namespace, $udom, $regexp) = @_;
                   1974: 
                   1975:     $udom ||= $env{'user.domain'};
                   1976: 
                   1977:     return () unless $udom;
                   1978: 
                   1979:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1980: }
                   1981: 
1.1023    raeburn  1982: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1983: 
                   1984: sub get_dom {
1.1172.2.146.  .1(raebu 1985:22):     my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
1.1172.2.57  raeburn  1986:     return if ($udom eq 'public');
1.806     raeburn  1987:     my $items='';
                   1988:     foreach my $item (@$storearr) {
                   1989:         $items.=&escape($item).'&';
                   1990:     }
                   1991:     $items=~s/\&$//;
1.860     raeburn  1992:     if (!$udom) {
                   1993:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1994:         return if ($udom eq 'public');
1.860     raeburn  1995:         if (defined(&domain($udom,'primary'))) {
                   1996:             $uhome=&domain($udom,'primary');
                   1997:         } else {
1.874     albertel 1998:             undef($uhome);
1.860     raeburn  1999:         }
                   2000:     } else {
                   2001:         if (!$uhome) {
                   2002:             if (defined(&domain($udom,'primary'))) {
                   2003:                 $uhome=&domain($udom,'primary');
                   2004:             }
                   2005:         }
                   2006:     }
                   2007:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.139  raeburn  2008:         my $rep;
                   2009:         if (grep { $_ eq $uhome } &current_machine_ids()) {
                   2010:             # domain information is hosted on this machine
                   2011:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1.1172.2.146.  .1(raebu 2012:22):         } else {
                   2013:22):             if ($encrypt) {
                   2014:22):                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2015:22):             } else {
                   2016:22):                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2017:22):             }
1.1172.2.139  raeburn  2018:         }
1.866     raeburn  2019:         my %returnhash;
1.875     albertel 2020:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2021:             return %returnhash;
                   2022:         }
1.806     raeburn  2023:         my @pairs=split(/\&/,$rep);
                   2024:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2025:             return @pairs;
                   2026:         }
                   2027:         my $i=0;
                   2028:         foreach my $item (@$storearr) {
                   2029:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2030:             $i++;
                   2031:         }
                   2032:         return %returnhash;
                   2033:     } else {
1.880     banghart 2034:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2035:     }
                   2036: }
                   2037: 
                   2038: # -------------------------------------------- put items in domain db files 
                   2039: 
                   2040: sub put_dom {
1.1172.2.146.  .1(raebu 2041:22):     my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
1.860     raeburn  2042:     if (!$udom) {
                   2043:         $udom=$env{'user.domain'};
                   2044:         if (defined(&domain($udom,'primary'))) {
                   2045:             $uhome=&domain($udom,'primary');
                   2046:         } else {
1.874     albertel 2047:             undef($uhome);
1.860     raeburn  2048:         }
                   2049:     } else {
                   2050:         if (!$uhome) {
                   2051:             if (defined(&domain($udom,'primary'))) {
                   2052:                 $uhome=&domain($udom,'primary');
                   2053:             }
                   2054:         }
                   2055:     } 
                   2056:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2057:         my $items='';
                   2058:         foreach my $item (keys(%$storehash)) {
                   2059:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2060:         }
                   2061:         $items=~s/\&$//;
1.1172.2.146.  .1(raebu 2062:22):         if ($encrypt) {
                   2063:22):             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2064:22):         } else {
                   2065:22):             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2066:22):         }
1.806     raeburn  2067:     } else {
1.860     raeburn  2068:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2069:     }
                   2070: }
                   2071: 
1.1023    raeburn  2072: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2073: sub newput_dom {
1.1023    raeburn  2074:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2075:     my $result;
                   2076:     if (!$udom) {
                   2077:         $udom=$env{'user.domain'};
                   2078:     }
1.1023    raeburn  2079:     if ($udom) {
                   2080:         my $uname = &get_domainconfiguser($udom);
                   2081:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2082:     }
                   2083:     return $result;
                   2084: }
                   2085: 
1.1023    raeburn  2086: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2087: sub del_dom {
1.1023    raeburn  2088:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2089:     if (ref($storearr) eq 'ARRAY') {
                   2090:         if (!$udom) {
                   2091:             $udom=$env{'user.domain'};
                   2092:         }
1.1023    raeburn  2093:         if ($udom) {
                   2094:             my $uname = &get_domainconfiguser($udom); 
                   2095:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2096:         }
                   2097:     }
                   2098: }
                   2099: 
1.1172.2.146.  .4(raebu 2100:22): sub store_dom {
                   2101:22):     my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
                   2102:22):     $$storehash{'ip'}=&get_requestor_ip();
                   2103:22):     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2104:22):     my $namevalue='';
                   2105:22):     foreach my $key (keys(%{$storehash})) {
                   2106:22):         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   2107:22):     }
                   2108:22):     $namevalue=~s/\&$//;
                   2109:22):     if (grep { $_ eq $home } current_machine_ids()) {
                   2110:22):         return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
                   2111:22):     } else {
                   2112:22):         if ($namespace eq 'private') {
                   2113:22):             return 'refused';
                   2114:22):         } elsif ($encrypt) {
                   2115:22):             return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
                   2116:22):         } else {
                   2117:22):             return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
                   2118:22):         }
                   2119:22):     }
                   2120:22): }
                   2121:22): 
                   2122:22): sub restore_dom {
                   2123:22):     my ($id,$namespace,$dom,$home,$encrypt) = @_;
                   2124:22):     my $answer;
                   2125:22):     if (grep { $_ eq $home } current_machine_ids()) {
                   2126:22):         $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
                   2127:22):     } elsif ($namespace ne 'private') {
                   2128:22):         if ($encrypt) {
                   2129:22):             $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
                   2130:22):         } else {
                   2131:22):             $answer=&reply("restoredom:$dom:$namespace:$id",$home);
                   2132:22):         }
                   2133:22):     }
                   2134:22):     my %returnhash=();
                   2135:22):     unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') ||
                   2136:22):             ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
                   2137:22):         foreach my $line (split(/\&/,$answer)) {
                   2138:22):             my ($name,$value)=split(/\=/,$line);
                   2139:22):             $returnhash{&unescape($name)}=&thaw_unescape($value);
                   2140:22):         }
                   2141:22):         my $version;
                   2142:22):         for ($version=1;$version<=$returnhash{'version'};$version++) {
                   2143:22):             foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2144:22):                 $returnhash{$item}=$returnhash{$version.':'.$item};
                   2145:22):             }
                   2146:22):         }
                   2147:22):     }
                   2148:22):     return %returnhash;
                   2149:22): }
                   2150:22): 
1.1023    raeburn  2151: # ----------------------------------construct domainconfig user for a domain 
                   2152: sub get_domainconfiguser {
                   2153:     my ($udom) = @_;
                   2154:     return $udom.'-domainconfig';
                   2155: }
                   2156: 
1.837     raeburn  2157: sub retrieve_inst_usertypes {
                   2158:     my ($udom) = @_;
                   2159:     my (%returnhash,@order);
1.989     raeburn  2160:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2161:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2162:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  2163:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2164:     } else {
                   2165:         if (defined(&domain($udom,'primary'))) {
                   2166:             my $uhome=&domain($udom,'primary');
                   2167:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2168:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  2169:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2170:                 return (\%returnhash,\@order);
                   2171:             }
                   2172:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2173:             my @pairs=split(/\&/,$hashitems);
                   2174:             foreach my $item (@pairs) {
                   2175:                 my ($key,$value)=split(/=/,$item,2);
                   2176:                 $key = &unescape($key);
                   2177:                 next if ($key =~ /^error: 2 /);
                   2178:                 $returnhash{$key}=&thaw_unescape($value);
                   2179:             }
                   2180:             my @esc_order = split(/\&/,$orderitems);
                   2181:             foreach my $item (@esc_order) {
                   2182:                 push(@order,&unescape($item));
                   2183:             }
                   2184:         } else {
1.1172.2.44  raeburn  2185:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2186:         }
1.1172.2.44  raeburn  2187:         return (\%returnhash,\@order);
1.837     raeburn  2188:     }
                   2189: }
                   2190: 
1.868     raeburn  2191: sub is_domainimage {
                   2192:     my ($url) = @_;
1.1172.2.142  raeburn  2193:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868     raeburn  2194:         if (&domain($1) ne '') {
                   2195:             return '1';
                   2196:         }
                   2197:     }
                   2198:     return;
                   2199: }
                   2200: 
1.899     raeburn  2201: sub inst_directory_query {
                   2202:     my ($srch) = @_;
                   2203:     my $udom = $srch->{'srchdomain'};
                   2204:     my %results;
                   2205:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2206:     my $outcome;
1.899     raeburn  2207:     if ($homeserver ne '') {
1.1172.2.116  raeburn  2208:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2209:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2210:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  2211:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   2212:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2213:                     (($major == 2) && ($minor < 11)) ||
                   2214:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   2215:                     return;
                   2216:                 }
                   2217:             }
                   2218:         }
1.904     albertel 2219: 	my $queryid=&reply("querysend:instdirsearch:".
                   2220: 			   &escape($srch->{'srchby'}).':'.
                   2221: 			   &escape($srch->{'srchterm'}).':'.
                   2222: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2223: 	my $host=&hostname($homeserver);
                   2224: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2225: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2226: 	    return;
                   2227: 	}
                   2228: 	my $response = &get_query_reply($queryid);
                   2229: 	my $maxtries = 5;
                   2230: 	my $tries = 1;
                   2231: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2232: 	    $response = &get_query_reply($queryid);
                   2233: 	    $tries ++;
                   2234: 	}
                   2235: 
                   2236:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2237:             if ($response eq 'unavailable') {
                   2238:                 $outcome = $response;
                   2239:             } else {
                   2240:                 $outcome = 'ok';
                   2241:                 my @matches = split(/\n/,$response);
                   2242:                 foreach my $match (@matches) {
                   2243:                     my ($key,$value) = split(/=/,$match);
                   2244:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2245:                 }
1.899     raeburn  2246:             }
                   2247:         }
                   2248:     }
1.909     raeburn  2249:     return ($outcome,%results);
1.899     raeburn  2250: }
                   2251: 
                   2252: sub usersearch {
                   2253:     my ($srch) = @_;
                   2254:     my $dom = $srch->{'srchdomain'};
                   2255:     my %results;
                   2256:     my %libserv = &all_library();
                   2257:     my $query = 'usersearch';
                   2258:     foreach my $tryserver (keys(%libserv)) {
                   2259:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2260:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2261:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2262:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.119  raeburn  2263:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2264:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2265:                              (($major == 2) && ($minor < 11)) ||
                   2266:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2267:                 }
                   2268:             }
1.899     raeburn  2269:             my $host=&hostname($tryserver);
                   2270:             my $queryid=
1.911     raeburn  2271:                 &reply("querysend:".&escape($query).':'.
                   2272:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2273:                        &escape($srch->{'srchtype'}).':'.
                   2274:                        &escape($srch->{'srchterm'}),$tryserver);
                   2275:             if ($queryid !~/^\Q$host\E\_/) {
                   2276:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2277:                 next;
1.899     raeburn  2278:             }
                   2279:             my $reply = &get_query_reply($queryid);
                   2280:             my $maxtries = 1;
                   2281:             my $tries = 1;
                   2282:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2283:                 $reply = &get_query_reply($queryid);
                   2284:                 $tries ++;
                   2285:             }
                   2286:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2287:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2288:             } else {
1.911     raeburn  2289:                 my @matches;
                   2290:                 if ($reply =~ /\n/) {
                   2291:                     @matches = split(/\n/,$reply);
                   2292:                 } else {
                   2293:                     @matches = split(/\&/,$reply);
                   2294:                 }
1.899     raeburn  2295:                 foreach my $match (@matches) {
                   2296:                     my ($uname,$udom,%userhash);
1.911     raeburn  2297:                     foreach my $entry (split(/:/,$match)) {
                   2298:                         my ($key,$value) =
                   2299:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2300:                         $userhash{$key} = $value;
                   2301:                         if ($key eq 'username') {
                   2302:                             $uname = $value;
                   2303:                         } elsif ($key eq 'domain') {
                   2304:                             $udom = $value;
1.911     raeburn  2305:                         }
1.899     raeburn  2306:                     }
                   2307:                     $results{$uname.':'.$udom} = \%userhash;
                   2308:                 }
                   2309:             }
                   2310:         }
                   2311:     }
                   2312:     return %results;
                   2313: }
                   2314: 
1.912     raeburn  2315: sub get_instuser {
                   2316:     my ($udom,$uname,$id) = @_;
                   2317:     my $homeserver = &domain($udom,'primary');
                   2318:     my ($outcome,%results);
                   2319:     if ($homeserver ne '') {
                   2320:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2321:                            &escape($id).':'.&escape($udom),$homeserver);
                   2322:         my $host=&hostname($homeserver);
                   2323:         if ($queryid !~/^\Q$host\E\_/) {
                   2324:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2325:             return;
                   2326:         }
                   2327:         my $response = &get_query_reply($queryid);
                   2328:         my $maxtries = 5;
                   2329:         my $tries = 1;
                   2330:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2331:             $response = &get_query_reply($queryid);
                   2332:             $tries ++;
                   2333:         }
                   2334:         if (!&error($response) && $response ne 'refused') {
                   2335:             if ($response eq 'unavailable') {
                   2336:                 $outcome = $response;
                   2337:             } else {
                   2338:                 $outcome = 'ok';
                   2339:                 my @matches = split(/\n/,$response);
                   2340:                 foreach my $match (@matches) {
                   2341:                     my ($key,$value) = split(/=/,$match);
                   2342:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2343:                 }
                   2344:             }
                   2345:         }
                   2346:     }
                   2347:     my %userinfo;
                   2348:     if (ref($results{$uname}) eq 'HASH') {
                   2349:         %userinfo = %{$results{$uname}};
                   2350:     } 
                   2351:     return ($outcome,%userinfo);
                   2352: }
                   2353: 
1.1172.2.69  raeburn  2354: sub get_multiple_instusers {
                   2355:     my ($udom,$users,$caller) = @_;
                   2356:     my ($outcome,$results);
                   2357:     if (ref($users) eq 'HASH') {
                   2358:         my $count = keys(%{$users});
                   2359:         my $requested = &freeze_escape($users);
                   2360:         my $homeserver = &domain($udom,'primary');
                   2361:         if ($homeserver ne '') {
                   2362:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2363:             my $host=&hostname($homeserver);
                   2364:             if ($queryid !~/^\Q$host\E\_/) {
                   2365:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2366:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2367:                 return ($outcome,$results);
                   2368:             }
                   2369:             my $response = &get_query_reply($queryid);
                   2370:             my $maxtries = 5;
                   2371:             if ($count > 100) {
                   2372:                 $maxtries = 1+int($count/20);
                   2373:             }
                   2374:             my $tries = 1;
                   2375:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2376:                 $response = &get_query_reply($queryid);
                   2377:                 $tries ++;
                   2378:             }
                   2379:             if ($response eq '') {
                   2380:                 $results = {};
                   2381:                 foreach my $key (keys(%{$users})) {
                   2382:                     my ($uname,$id);
                   2383:                     if ($caller eq 'id') {
                   2384:                         $id = $key;
                   2385:                     } else {
                   2386:                         $uname = $key;
                   2387:                     }
                   2388:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2389:                     $outcome = $resp;
                   2390:                     if ($resp eq 'ok') {
                   2391:                         %{$results} = (%{$results}, %info);
                   2392:                     } else {
                   2393:                         last;
                   2394:                     }
                   2395:                 }
                   2396:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2397:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2398:                     $outcome = $response;
                   2399:                 } else {
                   2400:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2401:                     if ($outcome eq 'ok') {
                   2402:                         $results = &thaw_unescape($userdata);
                   2403:                     }
                   2404:                 }
                   2405:             }
                   2406:         }
                   2407:     }
                   2408:     return ($outcome,$results);
                   2409: }
                   2410: 
1.912     raeburn  2411: sub inst_rulecheck {
1.923     raeburn  2412:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2413:     my %returnhash;
                   2414:     if ($udom ne '') {
                   2415:         if (ref($rules) eq 'ARRAY') {
                   2416:             @{$rules} = map {&escape($_);} (@{$rules});
                   2417:             my $rulestr = join(':',@{$rules});
                   2418:             my $homeserver=&domain($udom,'primary');
                   2419:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2420:                 my $response;
                   2421:                 if ($item eq 'username') {                
                   2422:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2423:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2424:                                               $homeserver));
1.923     raeburn  2425:                 } elsif ($item eq 'id') {
                   2426:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2427:                                               ':'.&escape($id).':'.$rulestr,
                   2428:                                               $homeserver));
1.1172.2.146.  .5(raebu 2429:22):                 } elsif ($item eq 'unamemap') {
                   2430:22):                     $response=&unescape(&reply('instunamemapcheck:'.
                   2431:22):                                                &escape($udom).':'.&escape($uname).
                   2432:22):                                               ':'.$rulestr,$homeserver));
1.945     raeburn  2433:                 } elsif ($item eq 'selfcreate') {
                   2434:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2435:                                                &escape($udom).':'.&escape($uname).
                   2436:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2437:                 }
1.912     raeburn  2438:                 if ($response ne 'refused') {
                   2439:                     my @pairs=split(/\&/,$response);
                   2440:                     foreach my $item (@pairs) {
                   2441:                         my ($key,$value)=split(/=/,$item,2);
                   2442:                         $key = &unescape($key);
                   2443:                         next if ($key =~ /^error: 2 /);
                   2444:                         $returnhash{$key}=&thaw_unescape($value);
                   2445:                     }
                   2446:                 }
                   2447:             }
                   2448:         }
                   2449:     }
                   2450:     return %returnhash;
                   2451: }
                   2452: 
                   2453: sub inst_userrules {
1.923     raeburn  2454:     my ($udom,$check) = @_;
1.912     raeburn  2455:     my (%ruleshash,@ruleorder);
                   2456:     if ($udom ne '') {
                   2457:         my $homeserver=&domain($udom,'primary');
                   2458:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2459:             my $response;
                   2460:             if ($check eq 'id') {
                   2461:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2462:                                  $homeserver);
1.943     raeburn  2463:             } elsif ($check eq 'email') {
                   2464:                 $response=&reply('instemailrules:'.&escape($udom),
                   2465:                                  $homeserver);
1.1172.2.146.  .5(raebu 2466:22):             } elsif ($check eq 'unamemap') {
                   2467:22):                 $response=&reply('unamemaprules:'.&escape($udom),
                   2468:22):                                  $homeserver);
1.923     raeburn  2469:             } else {
                   2470:                 $response=&reply('instuserrules:'.&escape($udom),
                   2471:                                  $homeserver);
                   2472:             }
1.912     raeburn  2473:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2474:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2475:                 ($response ne 'no_such_host')) {
                   2476:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2477:                 my @pairs=split(/\&/,$hashitems);
                   2478:                 foreach my $item (@pairs) {
                   2479:                     my ($key,$value)=split(/=/,$item,2);
                   2480:                     $key = &unescape($key);
                   2481:                     next if ($key =~ /^error: 2 /);
                   2482:                     $ruleshash{$key}=&thaw_unescape($value);
                   2483:                 }
                   2484:                 my @esc_order = split(/\&/,$orderitems);
                   2485:                 foreach my $item (@esc_order) {
                   2486:                     push(@ruleorder,&unescape($item));
                   2487:                 }
                   2488:             }
                   2489:         }
                   2490:     }
                   2491:     return (\%ruleshash,\@ruleorder);
                   2492: }
                   2493: 
1.976     raeburn  2494: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2495: 
                   2496: sub get_domain_defaults {
1.1172.2.35  raeburn  2497:     my ($domain,$ignore_cache) = @_;
                   2498:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2499:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2500:     unless ($ignore_cache) {
                   2501:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2502:         if (defined($cached)) {
                   2503:             if (ref($result) eq 'HASH') {
                   2504:                 return %{$result};
                   2505:             }
1.943     raeburn  2506:         }
                   2507:     }
                   2508:     my %domdefaults;
                   2509:     my %domconfig =
1.989     raeburn  2510:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2511:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2512:                                   'coursedefaults','usersessions',
1.1172.2.146.  .18(raeb 2513:-24):                                   'requestauthor','authordefaults',
                   2514:-24):                                   'selfenrollment','coursecategories',
                   2515:-24):                                   'autoenroll','helpsettings',
                   2516:-24):                                   'wafproxy','ltisec','toolsec',
                   2517:-24):                                   'domexttool','exttool'],$domain);
1.1172.2.41  raeburn  2518:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2519:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2520:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2521:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2522:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2523:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2524:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2525:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.146.  .12(raeb 2526:-23):         $domdefaults{'portal_def_email'} = $domconfig{'defaults'}{'portal_def_email'};
                   2527:-23):         $domdefaults{'portal_def_web'} = $domconfig{'defaults'}{'portal_def_web'};
1.1172.2.91  raeburn  2528:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2529:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2530:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.1172.2.146.  .5(raebu 2531:22):         $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
1.943     raeburn  2532:     } else {
                   2533:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2534:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2535:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2536:     }
1.976     raeburn  2537:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2538:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2539:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2540:         } else {
                   2541:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2542:         }
1.1172.2.6  raeburn  2543:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2544:         foreach my $item (@usertools) {
                   2545:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2546:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2547:             }
                   2548:         }
1.1172.2.29  raeburn  2549:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2550:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2551:         }
1.976     raeburn  2552:     }
1.985     raeburn  2553:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2554:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2555:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2556:         }
                   2557:     }
1.1172.2.146.  .18(raeb 2558:-24):     if (ref($domconfig{'authordefaults'}) eq 'HASH') {
                   2559:-24):         foreach my $item ('nocodemirror','copyright','sourceavail','domcoordacc','editors') {
                   2560:-24):             if ($item eq 'editors') {
                   2561:-24):                 if (ref($domconfig{'authordefaults'}{'editors'}) eq 'ARRAY') {
                   2562:-24):                     $domdefaults{$item} = join(',',@{$domconfig{'authordefaults'}{'editors'}});
                   2563:-24):                 }
                   2564:-24):             } else {
                   2565:-24):                 $domdefaults{$item} = $domconfig{'authordefaults'}{$item};
                   2566:-24):             }
                   2567:-24):         }
                   2568:-24):     }
1.1172.2.9  raeburn  2569:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2570:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2571:     }
1.989     raeburn  2572:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2573:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2574:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2575:         }
                   2576:     }
1.1047    raeburn  2577:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2578:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1172.2.144  raeburn  2579:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1172.2.60  raeburn  2580:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2581:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2582:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2583:         }
1.1172.2.41  raeburn  2584:         foreach my $type (@coursetypes) {
                   2585:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2586:                 unless ($type eq 'community') {
                   2587:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2588:                 }
                   2589:             }
                   2590:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2591:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2592:             }
1.1172.2.146.  .14(raeb 2593:-23):             if (ref($domconfig{'coursedefaults'}{'coursequota'}) eq 'HASH') {
                   2594:-23):                 $domdefaults{$type.'coursequota'} = $domconfig{'coursedefaults'}{'coursequota'}{$type};
                   2595:-23):             }
1.1172.2.60  raeburn  2596:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2597:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2598:                     $domdefaults{$type.'postsubtimeout'} =
                   2599:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2600:                 }
                   2601:             }
1.1172.2.146.  .13(raeb 2602:-23):             if (ref($domconfig{'coursedefaults'}{'domexttool'}) eq 'HASH') {
                   2603:-23):                 $domdefaults{$type.'domexttool'} = $domconfig{'coursedefaults'}{'domexttool'}{$type};
                   2604:-23):             } else {
                   2605:-23):                 $domdefaults{$type.'domexttool'} = 1;
                   2606:-23):             }
                   2607:-23):             if (ref($domconfig{'coursedefaults'}{'exttool'}) eq 'HASH') {
                   2608:-23):                 $domdefaults{$type.'exttool'} = $domconfig{'coursedefaults'}{'exttool'}{$type};
                   2609:-23):             } else {
                   2610:-23):                 $domdefaults{$type.'exttool'} = 0;
                   2611:-23):             }
1.1172.2.30  raeburn  2612:         }
1.1172.2.67  raeburn  2613:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2614:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2615:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2616:                 if (@clonecodes) {
                   2617:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2618:                 }
                   2619:             }
                   2620:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2621:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2622:         }
1.1172.2.103  raeburn  2623:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2624:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2625:         }
1.1172.2.146.  .3(raebu 2626:22):         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
                   2627:22):             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
                   2628:22):         }
1.1047    raeburn  2629:     }
1.1073    raeburn  2630:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2631:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2632:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2633:         }
                   2634:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2635:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2636:         }
1.1172.2.62  raeburn  2637:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2638:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2639:         }
1.1172.2.137  raeburn  2640:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1172.2.136  raeburn  2641:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2642:         }
1.1073    raeburn  2643:     }
1.1172.2.41  raeburn  2644:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2645:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2646:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2647:                             'approval','limit');
                   2648:             foreach my $type (@coursetypes) {
                   2649:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2650:                     my @mgrdc = ();
                   2651:                     foreach my $item (@settings) {
                   2652:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2653:                             push(@mgrdc,$item);
                   2654:                         }
                   2655:                     }
                   2656:                     if (@mgrdc) {
                   2657:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2658:                     }
                   2659:                 }
                   2660:             }
                   2661:         }
                   2662:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2663:             foreach my $type (@coursetypes) {
                   2664:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2665:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2666:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2667:                     }
                   2668:                 }
                   2669:             }
                   2670:         }
                   2671:     }
1.1172.2.46  raeburn  2672:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2673:         $domdefaults{'catauth'} = 'std';
                   2674:         $domdefaults{'catunauth'} = 'std';
                   2675:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2676:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2677:         }
                   2678:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2679:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2680:         }
                   2681:     }
1.1172.2.76  raeburn  2682:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2683:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1172.2.146  raeburn  2684:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1172.2.76  raeburn  2685:     }
1.1172.2.89  raeburn  2686:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2687:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2688:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2689:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2690:         }
                   2691:     }
1.1172.2.142  raeburn  2692:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   2693:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
                   2694:             if ($domconfig{'wafproxy'}{$item}) {
                   2695:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
                   2696:             }
                   2697:         }
                   2698:     }
1.1172.2.146.  .4(raebu 2699:22):     if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   2700:22):         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
                   2701:22):             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
                   2702:22):             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
                   2703:22):             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
                   2704:22):         }
                   2705:22):         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
                   2706:22):             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
          .13(raeb 2707:-23):                 $domdefaults{'ltiprivhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
                   2708:-23):             }
                   2709:-23):         }
          .17(raeb 2710:-24):         if (ref($domconfig{'ltisec'}{'suggested'}) eq 'HASH') {
                   2711:-24):             my %suggestions = %{$domconfig{'ltisec'}{'suggested'}};
                   2712:-24):             foreach my $item (keys(%{$domconfig{'ltisec'}{'suggested'}})) {
                   2713:-24):                 unless (ref($domconfig{'ltisec'}{'suggested'}{$item}) eq 'HASH') {
                   2714:-24):                     delete($suggestions{$item});
                   2715:-24):                 }
                   2716:-24):             }
                   2717:-24):             if (keys(%suggestions)) {
                   2718:-24):                 $domdefaults{'linkprotsuggested'} = \%suggestions;
                   2719:-24):             }
                   2720:-24):         }
          .13(raeb 2721:-23):     }
                   2722:-23):     if (ref($domconfig{'toolsec'}) eq 'HASH') {
                   2723:-23):         if (ref($domconfig{'toolsec'}{'encrypt'}) eq 'HASH') {
                   2724:-23):             $domdefaults{'toolenc_crs'} = $domconfig{'toolsec'}{'encrypt'}{'crs'};
                   2725:-23):             $domdefaults{'toolenc_dom'} = $domconfig{'toolsec'}{'encrypt'}{'dom'};
                   2726:-23):         }
                   2727:-23):         if (ref($domconfig{'toolsec'}{'private'}) eq 'HASH') {
                   2728:-23):             if (ref($domconfig{'toolsec'}{'private'}{'keys'}) eq 'ARRAY') {
                   2729:-23):                 $domdefaults{'toolprivhosts'} = $domconfig{'toolsec'}{'private'}{'keys'};
          .4(raebu 2730:22):             }
                   2731:22):         }
                   2732:22):     }
1.1172.2.23  raeburn  2733:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2734:     return %domdefaults;
                   2735: }
                   2736: 
1.1172.2.106  raeburn  2737: sub get_dom_cats {
                   2738:     my ($dom) = @_;
                   2739:     return unless (&domain($dom));
                   2740:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2741:     unless (defined($cached)) {
                   2742:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2743:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2744:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2745:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2746:             } else {
                   2747:                 $cats = {};
                   2748:             }
                   2749:         } else {
                   2750:             $cats = {};
                   2751:         }
                   2752:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2753:     }
                   2754:     return $cats;
                   2755: }
                   2756: 
                   2757: sub get_dom_instcats {
                   2758:     my ($dom) = @_;
                   2759:     return unless (&domain($dom));
                   2760:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2761:     unless (defined($cached)) {
                   2762:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2763:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2764:         if ($totcodes > 0) {
                   2765:             my $caller = 'global';
                   2766:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2767:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2768:                 $instcats = {
1.1172.2.146.  .10(raeb 2769:-23):                                 totcodes => $totcodes,
1.1172.2.106  raeburn  2770:                                 codes => \%codes,
                   2771:                                 codetitles => \@codetitles,
                   2772:                                 cat_titles => \%cat_titles,
                   2773:                                 cat_order => \%cat_order,
                   2774:                             };
                   2775:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2776:             }
                   2777:         }
                   2778:     }
                   2779:     return $instcats;
                   2780: }
                   2781: 
                   2782: sub retrieve_instcodes {
                   2783:     my ($coursecodes,$dom) = @_;
                   2784:     my $totcodes;
                   2785:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2786:     foreach my $course (keys(%courses)) {
                   2787:         if (ref($courses{$course}) eq 'HASH') {
                   2788:             if ($courses{$course}{'inst_code'} ne '') {
                   2789:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2790:                 $totcodes ++;
                   2791:             }
                   2792:         }
                   2793:     }
                   2794:     return $totcodes;
                   2795: }
                   2796: 
1.1172.2.113  raeburn  2797: # --------------------------------------------- Get domain config for passwords
                   2798: 
                   2799: sub get_passwdconf {
                   2800:     my ($dom) = @_;
                   2801:     my (%passwdconf,$gotconf,$lookup);
                   2802:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2803:     if (defined($cached)) {
                   2804:         if (ref($result) eq 'HASH') {
                   2805:             %passwdconf = %{$result};
                   2806:             $gotconf = 1;
                   2807:         }
                   2808:     }
                   2809:     unless ($gotconf) {
                   2810:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2811:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2812:             %passwdconf = %{$domconfig{'passwords'}};
                   2813:         }
                   2814:         my $cachetime = 24*60*60;
                   2815:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2816:     }
                   2817:     return %passwdconf;
                   2818: }
                   2819: 
1.1172.2.146.  .1(raebu 2820:22): sub course_portal_url {
                   2821:22):     my ($cnum,$cdom,$r) = @_;
                   2822:22):     my $chome = &homeserver($cnum,$cdom);
                   2823:22):     my $hostname = &hostname($chome);
                   2824:22):     my $protocol = $protocol{$chome};
                   2825:22):     $protocol = 'http' if ($protocol ne 'https');
                   2826:22):     my %domdefaults = &get_domain_defaults($cdom);
                   2827:22):     my $firsturl;
                   2828:22):     if ($domdefaults{'portal_def'}) {
                   2829:22):         $firsturl = $domdefaults{'portal_def'};
                   2830:22):     } else {
                   2831:22):         my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
                   2832:22):         $hostname = $alias if ($alias ne '');
                   2833:22):         $firsturl = $protocol.'://'.$hostname;
                   2834:22):     }
                   2835:22):     return $firsturl;
                   2836:22): }
                   2837:22): 
          .12(raeb 2838:-23): sub url_prefix {
                   2839:-23):     my ($r,$dom,$home,$context) = @_;
                   2840:-23):     my $prefix;
                   2841:-23):     my %domdefs = &get_domain_defaults($dom);
                   2842:-23):     if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
                   2843:-23):         if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
                   2844:-23):             $prefix = $1;
                   2845:-23):         }
                   2846:-23):     }
                   2847:-23):     if ($prefix eq '') {
                   2848:-23):         my $hostname = &hostname($home);
                   2849:-23):         my $protocol = $protocol{$home};
                   2850:-23):         $protocol = 'http' if ($protocol{$home} ne 'https');
                   2851:-23):         my $alias = &use_proxy_alias($r,$home);
                   2852:-23):         $hostname = $alias if ($alias ne '');
                   2853:-23):         $prefix = $protocol.'://'.$hostname;
                   2854:-23):     }
                   2855:-23):     return $prefix;
                   2856:-23): }
                   2857:-23): 
1.344     www      2858: # --------------------------------------------------- Assign a key to a student
                   2859: 
                   2860: sub assign_access_key {
1.364     www      2861: #
                   2862: # a valid key looks like uname:udom#comments
                   2863: # comments are being appended
                   2864: #
1.498     www      2865:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2866:     $kdom=
1.620     albertel 2867:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2868:     $knum=
1.620     albertel 2869:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2870:     $cdom=
1.620     albertel 2871:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2872:     $cnum=
1.620     albertel 2873:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2874:     $udom=$env{'user.name'} unless (defined($udom));
                   2875:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2876:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2877:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2878:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2879:                                                   # assigned to this person
                   2880:                                                   # - this should not happen,
1.345     www      2881:                                                   # unless something went wrong
                   2882:                                                   # the first time around
                   2883: # ready to assign
1.364     www      2884:         $logentry=$1.'; '.$logentry;
1.496     www      2885:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2886:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2887: # key now belongs to user
1.346     www      2888: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2889:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2890:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2891:                 return 'ok';
                   2892:             } else {
                   2893:                 return 
                   2894:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2895: 	    }
                   2896:         } else {
                   2897:             return 'error: Could not assign key, try again later.';
                   2898:         }
1.364     www      2899:     } elsif (!$existing{$ckey}) {
1.345     www      2900: # the key does not exist
                   2901: 	return 'error: The key does not exist';
                   2902:     } else {
                   2903: # the key is somebody else's
                   2904: 	return 'error: The key is already in use';
                   2905:     }
1.344     www      2906: }
                   2907: 
1.364     www      2908: # ------------------------------------------ put an additional comment on a key
                   2909: 
                   2910: sub comment_access_key {
                   2911: #
                   2912: # a valid key looks like uname:udom#comments
                   2913: # comments are being appended
                   2914: #
                   2915:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2916:     $cdom=
1.620     albertel 2917:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2918:     $cnum=
1.620     albertel 2919:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2920:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2921:     if ($existing{$ckey}) {
                   2922:         $existing{$ckey}.='; '.$logentry;
                   2923: # ready to assign
1.367     www      2924:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2925:                                                  $cdom,$cnum) eq 'ok') {
                   2926: 	    return 'ok';
                   2927:         } else {
                   2928: 	    return 'error: Count not store comment.';
                   2929:         }
                   2930:     } else {
                   2931: # the key does not exist
                   2932: 	return 'error: The key does not exist';
                   2933:     }
                   2934: }
                   2935: 
1.344     www      2936: # ------------------------------------------------------ Generate a set of keys
                   2937: 
                   2938: sub generate_access_keys {
1.364     www      2939:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2940:     $cdom=
1.620     albertel 2941:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2942:     $cnum=
1.620     albertel 2943:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2944:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2945:     unless (($cdom) && ($cnum)) { return 0; }
                   2946:     if ($number>10000) { return 0; }
                   2947:     sleep(2); # make sure don't get same seed twice
                   2948:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2949:     my $total=0;
                   2950:     for (my $i=1;$i<=$number;$i++) {
                   2951:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2952:                   sprintf("%lx",int(100000*rand)).'-'.
                   2953:                   sprintf("%lx",int(100000*rand));
                   2954:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2955:        $newkey=~s/0/h/g; # and also 0 and O
                   2956:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2957:        if ($existing{$newkey}) {
                   2958:            $i--;
                   2959:        } else {
1.364     www      2960: 	  if (&put('accesskeys',
                   2961:               { $newkey => '# generated '.localtime().
1.620     albertel 2962:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2963:                            '; '.$logentry },
                   2964: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2965:               $total++;
                   2966: 	  }
                   2967:        }
                   2968:     }
1.620     albertel 2969:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2970:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2971:     return $total;
                   2972: }
                   2973: 
                   2974: # ------------------------------------------------------- Validate an accesskey
                   2975: 
                   2976: sub validate_access_key {
                   2977:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2978:     $cdom=
1.620     albertel 2979:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2980:     $cnum=
1.620     albertel 2981:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2982:     $udom=$env{'user.domain'} unless (defined($udom));
                   2983:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2984:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2985:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2986: }
                   2987: 
                   2988: # ------------------------------------- Find the section of student in a course
1.652     albertel 2989: sub devalidate_getsection_cache {
                   2990:     my ($udom,$unam,$courseid)=@_;
                   2991:     my $hashid="$udom:$unam:$courseid";
                   2992:     &devalidate_cache_new('getsection',$hashid);
                   2993: }
1.298     matthew  2994: 
1.815     albertel 2995: sub courseid_to_courseurl {
                   2996:     my ($courseid) = @_;
                   2997:     #already url style courseid
                   2998:     return $courseid if ($courseid =~ m{^/});
                   2999: 
                   3000:     if (exists($env{'course.'.$courseid.'.num'})) {
                   3001: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   3002: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   3003: 	return "/$cdom/$cnum";
                   3004:     }
                   3005: 
                   3006:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   3007:     if (exists($courseinfo{'num'})) {
                   3008: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   3009:     }
                   3010: 
                   3011:     return undef;
                   3012: }
                   3013: 
1.298     matthew  3014: sub getsection {
                   3015:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 3016:     my $cachetime=1800;
1.551     albertel 3017: 
                   3018:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 3019:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 3020:     if (defined($cached)) { return $result; }
                   3021: 
1.298     matthew  3022:     my %Pending; 
                   3023:     my %Expired;
                   3024:     #
                   3025:     # Each role can either have not started yet (pending), be active, 
                   3026:     #    or have expired.
                   3027:     #
                   3028:     # If there is an active role, we are done.
                   3029:     #
                   3030:     # If there is more than one role which has not started yet, 
                   3031:     #     choose the one which will start sooner
                   3032:     # If there is one role which has not started yet, return it.
                   3033:     #
                   3034:     # If there is more than one expired role, choose the one which ended last.
                   3035:     # If there is a role which has expired, return it.
                   3036:     #
1.815     albertel 3037:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  3038:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  3039:     foreach my $key (keys(%roleshash)) {
1.479     albertel 3040:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  3041:         my $section=$1;
                   3042:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  3043:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  3044:         my $now=time;
1.548     albertel 3045:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  3046:             $Expired{$end}=$section;
                   3047:             next;
                   3048:         }
1.548     albertel 3049:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  3050:             $Pending{$start}=$section;
                   3051:             next;
                   3052:         }
1.599     albertel 3053:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  3054:     }
                   3055:     #
                   3056:     # Presumedly there will be few matching roles from the above
                   3057:     # loop and the sorting time will be negligible.
                   3058:     if (scalar(keys(%Pending))) {
                   3059:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 3060:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  3061:     } 
                   3062:     if (scalar(keys(%Expired))) {
                   3063:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   3064:         my $time = pop(@sorted);
1.599     albertel 3065:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  3066:     }
1.599     albertel 3067:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  3068: }
1.70      www      3069: 
1.599     albertel 3070: sub save_cache {
                   3071:     &purge_remembered();
1.722     albertel 3072:     #&Apache::loncommon::validate_page();
1.620     albertel 3073:     undef(%env);
1.780     albertel 3074:     undef($env_loaded);
1.599     albertel 3075: }
1.452     albertel 3076: 
1.599     albertel 3077: my $to_remember=-1;
                   3078: my %remembered;
                   3079: my %accessed;
                   3080: my $kicks=0;
                   3081: my $hits=0;
1.849     albertel 3082: sub make_key {
                   3083:     my ($name,$id) = @_;
1.872     albertel 3084:     if (length($id) > 65 
                   3085: 	&& length(&escape($id)) > 200) {
                   3086: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   3087:     }
1.849     albertel 3088:     return &escape($name.':'.$id);
                   3089: }
                   3090: 
1.599     albertel 3091: sub devalidate_cache_new {
                   3092:     my ($name,$id,$debug) = @_;
                   3093:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  3094:     my $remembered_id=$name.':'.$id;
1.849     albertel 3095:     $id=&make_key($name,$id);
1.599     albertel 3096:     $memcache->delete($id);
1.1172.2.81  raeburn  3097:     delete($remembered{$remembered_id});
                   3098:     delete($accessed{$remembered_id});
1.599     albertel 3099: }
                   3100: 
                   3101: sub is_cached_new {
                   3102:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  3103:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   3104:                                      # keys in %remembered hash, which persists for
                   3105:                                      # duration of request (no restriction on key length).
                   3106:     if (exists($remembered{$remembered_id})) {
                   3107: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   3108: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3109: 	$hits++;
1.1172.2.81  raeburn  3110: 	return ($remembered{$remembered_id},1);
1.599     albertel 3111:     }
1.1172.2.81  raeburn  3112:     $id=&make_key($name,$id);
1.599     albertel 3113:     my $value = $memcache->get($id);
                   3114:     if (!(defined($value))) {
                   3115: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 3116: 	return (undef,undef);
1.416     albertel 3117:     }
1.599     albertel 3118:     if ($value eq '__undef__') {
                   3119: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   3120: 	$value=undef;
                   3121:     }
1.1172.2.81  raeburn  3122:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3123:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   3124:     return ($value,1);
                   3125: }
                   3126: 
                   3127: sub do_cache_new {
                   3128:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  3129:     my $remembered_id=$name.':'.$id;
1.849     albertel 3130:     $id=&make_key($name,$id);
1.599     albertel 3131:     my $setvalue=$value;
                   3132:     if (!defined($setvalue)) {
                   3133: 	$setvalue='__undef__';
                   3134:     }
1.623     albertel 3135:     if (!defined($time) ) {
                   3136: 	$time=600;
                   3137:     }
1.599     albertel 3138:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 3139:     my $result = $memcache->set($id,$setvalue,$time);
                   3140:     if (! $result) {
1.872     albertel 3141: 	&logthis("caching of id -> $id  failed");
1.910     albertel 3142: 	$memcache->disconnect_all();
1.872     albertel 3143:     }
1.600     albertel 3144:     # need to make a copy of $value
1.1172.2.81  raeburn  3145:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3146:     return $value;
                   3147: }
                   3148: 
                   3149: sub make_room {
1.1172.2.81  raeburn  3150:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3151: 
1.1172.2.81  raeburn  3152:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3153:                                     : $value;
1.599     albertel 3154:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  3155:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3156:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3157:     my $to_kick;
                   3158:     my $max_time=0;
                   3159:     foreach my $other (keys(%accessed)) {
                   3160: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3161: 	    $to_kick=$other;
                   3162: 	    $max_time=&tv_interval($accessed{$other});
                   3163: 	}
                   3164:     }
                   3165:     delete($remembered{$to_kick});
                   3166:     delete($accessed{$to_kick});
                   3167:     $kicks++;
                   3168:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3169:     return;
                   3170: }
                   3171: 
1.599     albertel 3172: sub purge_remembered {
1.604     albertel 3173:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3174:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3175:     undef(%remembered);
                   3176:     undef(%accessed);
1.428     albertel 3177: }
1.70      www      3178: # ------------------------------------- Read an entry from a user's environment
                   3179: 
                   3180: sub userenvironment {
                   3181:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3182:     my $items;
                   3183:     foreach my $item (@what) {
                   3184:         $items.=&escape($item).'&';
                   3185:     }
                   3186:     $items=~s/\&$//;
1.70      www      3187:     my %returnhash=();
1.1009    raeburn  3188:     my $uhome = &homeserver($unam,$udom);
                   3189:     unless ($uhome eq 'no_host') {
                   3190:         my @answer=split(/\&/, 
                   3191:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3192:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3193:             return %returnhash;
                   3194:         }
1.1009    raeburn  3195:         my $i;
                   3196:         for ($i=0;$i<=$#what;$i++) {
                   3197: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3198:         }
1.70      www      3199:     }
                   3200:     return %returnhash;
1.1       albertel 3201: }
                   3202: 
1.617     albertel 3203: # ---------------------------------------------------------- Get a studentphoto
                   3204: sub studentphoto {
                   3205:     my ($udom,$unam,$ext) = @_;
                   3206:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3207:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3208:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3209:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3210:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3211:             } else {
                   3212:                 my ($result,$perm_reqd)=
1.707     albertel 3213: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3214:                 if ($result eq 'ok') {
                   3215:                     if (!($perm_reqd eq 'yes')) {
                   3216:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3217:                     }
                   3218:                 }
                   3219:             }
                   3220:         }
                   3221:     } else {
                   3222:         my ($result,$perm_reqd) = 
1.707     albertel 3223: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3224:         if ($result eq 'ok') {
                   3225:             if (!($perm_reqd eq 'yes')) {
                   3226:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3227:             }
                   3228:         }
                   3229:     }
                   3230:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3231: }
                   3232: 
                   3233: sub retrievestudentphoto {
                   3234:     my ($udom,$unam,$ext,$type) = @_;
                   3235:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3236:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3237:     if ($ret eq 'ok') {
                   3238:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3239:         if ($type eq 'thumbnail') {
                   3240:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3241:         }
                   3242:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3243:         return $tokenurl;
                   3244:     } else {
                   3245:         if ($type eq 'thumbnail') {
                   3246:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3247:         } else { 
                   3248:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3249:         }
1.617     albertel 3250:     }
                   3251: }
                   3252: 
1.263     www      3253: # -------------------------------------------------------------------- New chat
                   3254: 
                   3255: sub chatsend {
1.724     raeburn  3256:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3257:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3258:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3259:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3260:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3261: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3262: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3263: }
                   3264: 
                   3265: # ------------------------------------------ Find current version of a resource
                   3266: 
                   3267: sub getversion {
                   3268:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  3269:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3270:     return &currentversion(&filelocation('',$fname));
                   3271: }
                   3272: 
                   3273: sub currentversion {
                   3274:     my $fname=shift;
                   3275:     my $author=$fname;
                   3276:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3277:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3278:     my $home=&homeserver($uname,$udom);
1.292     www      3279:     if ($home eq 'no_host') { 
                   3280:         return -1; 
                   3281:     }
1.1112    www      3282:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3283:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3284: 	return -1;
                   3285:     }
1.1112    www      3286:     return $answer;
1.263     www      3287: }
                   3288: 
1.1111    www      3289: #
                   3290: # Return special version number of resource if set by override, empty otherwise
                   3291: #
                   3292: sub usedversion {
                   3293:     my $fname=shift;
                   3294:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3295:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3296:     if ($urlversion) { return $urlversion; }
                   3297:     return '';
                   3298: }
                   3299: 
1.1       albertel 3300: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3301: 
1.1       albertel 3302: sub subscribe {
                   3303:     my $fname=shift;
1.761     raeburn  3304:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3305:     $fname=~s/[\n\r]//g;
1.1       albertel 3306:     my $author=$fname;
                   3307:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3308:     my ($udom,$uname)=split(/\//,$author);
                   3309:     my $home=homeserver($uname,$udom);
1.335     albertel 3310:     if ($home eq 'no_host') {
                   3311:         return 'not_found';
1.1       albertel 3312:     }
                   3313:     my $answer=reply("sub:$fname",$home);
1.64      www      3314:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3315: 	$answer.=' by '.$home;
                   3316:     }
1.1       albertel 3317:     return $answer;
                   3318: }
                   3319:     
1.8       www      3320: # -------------------------------------------------------------- Replicate file
                   3321: 
                   3322: sub repcopy {
                   3323:     my $filename=shift;
1.23      www      3324:     $filename=~s/\/+/\//g;
1.1142    raeburn  3325:     my $londocroot = $perlvar{'lonDocRoot'};
                   3326:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3327:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3328:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3329: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3330: 	return &repcopy_userfile($filename);
                   3331:     }
1.532     albertel 3332:     $filename=~s/[\n\r]//g;
1.8       www      3333:     my $transname="$filename.in.transfer";
1.828     www      3334: # FIXME: this should flock
1.607     raeburn  3335:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3336:     my $remoteurl=subscribe($filename);
1.64      www      3337:     if ($remoteurl =~ /^con_lost by/) {
                   3338: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3339:            return 'unavailable';
1.8       www      3340:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3341: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3342: 	   return 'not_found';
1.64      www      3343:     } elsif ($remoteurl =~ /^rejected by/) {
                   3344: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3345:            return 'forbidden';
1.20      www      3346:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3347:            return 'ok';
1.8       www      3348:     } else {
1.290     www      3349:         my $author=$filename;
                   3350:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3351:         my ($udom,$uname)=split(/\//,$author);
                   3352:         my $home=homeserver($uname,$udom);
                   3353:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3354:            my @parts=split(/\//,$filename);
                   3355:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3356:            if ($path ne "$londocroot/res") {
1.8       www      3357:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3358: 	       return 'bad_request';
1.8       www      3359:            }
                   3360:            my $count;
                   3361:            for ($count=5;$count<$#parts;$count++) {
                   3362:                $path.="/$parts[$count]";
                   3363:                if ((-e $path)!=1) {
                   3364: 		   mkdir($path,0777);
                   3365:                }
                   3366:            }
                   3367:            my $ua=new LWP::UserAgent;
                   3368:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3369:            my $response=$ua->request($request,$transname);
                   3370:            if ($response->is_error()) {
                   3371: 	       unlink($transname);
                   3372:                my $message=$response->status_line;
1.672     albertel 3373:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3374:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3375:                return 'unavailable';
1.8       www      3376:            } else {
1.16      www      3377: 	       if ($remoteurl!~/\.meta$/) {
                   3378:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3379:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3380:                   if ($mresponse->is_error()) {
                   3381: 		      unlink($filename.'.meta');
                   3382:                       &logthis(
1.672     albertel 3383:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3384:                   }
                   3385: 	       }
1.8       www      3386:                rename($transname,$filename);
1.607     raeburn  3387:                return 'ok';
1.8       www      3388:            }
1.290     www      3389:        }
1.8       www      3390:     }
1.330     www      3391: }
                   3392: 
1.1172.2.124  raeburn  3393: # ------------------------------------------------- Unsubscribe from a resource
                   3394: 
                   3395: sub unsubscribe {
                   3396:     my ($fname) = @_;
                   3397:     my $answer;
                   3398:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3399:     $fname=~s/[\n\r]//g;
                   3400:     my $author=$fname;
                   3401:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3402:     my ($udom,$uname)=split(/\//,$author);
                   3403:     my $home=homeserver($uname,$udom);
                   3404:     if ($home eq 'no_host') {
                   3405:         $answer = 'no_host';
                   3406:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3407:         $answer = 'home';
                   3408:     } else {
1.1172.2.125  raeburn  3409:         $answer = reply("unsub:$fname",$home);
1.1172.2.124  raeburn  3410:     }
                   3411:     return $answer;
                   3412: }
                   3413: 
1.330     www      3414: # ------------------------------------------------ Get server side include body
                   3415: sub ssi_body {
1.381     albertel 3416:     my ($filelink,%form)=@_;
1.606     matthew  3417:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3418:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3419:     }
1.953     www      3420:     my $output='';
                   3421:     my $response;
1.980     raeburn  3422:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3423:        ($output,$response)=&externalssi($filelink);
1.953     www      3424:     } else {
1.1004    droeschl 3425:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3426:        $filelink .= 'inhibitmenu=yes';
1.953     www      3427:        ($output,$response)=&ssi($filelink,%form);
                   3428:     }
1.778     albertel 3429:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3430:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3431:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3432:     if (wantarray) {
                   3433:         return ($output, $response);
                   3434:     } else {
                   3435:         return $output;
                   3436:     }
1.8       www      3437: }
                   3438: 
1.15      www      3439: # --------------------------------------------------------- Server Side Include
                   3440: 
1.782     albertel 3441: sub absolute_url {
1.1172.2.145  raeburn  3442:     my ($host_name,$unalias,$keep_proto) = @_;
1.782     albertel 3443:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3444:     if ($host_name eq '') {
                   3445: 	$host_name = $ENV{'SERVER_NAME'};
                   3446:     }
1.1172.2.145  raeburn  3447:     if ($unalias) {
                   3448:         my $alias = &get_proxy_alias();
                   3449:         if ($alias eq $host_name) {
                   3450:             my $lonhost = $perlvar{'lonHostID'};
                   3451:             my $hostname = &hostname($lonhost);
                   3452:             my $lcproto;
                   3453:             if (($keep_proto) || ($hostname eq '')) {
                   3454:                 $lcproto = $protocol;
                   3455:             } else {
                   3456:                 $lcproto = $protocol{$lonhost};
                   3457:                 $lcproto = 'http' if ($lcproto ne 'https');
                   3458:                 $lcproto .= '://';
                   3459:             }
                   3460:             unless ($hostname eq '') {
                   3461:                 return $lcproto.$hostname;
                   3462:             }
                   3463:         }
                   3464:     } 
1.782     albertel 3465:     return $protocol.$host_name;
                   3466: }
                   3467: 
1.942     foxr     3468: #
                   3469: #   Server side include.
                   3470: # Parameters:
                   3471: #  fn     Possibly encrypted resource name/id.
                   3472: #  form   Hash that describes how the rendering should be done
                   3473: #         and other things.
1.944     foxr     3474: # Returns:
1.950     raeburn  3475: #   Scalar context: The content of the response.
                   3476: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3477: #     
1.15      www      3478: sub ssi {
                   3479: 
1.944     foxr     3480:     my ($fn,%form)=@_;
1.1172.2.145  raeburn  3481:     my ($host,$request,$response);
                   3482:     $host = &absolute_url('',1);
1.711     albertel 3483: 
                   3484:     $form{'no_update_last_known'}=1;
1.895     albertel 3485:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3486:     if (%form) {
1.1172.2.145  raeburn  3487:       $request=new HTTP::Request('POST',$host.$fn);
1.1172.2.58  raeburn  3488:       $request->content(join('&',map {
                   3489:             my $name = escape($_);
                   3490:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3491:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3492:             : &escape($form{$_}) );
                   3493:         } keys(%form)));
1.23      www      3494:     } else {
1.1172.2.145  raeburn  3495:       $request=new HTTP::Request('GET',$host.$fn);
1.23      www      3496:     }
                   3497: 
1.15      www      3498:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3499: 
1.1172.2.101  raeburn  3500:     if (($env{'request.course.id'}) &&
                   3501:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3502:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3503:         ($form{'grade_symb'} ne '') &&
                   3504:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3505:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3506:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3507:             my $ua=new LWP::UserAgent;
                   3508:             $ua->local_address('127.0.0.1');
                   3509:             $response = $ua->request($request);
                   3510:         } else {
                   3511:             {
                   3512:                 require LWP::Protocol::http;
                   3513:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3514:                 my $ua=new LWP::UserAgent;
                   3515:                 $response = $ua->request($request);
                   3516:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3517:             }
                   3518:         }
                   3519:     } else {
                   3520:         my $ua=new LWP::UserAgent;
                   3521:         $response = $ua->request($request);
                   3522:     }
1.944     foxr     3523:     if (wantarray) {
1.1172.2.3  raeburn  3524: 	return ($response->content, $response);
1.944     foxr     3525:     } else {
1.1172.2.3  raeburn  3526: 	return $response->content;
1.942     foxr     3527:     }
1.324     www      3528: }
                   3529: 
                   3530: sub externalssi {
                   3531:     my ($url)=@_;
                   3532:     my $ua=new LWP::UserAgent;
                   3533:     my $request=new HTTP::Request('GET',$url);
                   3534:     my $response=$ua->request($request);
1.954     raeburn  3535:     if (wantarray) {
                   3536:         return ($response->content, $response);
                   3537:     } else {
                   3538:         return $response->content;
                   3539:     }
1.15      www      3540: }
1.254     www      3541: 
1.1172.2.98  raeburn  3542: # If the local copy of a replicated resource is outdated, trigger a
                   3543: # connection from the homeserver to flush the delayed queue. If no update
                   3544: # happens, remove local copies of outdated resource (and corresponding
                   3545: # metadata file).
                   3546: 
                   3547: sub remove_stale_resfile {
                   3548:     my ($url) = @_;
                   3549:     my $removed;
                   3550:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3551:         my $audom = $1;
                   3552:         my $auname = $2;
                   3553:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3554:             my $homeserver = &homeserver($auname,$audom);
                   3555:             unless (($homeserver eq 'no_host') ||
                   3556:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3557:                 my $fname = &filelocation('',$url);
                   3558:                 if (-e $fname) {
                   3559:                     my $hostname = &hostname($homeserver);
                   3560:                     if ($hostname) {
1.1172.2.120  raeburn  3561:                         my $protocol = $protocol{$homeserver};
                   3562:                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3563:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120  raeburn  3564:                         my $ua=new LWP::UserAgent;
                   3565:                         $ua->timeout(5);
1.1172.2.98  raeburn  3566:                         my $request=new HTTP::Request('HEAD',$uri);
                   3567:                         my $response=$ua->request($request);
                   3568:                         if ($response->is_success()) {
                   3569:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3570:                             my $locmodtime = (stat($fname))[9];
                   3571:                             if ($locmodtime < $remmodtime) {
                   3572:                                 my $stale;
                   3573:                                 my $answer = &reply('pong',$homeserver);
                   3574:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3575:                                     sleep(0.2);
                   3576:                                     $locmodtime = (stat($fname))[9];
                   3577:                                     if ($locmodtime < $remmodtime) {
                   3578:                                         my $posstransfer = $fname.'.in.transfer';
                   3579:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3580:                                             $removed = 1;
                   3581:                                         } else {
                   3582:                                             $stale = 1;
                   3583:                                         }
                   3584:                                     } else {
                   3585:                                         $removed = 1;
                   3586:                                     }
                   3587:                                 } else {
                   3588:                                     $stale = 1;
                   3589:                                 }
                   3590:                                 if ($stale) {
1.1172.2.124  raeburn  3591:                                     if (unlink($fname)) {
                   3592:                                         if ($uri!~/\.meta$/) {
                   3593:                                             if (-e $fname.'.meta') {
                   3594:                                                 unlink($fname.'.meta');
                   3595:                                             }
                   3596:                                         }
                   3597:                                         my $unsubresult = &unsubscribe($fname);
                   3598:                                         unless ($unsubresult eq 'ok') {
                   3599:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3600:                                         }
                   3601:                                         $removed = 1;
1.1172.2.98  raeburn  3602:                                     }
                   3603:                                 }
                   3604:                             }
                   3605:                         }
                   3606:                     }
                   3607:                 }
                   3608:             }
                   3609:         }
                   3610:     }
                   3611:     return $removed;
                   3612: }
                   3613: 
1.492     albertel 3614: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3615: 
                   3616: sub allowuploaded {
                   3617:     my ($srcurl,$url)=@_;
                   3618:     $url=&clutter(&declutter($url));
                   3619:     my $dir=$url;
                   3620:     $dir=~s/\/[^\/]+$//;
                   3621:     my %httpref=();
                   3622:     my $httpurl=&hreflocation('',$url);
                   3623:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3624:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3625: }
1.477     raeburn  3626: 
1.1172.2.13  raeburn  3627: #
                   3628: # Determine if the current user should be able to edit a particular resource,
                   3629: # when viewing in course context.
                   3630: # (a) When viewing resource used to determine if "Edit" item is included in
                   3631: #     Functions.
                   3632: # (b) When displaying folder contents in course editor, used to determine if
                   3633: #     "Edit" link will be displayed alongside resource.
                   3634: #
                   3635: #  input: six args -- filename (decluttered), course number, course domain,
                   3636: #                   url, symb (if registered) and group (if this is a group
                   3637: #                   item -- e.g., bulletin board, group page etc.).
                   3638: #  output: array of five scalars --
                   3639: #          $cfile -- url for file editing if editable on current server
                   3640: #          $home -- homeserver of resource (i.e., for author if published,
                   3641: #                                           or course if uploaded.).
                   3642: #          $switchserver --  1 if server switch will be needed.
                   3643: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3644: #          $forceview -- 1 if icon/link should be to go to view mode
                   3645: #
                   3646: 
                   3647: sub can_edit_resource {
                   3648:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3649:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3650: #
                   3651: # For aboutme pages user can only edit his/her own.
                   3652: #
                   3653:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3654:         my ($sdom,$sname) = ($1,$2);
                   3655:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3656:             $home = $env{'user.home'};
                   3657:             $cfile = $resurl;
                   3658:             if ($env{'form.forceedit'}) {
                   3659:                 $forceview = 1;
                   3660:             } else {
                   3661:                 $forceedit = 1;
                   3662:             }
                   3663:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3664:         } else {
                   3665:             return;
                   3666:         }
                   3667:     }
                   3668: 
                   3669:     if ($env{'request.course.id'}) {
                   3670:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3671:         if ($group ne '') {
                   3672: # if this is a group homepage or group bulletin board, check group privs
                   3673:             my $allowed = 0;
                   3674:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3675:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3676:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3677:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3678:                     $allowed = 1;
                   3679:                 }
                   3680:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3681:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3682:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3683:                     $allowed = 1;
                   3684:                 }
                   3685:             }
                   3686:             if ($allowed) {
                   3687:                 $home=&homeserver($cnum,$cdom);
                   3688:                 if ($env{'form.forceedit'}) {
                   3689:                     $forceview = 1;
                   3690:                 } else {
                   3691:                     $forceedit = 1;
                   3692:                 }
                   3693:                 $cfile = $resurl;
                   3694:             } else {
                   3695:                 return;
                   3696:             }
                   3697:         } else {
1.1172.2.15  raeburn  3698:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3699:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3700:                     return;
                   3701:                 }
                   3702:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3703: #
                   3704: # No edit allowed where CC has switched to student role.
                   3705: #
                   3706:                 return;
                   3707:             }
                   3708:         }
                   3709:     }
                   3710: 
                   3711:     if ($file ne '') {
                   3712:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3713:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3714:                 $uploaded = 1;
                   3715:                 $incourse = 1;
                   3716:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3717:                     $cfile = &hreflocation('',$file);
                   3718:                     if ($env{'form.forceedit'}) {
                   3719:                         $forceview = 1;
                   3720:                     } else {
                   3721:                         $forceedit = 1;
                   3722:                     }
                   3723:                 }
                   3724:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3725:                 $incourse = 1;
                   3726:                 if ($env{'form.forceedit'}) {
                   3727:                     $forceview = 1;
                   3728:                 } else {
                   3729:                     $forceedit = 1;
                   3730:                 }
                   3731:                 $cfile = $resurl;
                   3732:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3733:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3734:                     $incourse = 1;
                   3735:                     if ($env{'form.forceedit'}) {
                   3736:                         $forceview = 1;
                   3737:                     } else {
                   3738:                         $forceedit = 1;
                   3739:                     }
                   3740:                     $cfile = $resurl;
                   3741:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3742:                     $incourse = 1;
                   3743:                     $cfile = $resurl.'/smpedit';
                   3744:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3745:                     $incourse = 1;
                   3746:                     if ($env{'form.forceedit'}) {
                   3747:                         $forceview = 1;
                   3748:                     } else {
                   3749:                         $forceedit = 1;
                   3750:                     }
                   3751:                     $cfile = $resurl;
1.1172.2.122  raeburn  3752:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3753:                     my ($map,$id,$res) = &decode_symb($symb);
                   3754:                     if ($map =~ /\.page$/) {
                   3755:                         $incourse = 1;
                   3756:                         if ($env{'form.forceedit'}) {
                   3757:                             $forceview = 1;
                   3758:                             $cfile = $map;
                   3759:                         } else {
                   3760:                             $forceedit = 1;
                   3761:                             $cfile =  '/adm/wrapper'.$resurl;
                   3762:                         }
                   3763:                     }
1.1172.2.146.  .1(raebu 3764:22):                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3765:22):                     $incourse = 1;
                   3766:22):                     if ($env{'form.forceedit'}) {
                   3767:22):                         $forceview = 1;
                   3768:22):                     } else {
                   3769:22):                         $forceedit = 1;
                   3770:22):                     }
                   3771:22):                     $cfile = $resurl;
1.1172.2.15  raeburn  3772:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3773:                     $incourse = 1;
                   3774:                     if ($env{'form.forceedit'}) {
                   3775:                         $forceview = 1;
                   3776:                     } else {
                   3777:                         $forceedit = 1;
                   3778:                     }
                   3779:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3780:                 }
                   3781:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3782:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3783:                 if (&is_on_map($template)) {
                   3784:                     $incourse = 1;
                   3785:                     $forceview = 1;
                   3786:                     $cfile = $template;
                   3787:                 }
                   3788:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3789:                 $incourse = 1;
                   3790:                 if ($env{'form.forceedit'}) {
                   3791:                     $forceview = 1;
                   3792:                 } else {
                   3793:                     $forceedit = 1;
                   3794:                 }
                   3795:                 $cfile = $resurl;
1.1172.2.146.  .1(raebu 3796:22):             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3797:22):                 $incourse = 1;
                   3798:22):                 if ($env{'form.forceedit'}) {
                   3799:22):                     $forceview = 1;
                   3800:22):                 } else {
                   3801:22):                     $forceedit = 1;
                   3802:22):                 }
                   3803:22):                 $cfile = $resurl;
1.1172.2.13  raeburn  3804:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3805:                 $incourse = 1;
                   3806:                 $forceview = 1;
                   3807:                 if ($symb) {
                   3808:                     my ($map,$id,$res)=&decode_symb($symb);
                   3809:                     $env{'request.symb'} = $symb;
                   3810:                     $cfile = &clutter($res);
                   3811:                 } else {
                   3812:                     $cfile = $env{'form.suppurl'};
1.1172.2.146.  .1(raebu 3813:22):                     my $escfile = &unescape($cfile);
                   3814:22):                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3815:22):                         $cfile = '/adm/wrapper'.$escfile;
                   3816:22):                     } else {
                   3817:22):                         $escfile =~ s{^http://}{};
                   3818:22):                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3819:22):                     }
1.1172.2.13  raeburn  3820:                 }
1.1172.2.31  raeburn  3821:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3822:                 if ($env{'form.forceedit'}) {
                   3823:                     $forceview = 1;
                   3824:                 } else {
                   3825:                     $forceedit = 1;
                   3826:                 }
                   3827:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3828:             }
                   3829:         }
                   3830:         if ($uploaded || $incourse) {
                   3831:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3832:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3833:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3834:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3835:             # Check that the user has permission to edit this resource
                   3836:             my $setpriv = 1;
                   3837:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3838:             if (defined($cfudom)) {
                   3839:                 $home=&homeserver($cfuname,$cfudom);
                   3840:                 $cfile=$file;
                   3841:             }
                   3842:         }
                   3843:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3844:             (($home ne '') && ($home ne 'no_host'))) {
                   3845:             my @ids=&current_machine_ids();
                   3846:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3847:                 $switchserver=1;
                   3848:             }
                   3849:         }
                   3850:     }
                   3851:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3852: }
                   3853: 
                   3854: sub is_course_upload {
                   3855:     my ($file,$cnum,$cdom) = @_;
                   3856:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3857:     $uploadpath =~ s{^\/}{};
                   3858:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3859:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3860:         return 1;
                   3861:     }
                   3862:     return;
                   3863: }
                   3864: 
                   3865: sub in_course {
                   3866:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3867:     if ($hideprivileged) {
                   3868:         my $skipuser;
1.1172.2.23  raeburn  3869:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3870:         my @possdoms = ($cdom);
                   3871:         if ($coursehash{'checkforpriv'}) {
                   3872:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3873:         }
                   3874:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3875:             $skipuser = 1;
                   3876:             if ($coursehash{'nothideprivileged'}) {
                   3877:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3878:                     my $user;
                   3879:                     if ($item =~ /:/) {
                   3880:                         $user = $item;
                   3881:                     } else {
                   3882:                         $user = join(':',split(/[\@]/,$item));
                   3883:                     }
                   3884:                     if ($user eq $uname.':'.$udom) {
                   3885:                         undef($skipuser);
                   3886:                         last;
                   3887:                     }
                   3888:                 }
                   3889:             }
                   3890:             if ($skipuser) {
                   3891:                 return 0;
                   3892:             }
                   3893:         }
                   3894:     }
                   3895:     $type ||= 'any';
                   3896:     if (!defined($cdom) || !defined($cnum)) {
                   3897:         my $cid  = $env{'request.course.id'};
                   3898:         $cdom = $env{'course.'.$cid.'.domain'};
                   3899:         $cnum = $env{'course.'.$cid.'.num'};
                   3900:     }
                   3901:     my $typesref;
                   3902:     if (($type eq 'any') || ($type eq 'all')) {
                   3903:         $typesref = ['active','previous','future'];
                   3904:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3905:         $typesref = [$type];
                   3906:     }
                   3907:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3908:                               $typesref,undef,[$cdom]);
                   3909:     my ($tmp) = keys(%roles);
                   3910:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3911:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3912:     if (@course_roles > 0) {
                   3913:         return 1;
                   3914:     }
                   3915:     return 0;
                   3916: }
                   3917: 
1.478     albertel 3918: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3919: # input: action, courseID, current domain, intended
1.637     raeburn  3920: #        path to file, source of file, instruction to parse file for objects,
                   3921: #        ref to hash for embedded objects,
                   3922: #        ref to hash for codebase of java objects.
1.1095    raeburn  3923: #        reference to scalar to accommodate mime type determined
                   3924: #          from File::MMagic if $parser = parse.
1.637     raeburn  3925: #
1.485     raeburn  3926: # output: url to file (if action was uploaddoc), 
                   3927: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3928: #
1.478     albertel 3929: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3930: # course.
1.477     raeburn  3931: #
1.478     albertel 3932: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3933: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3934: #          course's home server.
1.477     raeburn  3935: #
1.478     albertel 3936: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3937: #          be copied from $source (current location) to 
                   3938: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3939: #         and will then be copied to
                   3940: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3941: #         course's home server.
1.485     raeburn  3942: #
1.481     raeburn  3943: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3944: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3945: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3946: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3947: #         in course's home server.
1.637     raeburn  3948: #
1.477     raeburn  3949: 
                   3950: sub process_coursefile {
1.1095    raeburn  3951:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3952:         $mimetype)=@_;
1.477     raeburn  3953:     my $fetchresult;
1.638     albertel 3954:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3955:     if ($action eq 'propagate') {
1.638     albertel 3956:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3957: 			     $home);
1.481     raeburn  3958:     } else {
1.477     raeburn  3959:         my $fpath = '';
                   3960:         my $fname = $file;
1.478     albertel 3961:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3962:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3963:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3964:         if ($action eq 'copy') {
                   3965:             if ($source eq '') {
                   3966:                 $fetchresult = 'no source file';
                   3967:                 return $fetchresult;
                   3968:             } else {
                   3969:                 my $destination = $filepath.'/'.$fname;
                   3970:                 rename($source,$destination);
                   3971:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3972:                                  $home);
1.481     raeburn  3973:             }
                   3974:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3975:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3976:             print $fh $env{'form.'.$source};
1.481     raeburn  3977:             close($fh);
1.637     raeburn  3978:             if ($parser eq 'parse') {
1.1024    raeburn  3979:                 my $mm = new File::MMagic;
1.1095    raeburn  3980:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3981:                 if ($type eq 'text/html') {
1.1024    raeburn  3982:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3983:                     unless ($parse_result eq 'ok') {
                   3984:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3985:                     }
1.637     raeburn  3986:                 }
1.1095    raeburn  3987:                 if (ref($mimetype)) {
                   3988:                     $$mimetype = $type;
                   3989:                 } 
1.637     raeburn  3990:             }
1.477     raeburn  3991:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3992:                                  $home);
1.481     raeburn  3993:             if ($fetchresult eq 'ok') {
                   3994:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3995:             } else {
                   3996:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3997:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3998:                 return '/adm/notfound.html';
                   3999:             }
1.477     raeburn  4000:         }
                   4001:     }
1.485     raeburn  4002:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  4003:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 4004:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  4005:     }
                   4006:     return $fetchresult;
                   4007: }
                   4008: 
1.637     raeburn  4009: sub build_filepath {
                   4010:     my ($fpath) = @_;
                   4011:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   4012:     unless ($fpath eq '') {
                   4013:         my @parts=split('/',$fpath);
                   4014:         foreach my $part (@parts) {
                   4015:             $filepath.= '/'.$part;
                   4016:             if ((-e $filepath)!=1) {
                   4017:                 mkdir($filepath,0777);
                   4018:             }
                   4019:         }
                   4020:     }
                   4021:     return $filepath;
                   4022: }
                   4023: 
                   4024: sub store_edited_file {
1.638     albertel 4025:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  4026:     my $file = $primary_url;
                   4027:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   4028:     my $fpath = '';
                   4029:     my $fname = $file;
                   4030:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   4031:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   4032:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  4033:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  4034:     print $fh $content;
                   4035:     close($fh);
1.638     albertel 4036:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  4037:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4038: 			  $home);
1.637     raeburn  4039:     if ($$fetchresult eq 'ok') {
                   4040:         return '/uploaded/'.$fpath.'/'.$fname;
                   4041:     } else {
1.638     albertel 4042:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   4043: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  4044:         return '/adm/notfound.html';
                   4045:     }
                   4046: }
                   4047: 
1.531     albertel 4048: sub clean_filename {
1.831     albertel 4049:     my ($fname,$args)=@_;
1.315     www      4050: # Replace Windows backslashes by forward slashes
1.257     www      4051:     $fname=~s/\\/\//g;
1.831     albertel 4052:     if (!$args->{'keep_path'}) {
                   4053:         # Get rid of everything but the actual filename
                   4054: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   4055:     }
1.315     www      4056: # Replace spaces by underscores
                   4057:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  4058: # Transliterate non-ascii text to ascii
                   4059:     my $lang = &Apache::lonlocal::current_language();
                   4060:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      4061: # Replace all other weird characters by nothing
1.831     albertel 4062:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 4063: # Replace all .\d. sequences with _\d. so they no longer look like version
                   4064: # numbers
                   4065:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.140  raeburn  4066: # Replace three or more adjacent underscores with one for consistency
                   4067: # with loncfile::filename_check() so complete url can be extracted by
                   4068: # lonnet::decode_symb()
                   4069:     $fname=~s/_{3,}/_/g;
1.531     albertel 4070:     return $fname;
                   4071: }
1.1172.2.110  raeburn  4072: 
1.1051    raeburn  4073: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   4074: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   4075: # image with the same aspect ratio as the original, but with dimensions which do 
                   4076: # not exceed $resizewidth and $resizeheight.
                   4077:  
1.984     neumanie 4078: sub resizeImage {
1.1051    raeburn  4079:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   4080:     my $ima = Image::Magick->new;
                   4081:     my $resized;
                   4082:     if (-e $img_path) {
                   4083:         $ima->Read($img_path);
                   4084:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   4085:             my $width = $ima->Get('width');
                   4086:             my $height = $ima->Get('height');
                   4087:             if ($width > $resizewidth) {
                   4088: 	        my $factor = $width/$resizewidth;
                   4089:                 my $newheight = $height/$factor;
                   4090:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   4091:                 $resized = 1;
                   4092:             }
                   4093:         }
                   4094:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   4095:             my $width = $ima->Get('width');
                   4096:             my $height = $ima->Get('height');
                   4097:             if ($height > $resizeheight) {
                   4098:                 my $factor = $height/$resizeheight;
                   4099:                 my $newwidth = $width/$factor;
                   4100:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   4101:                 $resized = 1;
                   4102:             }
                   4103:         }
                   4104:         if ($resized) {
                   4105:             $ima->Write($img_path);
                   4106:         }
                   4107:     }
                   4108:     return;
1.977     amueller 4109: }
                   4110: 
1.608     albertel 4111: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 4112: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  4113: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  4114: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.146.  .13(raeb 4115:-23): #                                    canceloverwrite, scantron, toollogo or ''. 
1.1090    raeburn  4116: #                   if 'coursedoc': upload to the current course
                   4117: #                   if 'existingfile': write file to tmp/overwrites directory 
                   4118: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   4119: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 4120: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  4121: #        $parser - instruction to parse file for objects ($parser = parse) or
                   4122: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   4123: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   4124: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  4125: #        $allfiles - reference to hash for embedded objects
                   4126: #        $codebase - reference to hash for codebase of java objects
1.1172.2.146.  .13(raeb 4127:-23): #        $destuname - username for permanent storage of uploaded file
                   4128:-23): #        $destudom - domain for permanaent storage of uploaded file
1.860     raeburn  4129: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   4130: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  4131: #        $resizewidth - width (pixels) to which to resize uploaded image
                   4132: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  4133: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  4134: #                    from File::MMagic.
1.858     raeburn  4135: # 
1.686     albertel 4136: # output: url of file in userspace, or error: <message> 
                   4137: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 4138: 
1.531     albertel 4139: sub userfileupload {
1.1090    raeburn  4140:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  4141:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 4142:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 4143:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 4144:     $fname=&clean_filename($fname);
1.1090    raeburn  4145:     # See if there is anything left
1.257     www      4146:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  4147:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   4148:     if ($fname =~ /^\./) {
                   4149:         my ($s,$usec) = &gettimeofday();
                   4150:         while (length($usec) < 6) {
                   4151:             $usec = '0'.$usec;
                   4152:         }
                   4153:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   4154:     }
1.1090    raeburn  4155:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   4156:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   4157:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   4158:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  4159:         my $now = time;
1.1090    raeburn  4160:         my $filepath;
1.1095    raeburn  4161:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  4162:              $filepath = 'tmp/helprequests/'.$now;
                   4163:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   4164:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   4165:                          '_'.$env{'user.domain'}.'/pending';
                   4166:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   4167:             my ($docuname,$docudom);
1.1172.2.96  raeburn  4168:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  4169:                 $docudom = $destudom;
                   4170:             } else {
                   4171:                 $docudom = $env{'user.domain'};
                   4172:             }
1.1172.2.96  raeburn  4173:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  4174:                 $docuname = $destuname;
                   4175:             } else {
                   4176:                 $docuname = $env{'user.name'};
                   4177:             }
                   4178:             if (exists($env{'form.group'})) {
                   4179:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4180:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4181:             }
                   4182:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   4183:             if ($context eq 'canceloverwrite') {
                   4184:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   4185:                 if (-e  $tempfile) {
                   4186:                     my @info = stat($tempfile);
                   4187:                     if ($info[9] eq $env{'form.timestamp'}) {
                   4188:                         unlink($tempfile);
                   4189:                     }
                   4190:                 }
                   4191:                 return;
1.523     raeburn  4192:             }
                   4193:         }
1.1090    raeburn  4194:         # Create the directory if not present
1.741     raeburn  4195:         my @parts=split(/\//,$filepath);
                   4196:         my $fullpath = $perlvar{'lonDaemons'};
                   4197:         for (my $i=0;$i<@parts;$i++) {
                   4198:             $fullpath .= '/'.$parts[$i];
                   4199:             if ((-e $fullpath)!=1) {
                   4200:                 mkdir($fullpath,0777);
                   4201:             }
                   4202:         }
1.1172.2.96  raeburn  4203:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  4204:         print $fh $env{'form.'.$formname};
                   4205:         close($fh);
1.1090    raeburn  4206:         if ($context eq 'existingfile') {
                   4207:             my @info = stat($fullpath.'/'.$fname);
                   4208:             return ($fullpath.'/'.$fname,$info[9]);
                   4209:         } else {
                   4210:             return $fullpath.'/'.$fname;
                   4211:         }
1.523     raeburn  4212:     }
1.995     raeburn  4213:     if ($subdir eq 'scantron') {
                   4214:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4215:     } else {
1.995     raeburn  4216:         $fname="$subdir/$fname";
                   4217:     }
1.1090    raeburn  4218:     if ($context eq 'coursedoc') {
1.638     albertel 4219: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4220: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4221:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4222:             return &finishuserfileupload($docuname,$docudom,
                   4223: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4224: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4225:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4226:         } else {
1.1172.2.21  raeburn  4227:             if ($env{'form.folder'}) {
                   4228:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4229:             }
1.638     albertel 4230:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4231: 				       $fname,$formname,$parser,
1.1095    raeburn  4232: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4233:         }
1.719     banghart 4234:     } elsif (defined($destuname)) {
                   4235:         my $docuname=$destuname;
                   4236:         my $docudom=$destudom;
1.860     raeburn  4237: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4238: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4239:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4240:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4241:     } else {
1.638     albertel 4242:         my $docuname=$env{'user.name'};
                   4243:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  4244:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4245:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4246:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4247:         }
1.860     raeburn  4248: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4249: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4250:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4251:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4252:     }
1.271     www      4253: }
                   4254: 
                   4255: sub finishuserfileupload {
1.860     raeburn  4256:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4257:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4258:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4259:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4260:   
1.860     raeburn  4261:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4262:     $file=$fname;
                   4263:     if ($fname=~m|/|) {
                   4264:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4265: 	$path.=$fnamepath.'/';
                   4266:     }
1.259     www      4267:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4268:     my $count;
                   4269:     for ($count=4;$count<=$#parts;$count++) {
                   4270:         $filepath.="/$parts[$count]";
                   4271:         if ((-e $filepath)!=1) {
                   4272: 	    mkdir($filepath,0777);
                   4273:         }
                   4274:     }
1.984     neumanie 4275: 
1.258     www      4276: # Save the file
                   4277:     {
1.1172.2.96  raeburn  4278: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4279: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4280: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4281: 	    return '/adm/notfound.html';
                   4282: 	}
1.1090    raeburn  4283:         if ($context eq 'overwrite') {
1.1117    foxr     4284:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4285:             my $target = $filepath.'/'.$file;
                   4286:             if (-e $source) {
                   4287:                 my @info = stat($source);
                   4288:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4289:                     unless (&File::Copy::move($source,$target)) {
                   4290:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4291:                         return "Moving from $source failed";
                   4292:                     }
                   4293:                 } else {
                   4294:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4295:                 }
                   4296:             } else {
                   4297:                 return "Temporary file: $source missing";
                   4298:             }
                   4299:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4300: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4301: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4302: 	    return '/adm/notfound.html';
                   4303: 	}
1.570     albertel 4304: 	close(FH);
1.1051    raeburn  4305:         if ($resizewidth && $resizeheight) {
                   4306:             my $mm = new File::MMagic;
                   4307:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4308:             if ($mime_type =~ m{^image/}) {
                   4309: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4310:             }  
1.977     amueller 4311: 	}
1.258     www      4312:     }
1.1152    raeburn  4313:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4314:         if (ref($mimetype)) {
                   4315:             if ($$mimetype eq '') {
                   4316:                 my $mm = new File::MMagic;
                   4317:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4318:                 $$mimetype = $type;
                   4319:             }
                   4320:         }
                   4321:     }
1.1172.2.109  raeburn  4322:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4323:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4324:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4325:                                                        $allfiles,$codebase);
                   4326:             unless ($parse_result eq 'ok') {
                   4327:                 &logthis('Failed to parse '.$filepath.$file.
                   4328: 	   	         ' for embedded media: '.$parse_result); 
                   4329:             }
1.637     raeburn  4330:         }
1.1172.2.109  raeburn  4331:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4332:         my $format = $env{'form.scantron_format'};
                   4333:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4334:     }
1.860     raeburn  4335:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4336:         my $input = $filepath.'/'.$file;
                   4337:         my $output = $filepath.'/'.'tn-'.$file;
1.1172.2.146.  .13(raeb 4338:-23):         my $makethumb;
1.860     raeburn  4339:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.146.  .13(raeb 4340:-23):         if ($context eq 'toollogo') {
                   4341:-23):             my ($fullwidth,$fullheight) = &check_dimensions($input);
                   4342:-23):             if ($fullwidth ne '' && $fullheight ne '') {
                   4343:-23):                 if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
                   4344:-23):                     $makethumb = 1;
                   4345:-23):                 }
                   4346:-23):             }
                   4347:-23):         } else {
                   4348:-23):             $makethumb = 1;
                   4349:-23):         }
                   4350:-23):         if ($makethumb) {
                   4351:-23):             my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4352:-23):             system({$args[0]} @args);
                   4353:-23):             if (-e $filepath.'/'.'tn-'.$file) {
                   4354:-23):                 $fetchthumb  = 1;
                   4355:-23):             }
1.860     raeburn  4356:         }
                   4357:     }
1.858     raeburn  4358:  
1.259     www      4359: # Notify homeserver to grep it
                   4360: #
1.984     neumanie 4361:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4362:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4363:     if ($fetchresult eq 'ok') {
1.860     raeburn  4364:         if ($fetchthumb) {
                   4365:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4366:             if ($thumbresult ne 'ok') {
                   4367:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4368:                          $docuhome.': '.$thumbresult);
                   4369:             }
                   4370:         }
1.259     www      4371: #
1.258     www      4372: # Return the URL to it
1.494     albertel 4373:         return '/uploaded/'.$path.$file;
1.263     www      4374:     } else {
1.494     albertel 4375:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4376: 		 ': '.$fetchresult);
1.263     www      4377:         return '/adm/notfound.html';
1.858     raeburn  4378:     }
1.493     albertel 4379: }
                   4380: 
1.637     raeburn  4381: sub extract_embedded_items {
1.961     raeburn  4382:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4383:     my @state = ();
1.1164    raeburn  4384:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4385:     my %javafiles = (
                   4386:                       codebase => '',
                   4387:                       code => '',
                   4388:                       archive => ''
                   4389:                     );
                   4390:     my %mediafiles = (
                   4391:                       src => '',
                   4392:                       movie => '',
                   4393:                      );
1.648     raeburn  4394:     my $p;
                   4395:     if ($content) {
                   4396:         $p = HTML::LCParser->new($content);
                   4397:     } else {
1.961     raeburn  4398:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4399:     }
1.641     albertel 4400:     while (my $t=$p->get_token()) {
1.640     albertel 4401: 	if ($t->[0] eq 'S') {
                   4402: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4403: 	    push(@state, $tagname);
1.648     raeburn  4404:             if (lc($tagname) eq 'allow') {
                   4405:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4406:             }
1.640     albertel 4407: 	    if (lc($tagname) eq 'img') {
                   4408: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4409: 	    }
1.886     albertel 4410: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4411:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4412: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4413:                 }
1.886     albertel 4414: 	    }
1.645     raeburn  4415:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4416:                 my $src;
1.645     raeburn  4417:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4418:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4419:                 } else {
1.1164    raeburn  4420:                     if ($attr->{'src'} ne '') {
                   4421:                         $src = $attr->{'src'};
                   4422:                         &add_filetype($allfiles,$src,'src');
                   4423:                     }
                   4424:                 }
                   4425:                 my $text = $p->get_trimmed_text();
                   4426:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4427:                     my @swfargs = split(/,/,$1);
                   4428:                     foreach my $item (@swfargs) {
                   4429:                         $item =~ s/["']//g;
                   4430:                         $item =~ s/^\s+//;
                   4431:                         $item =~ s/\s+$//;
                   4432:                     }
                   4433:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4434:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4435:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4436:                         } else {
                   4437:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4438:                         }
                   4439:                     }
1.645     raeburn  4440:                 }
                   4441:             }
                   4442:             if (lc($tagname) eq 'link') {
                   4443:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4444:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4445:                 }
                   4446:             }
1.640     albertel 4447: 	    if (lc($tagname) eq 'object' ||
                   4448: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4449: 		foreach my $item (keys(%javafiles)) {
                   4450: 		    $javafiles{$item} = '';
                   4451: 		}
1.1164    raeburn  4452:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4453:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4454:                 }
1.640     albertel 4455: 	    }
                   4456: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4457: 		my $name = lc($attr->{'name'});
                   4458: 		foreach my $item (keys(%javafiles)) {
                   4459: 		    if ($name eq $item) {
                   4460: 			$javafiles{$item} = $attr->{'value'};
                   4461: 			last;
                   4462: 		    }
                   4463: 		}
1.1164    raeburn  4464:                 my $pathfrom;
1.640     albertel 4465: 		foreach my $item (keys(%mediafiles)) {
                   4466: 		    if ($name eq $item) {
1.1164    raeburn  4467:                         $pathfrom = $attr->{'value'};
                   4468:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4469: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4470: 			last;
                   4471: 		    }
                   4472: 		}
1.1164    raeburn  4473:                 if ($name eq 'flashvars') {
                   4474:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4475:                 }
                   4476:                 if ($pathfrom ne '') {
                   4477:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4478:                                          $pathfrom);
                   4479:                 }
1.640     albertel 4480: 	    }
                   4481: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4482: 		foreach my $item (keys(%javafiles)) {
                   4483: 		    if ($attr->{$item}) {
                   4484: 			$javafiles{$item} = $attr->{$item};
                   4485: 			last;
                   4486: 		    }
                   4487: 		}
                   4488: 		foreach my $item (keys(%mediafiles)) {
                   4489: 		    if ($attr->{$item}) {
                   4490: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4491: 			last;
                   4492: 		    }
                   4493: 		}
1.1164    raeburn  4494:                 if (lc($tagname) eq 'embed') {
                   4495:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4496:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4497:                                              $attr->{'src'});
                   4498:                     }
                   4499:                 }
1.640     albertel 4500: 	    }
1.1172.2.35  raeburn  4501:             if (lc($tagname) eq 'iframe') {
                   4502:                 my $src = $attr->{'src'} ;
                   4503:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4504:                     &add_filetype($allfiles,$src,'src');
                   4505:                 } elsif ($src =~ m{^/}) {
                   4506:                     if ($env{'request.course.id'}) {
                   4507:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4508:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4509:                         my $url = &hreflocation('',$fullpath);
                   4510:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4511:                             my $relpath = $1;
                   4512:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4513:                                 &add_filetype($allfiles,$1,'src');
                   4514:                             }
                   4515:                         }
                   4516:                     }
                   4517:                 }
                   4518:             }
1.1164    raeburn  4519:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4520:                 pop(@state);
1.1164    raeburn  4521:             }
1.640     albertel 4522: 	} elsif ($t->[0] eq 'E') {
                   4523: 	    my ($tagname) = ($t->[1]);
                   4524: 	    if ($javafiles{'codebase'} ne '') {
                   4525: 		$javafiles{'codebase'} .= '/';
                   4526: 	    }  
                   4527: 	    if (lc($tagname) eq 'applet' ||
                   4528: 		lc($tagname) eq 'object' ||
                   4529: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4530: 		) {
                   4531: 		foreach my $item (keys(%javafiles)) {
                   4532: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4533: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4534: 			&add_filetype($allfiles,$file,$item);
                   4535: 		    }
                   4536: 		}
                   4537: 	    } 
                   4538: 	    pop @state;
                   4539: 	}
                   4540:     }
1.1164    raeburn  4541:     foreach my $id (sort(keys(%flashvars))) {
                   4542:         if ($shockwave{$id} ne '') {
                   4543:             my @pairs = split(/\&/,$flashvars{$id});
                   4544:             foreach my $pair (@pairs) {
                   4545:                 my ($key,$value) = split(/\=/,$pair);
                   4546:                 if ($key eq 'thumb') {
                   4547:                     &add_filetype($allfiles,$value,$key);
                   4548:                 } elsif ($key eq 'content') {
                   4549:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4550:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4551:                     if ($ext ne '') {
                   4552:                         &add_filetype($allfiles,$path.$value,$ext);
                   4553:                     }
                   4554:                 }
                   4555:             }
                   4556:         }
                   4557:     }
1.637     raeburn  4558:     return 'ok';
                   4559: }
                   4560: 
1.639     albertel 4561: sub add_filetype {
                   4562:     my ($allfiles,$file,$type)=@_;
                   4563:     if (exists($allfiles->{$file})) {
                   4564: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4565: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4566: 	}
                   4567:     } else {
                   4568: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4569:     }
                   4570: }
                   4571: 
1.1164    raeburn  4572: sub embedded_dependency {
                   4573:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4574:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4575:         if (($identifier ne '') &&
                   4576:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4577:             ($pathfrom ne '')) {
                   4578:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4579:             foreach my $dep (@{$related->{$identifier}}) {
                   4580:                 &add_filetype($allfiles,$path.$dep,'object');
                   4581:             }
                   4582:         }
                   4583:     }
                   4584:     return;
                   4585: }
                   4586: 
1.1172.2.146.  .13(raeb 4587:-23): sub check_dimensions {
                   4588:-23):     my ($inputfile) = @_;
                   4589:-23):     my ($fullwidth,$fullheight);
                   4590:-23):     if (($inputfile =~ m|^[/\w.\-]+$|) && (-e $inputfile)) {
                   4591:-23):         my $mm = new File::MMagic;
                   4592:-23):         my $mime_type = $mm->checktype_filename($inputfile);
                   4593:-23):         if ($mime_type =~ m{^image/}) {
                   4594:-23):             if (open(PIPE,"identify $inputfile 2>&1 |")) {
                   4595:-23):                 my $imageinfo = <PIPE>;
                   4596:-23):                 if (!close(PIPE)) {
                   4597:-23):                     &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
                   4598:-23):                 }
                   4599:-23):                 chomp($imageinfo);
                   4600:-23):                 my ($fullsize) =
                   4601:-23):                     ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
                   4602:-23):                 if ($fullsize) {
                   4603:-23):                     ($fullwidth,$fullheight) = split(/x/,$fullsize);
                   4604:-23):                 }
                   4605:-23):             }
                   4606:-23):         }
                   4607:-23):     }
                   4608:-23):     return ($fullwidth,$fullheight);
                   4609:-23): }
                   4610:-23): 
1.1172.2.109  raeburn  4611: sub bubblesheet_converter {
                   4612:     my ($cdom,$fullpath,$config,$format) = @_;
                   4613:     if ((&domain($cdom) ne '') &&
                   4614:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4615:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4616:         my (%csvcols,%csvoptions);
                   4617:         if (ref($config->{'fields'}) eq 'HASH') {
                   4618:             %csvcols = %{$config->{'fields'}};
                   4619:         }
                   4620:         if (ref($config->{'options'}) eq 'HASH') {
                   4621:             %csvoptions = %{$config->{'options'}};
                   4622:         }
                   4623:         my %csvbynum = reverse(%csvcols);
                   4624:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4625:         if (keys(%scantronconf)) {
                   4626:             my %bynum = (
                   4627:                           $scantronconf{CODEstart} => 'CODEstart',
                   4628:                           $scantronconf{IDstart}   => 'IDstart',
                   4629:                           $scantronconf{PaperID}   => 'PaperID',
                   4630:                           $scantronconf{FirstName} => 'FirstName',
                   4631:                           $scantronconf{LastName}  => 'LastName',
                   4632:                           $scantronconf{Qstart}    => 'Qstart',
                   4633:                         );
                   4634:             my @ordered;
                   4635:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4636:                 push(@ordered,$bynum{$item});
                   4637:             }
                   4638:             my %mapstart = (
                   4639:                               CODEstart => 'CODE',
                   4640:                               IDstart   => 'ID',
                   4641:                               PaperID   => 'PaperID',
                   4642:                               FirstName => 'FirstName',
                   4643:                               LastName  => 'LastName',
                   4644:                               Qstart    => 'FirstQuestion',
                   4645:                            );
                   4646:             my %maplength = (
                   4647:                               CODEstart => 'CODElength',
                   4648:                               IDstart   => 'IDlength',
                   4649:                               PaperID   => 'PaperIDlength',
                   4650:                               FirstName => 'FirstNamelength',
                   4651:                               LastName  => 'LastNamelength',
                   4652:             );
                   4653:             if (open(my $fh,'<',$fullpath)) {
                   4654:                 my $output;
                   4655:                 my %lettdig = &letter_to_digits();
                   4656:                 my %diglett = reverse(%lettdig);
                   4657:                 my $numletts = scalar(keys(%lettdig));
                   4658:                 my $num = 0;
                   4659:                 while (my $line=<$fh>) {
                   4660:                     $num ++;
                   4661:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4662:                     $line =~ s{[\r\n]+$}{};
                   4663:                     my %found;
1.1172.2.143  raeburn  4664:                     my @values = split(/,/,$line,-1);
1.1172.2.109  raeburn  4665:                     my ($qstart,$record);
                   4666:                     for (my $i=0; $i<@values; $i++) {
                   4667:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4668:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4669:                             if ($values[$i] eq '') {
                   4670:                                 $values[$i] = $scantronconf{'Qoff'};
                   4671:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4672:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4673:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4674:                                 }
                   4675:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4676:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4677:                                     $values[$i] = $diglett{$values[$i]};
                   4678:                                 }
                   4679:                             } else {
                   4680:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4681:                                     my $digit;
                   4682:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4683:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4684:                                         if ($values[$i] eq 'J') {
                   4685:                                             $digit += $numletts;
                   4686:                                         }
                   4687:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4688:                                         $digit = $values[$i]-1;
                   4689:                                         if ($values[$i] eq '0') {
                   4690:                                             $digit += $numletts;
                   4691:                                         }
                   4692:                                     }
                   4693:                                     my $qval='';
                   4694:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4695:                                         if ($j == $digit) {
                   4696:                                             $qval .= $scantronconf{'Qon'};
                   4697:                                         } else {
                   4698:                                             $qval .= $scantronconf{'Qoff'};
                   4699:                                         }
                   4700:                                     }
                   4701:                                     $values[$i] = $qval;
                   4702:                                 }
                   4703:                             }
                   4704:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4705:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4706:                             }
                   4707:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4708:                             if ($numblank > 0) {
                   4709:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4710:                             }
                   4711:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4712:                                 $qstart = $i;
                   4713:                                 $found{$csvbynum{$i}} = $values[$i];
                   4714:                             } else {
                   4715:                                 $found{'FirstQuestion'} .= $values[$i];
                   4716:                             }
                   4717:                         } elsif (exists($csvbynum{$i})) {
                   4718:                             if ($csvoptions{'rem'}) {
                   4719:                                 $values[$i] =~ s/^\s+//;
                   4720:                             }
                   4721:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4722:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4723:                                     $values[$i] = '0'.$values[$i];
                   4724:                                 }
                   4725:                             }
                   4726:                             $found{$csvbynum{$i}} = $values[$i];
                   4727:                         }
                   4728:                     }
                   4729:                     foreach my $item (@ordered) {
                   4730:                         my $currlength = 1+length($record);
                   4731:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4732:                         if ($numspaces > 0) {
                   4733:                             $record .= (' ' x $numspaces);
                   4734:                         }
                   4735:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4736:                             unless ($item eq 'Qstart') {
                   4737:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4738:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4739:                                 }
                   4740:                             }
                   4741:                             $record .= $found{$mapstart{$item}};
                   4742:                         }
                   4743:                     }
                   4744:                     $output .= "$record\n";
                   4745:                 }
                   4746:                 close($fh);
                   4747:                 if ($output) {
                   4748:                     if (open(my $fh,'>',$fullpath)) {
                   4749:                         print $fh $output;
                   4750:                         close($fh);
                   4751:                     }
                   4752:                 }
                   4753:             }
                   4754:         }
                   4755:         return;
                   4756:     }
                   4757: }
                   4758: 
                   4759: sub letter_to_digits {
                   4760:     my %lettdig = (
                   4761:                     A => 1,
                   4762:                     B => 2,
                   4763:                     C => 3,
                   4764:                     D => 4,
                   4765:                     E => 5,
                   4766:                     F => 6,
                   4767:                     G => 7,
                   4768:                     H => 8,
                   4769:                     I => 9,
                   4770:                     J => 0,
                   4771:                   );
                   4772:     return %lettdig;
                   4773: }
                   4774: 
                   4775: sub get_scantron_config {
                   4776:     my ($which,$cdom) = @_;
                   4777:     my @lines = &get_scantronformat_file($cdom);
                   4778:     my %config;
                   4779:     #FIXME probably should move to XML it has already gotten a bit much now
                   4780:     foreach my $line (@lines) {
                   4781:         my ($name,$descrip)=split(/:/,$line);
                   4782:         if ($name ne $which ) { next; }
                   4783:         chomp($line);
                   4784:         my @config=split(/:/,$line);
                   4785:         $config{'name'}=$config[0];
                   4786:         $config{'description'}=$config[1];
                   4787:         $config{'CODElocation'}=$config[2];
                   4788:         $config{'CODEstart'}=$config[3];
                   4789:         $config{'CODElength'}=$config[4];
                   4790:         $config{'IDstart'}=$config[5];
                   4791:         $config{'IDlength'}=$config[6];
                   4792:         $config{'Qstart'}=$config[7];
                   4793:         $config{'Qlength'}=$config[8];
                   4794:         $config{'Qoff'}=$config[9];
                   4795:         $config{'Qon'}=$config[10];
                   4796:         $config{'PaperID'}=$config[11];
                   4797:         $config{'PaperIDlength'}=$config[12];
                   4798:         $config{'FirstName'}=$config[13];
                   4799:         $config{'FirstNamelength'}=$config[14];
                   4800:         $config{'LastName'}=$config[15];
                   4801:         $config{'LastNamelength'}=$config[16];
                   4802:         $config{'BubblesPerRow'}=$config[17];
                   4803:         last;
                   4804:     }
                   4805:     return %config;
                   4806: }
                   4807: 
                   4808: sub get_scantronformat_file {
                   4809:     my ($cdom) = @_;
                   4810:     if ($cdom eq '') {
                   4811:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4812:     }
                   4813:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4814:     my $gottab = 0;
                   4815:     my @lines;
                   4816:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4817:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4818:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4819:             if ($formatfile ne '-1') {
                   4820:                 @lines = split("\n",$formatfile,-1);
                   4821:                 $gottab = 1;
                   4822:             }
                   4823:         }
                   4824:     }
                   4825:     if (!$gottab) {
                   4826:         my $confname = $cdom.'-domainconfig';
                   4827:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4828:         my $formatfile = &getfile($default);
                   4829:         if ($formatfile ne '-1') {
                   4830:             @lines = split("\n",$formatfile,-1);
                   4831:             $gottab = 1;
                   4832:         }
                   4833:     }
                   4834:     if (!$gottab) {
                   4835:         my @domains = &current_machine_domains();
                   4836:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4837:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4838:                 @lines = <$fh>;
                   4839:                 close($fh);
                   4840:             }
                   4841:         } else {
                   4842:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4843:                 @lines = <$fh>;
                   4844:                 close($fh);
                   4845:             }
                   4846:         }
1.1172.2.146.  .8(raebu 4847:23):         chomp(@lines);
1.1172.2.109  raeburn  4848:     }
                   4849:     return @lines;
                   4850: }
                   4851: 
1.493     albertel 4852: sub removeuploadedurl {
1.984     neumanie 4853:     my ($url)=@_;	
                   4854:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4855:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4856: }
                   4857: 
                   4858: sub removeuserfile {
                   4859:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4860:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4861:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4862:     if ($result eq 'ok') {	
1.798     raeburn  4863:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4864:             my $metafile = $fname.'.meta';
                   4865:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4866: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4867:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4868:             my $sqlresult = 
1.823     albertel 4869:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4870:                                         'portfolio_metadata',$group,
                   4871:                                         'delete');
1.798     raeburn  4872:         }
                   4873:     }
                   4874:     return $result;
1.257     www      4875: }
1.15      www      4876: 
1.530     albertel 4877: sub mkdiruserfile {
                   4878:     my ($docuname,$docudom,$dir)=@_;
                   4879:     my $home=&homeserver($docuname,$docudom);
                   4880:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4881: }
                   4882: 
1.531     albertel 4883: sub renameuserfile {
                   4884:     my ($docuname,$docudom,$old,$new)=@_;
                   4885:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4886:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4887:                         &escape("$old").':'.&escape("$new"),$home);
                   4888:     if ($result eq 'ok') {
                   4889:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4890:             my $oldmeta = $old.'.meta';
                   4891:             my $newmeta = $new.'.meta';
                   4892:             my $metaresult = 
                   4893:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4894: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4895:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4896:             my $sqlresult = 
1.823     albertel 4897:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4898:                                         'portfolio_metadata',$group,
                   4899:                                         'delete');
1.798     raeburn  4900:         }
                   4901:     }
                   4902:     return $result;
1.531     albertel 4903: }
                   4904: 
1.14      www      4905: # ------------------------------------------------------------------------- Log
                   4906: 
                   4907: sub log {
                   4908:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4909:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4910: }
                   4911: 
                   4912: # ------------------------------------------------------------------ Course Log
1.352     www      4913: #
                   4914: # This routine flushes several buffers of non-mission-critical nature
                   4915: #
1.157     www      4916: 
                   4917: sub flushcourselogs {
1.352     www      4918:     &logthis('Flushing log buffers');
                   4919: #
                   4920: # course logs
                   4921: # This is a log of all transactions in a course, which can be used
                   4922: # for data mining purposes
                   4923: #
                   4924: # It also collects the courseid database, which lists last transaction
                   4925: # times and course titles for all courseids
                   4926: #
                   4927:     my %courseidbuffer=();
1.921     raeburn  4928:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4929:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4930: 		          &escape($courselogs{$crsid}),
                   4931: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4932: 	    delete $courselogs{$crsid};
                   4933:         } else {
                   4934:             &logthis('Failed to flush log buffer for '.$crsid);
                   4935:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4936:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4937:                         " exceeded maximum size, deleting.</font>");
                   4938:                delete $courselogs{$crsid};
                   4939:             }
1.352     www      4940:         }
1.920     raeburn  4941:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4942:             'description' => $coursedescrbuf{$crsid},
                   4943:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4944:             'type'        => $coursetypebuf{$crsid},
                   4945:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4946:         };
1.191     harris41 4947:     }
1.352     www      4948: #
                   4949: # Write course id database (reverse lookup) to homeserver of courses 
                   4950: # Is used in pickcourse
                   4951: #
1.840     albertel 4952:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4953:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4954:                                     $courseidbuffer{$crs_home},
                   4955:                                     $crs_home,'timeonly');
1.352     www      4956:     }
                   4957: #
                   4958: # File accesses
                   4959: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4960: #
1.449     matthew  4961:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4962:         if ($entry =~ /___count$/) {
                   4963:             my ($dom,$name);
1.807     albertel 4964:             ($dom,$name,undef)=
1.811     albertel 4965: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4966:             if (! defined($dom) || $dom eq '' || 
                   4967:                 ! defined($name) || $name eq '') {
1.620     albertel 4968:                 my $cid = $env{'request.course.id'};
1.1172.2.142  raeburn  4969: #
                   4970: # FIXME 11/29/2021
                   4971: # Typo in rev. 1.458 (2003/12/09)??
                   4972: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
                   4973: #
1.1172.2.146.  .13(raeb 4974:-23): # While these remain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
1.1172.2.142  raeburn  4975: # $dom and $name will always be null, so the &inc() call will default to storing this data
                   4976: # in a nohist_accesscount.db file for the user rather than the course.
                   4977: #
                   4978: # That said there is a lot of noise in the data being stored.
                   4979: # So counts for prtspool/  and adm/ etc. are recorded.
                   4980: #
                   4981: # A review of which items ending '___count' are written to %accesshash should likely be
                   4982: # made before deciding whether to set these to 'course.' instead of 'request.'
                   4983: #
                   4984: # Under the current scheme each user receives a nohist_accesscount.db file listing
                   4985: # accesses for things which are not published resources, regardless of course, and
                   4986: # there is not a nohist_accesscount.db file in a course, which might log accesses from
                   4987: # anyone in the course for things which are not published resources.
                   4988: #
                   4989: # For an author, nohist_accesscount.db ends up having records for other items
                   4990: # mixed up with the legitimate access counts for the author's published resources.
                   4991: #
1.620     albertel 4992:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4993:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4994:             }
1.450     matthew  4995:             my $value = $accesshash{$entry};
                   4996:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4997:             my %temphash=($url => $value);
1.449     matthew  4998:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4999:             if ($result eq 'ok') {
                   5000:                 delete $accesshash{$entry};
                   5001:             }
                   5002:         } else {
1.811     albertel 5003:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      5004:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  5005:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  5006:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   5007:                 delete $accesshash{$entry};
                   5008:             }
1.185     www      5009:         }
1.191     harris41 5010:     }
1.352     www      5011: #
                   5012: # Roles
                   5013: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   5014: #
1.800     albertel 5015:     foreach my $entry (keys(%userrolehash)) {
1.351     www      5016:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      5017: 	    split(/\:/,$entry);
                   5018:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      5019:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      5020:                 $rudom,$runame) eq 'ok') {
                   5021: 	    delete $userrolehash{$entry};
                   5022:         }
                   5023:     }
1.662     raeburn  5024: #
1.1172.2.90  raeburn  5025: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  5026: #
                   5027:     my %domrolebuffer = ();
1.1000    raeburn  5028:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 5029:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  5030:         if ($domrolebuffer{$rudom}) {
                   5031:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   5032:                       '='.&escape($domainrolehash{$entry});
                   5033:         } else {
                   5034:             $domrolebuffer{$rudom}.=&escape($entry).
                   5035:                       '='.&escape($domainrolehash{$entry});
                   5036:         }
                   5037:         delete $domainrolehash{$entry};
                   5038:     }
                   5039:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  5040:         my %servers;
                   5041:         if (defined(&domain($dom,'primary'))) {
                   5042:             my $primary=&domain($dom,'primary');
                   5043:             my $hostname=&hostname($primary);
                   5044:             $servers{$primary} = $hostname;
                   5045:         } else {
                   5046:             %servers = &get_servers($dom,'library');
                   5047:         }
1.841     albertel 5048: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  5049: 	    if (&reply('domroleput:'.$dom.':'.
                   5050: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   5051: 	        last;
                   5052: 	    } else {
1.841     albertel 5053: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   5054: 	    }
1.662     raeburn  5055:         }
                   5056:     }
1.186     www      5057:     $dumpcount++;
1.157     www      5058: }
                   5059: 
                   5060: sub courselog {
                   5061:     my $what=shift;
1.158     www      5062:     $what=time.':'.$what;
1.620     albertel 5063:     unless ($env{'request.course.id'}) { return ''; }
                   5064:     $coursedombuf{$env{'request.course.id'}}=
                   5065:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5066:     $coursenumbuf{$env{'request.course.id'}}=
                   5067:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   5068:     $coursehombuf{$env{'request.course.id'}}=
                   5069:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   5070:     $coursedescrbuf{$env{'request.course.id'}}=
                   5071:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   5072:     $courseinstcodebuf{$env{'request.course.id'}}=
                   5073:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   5074:     $courseownerbuf{$env{'request.course.id'}}=
                   5075:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  5076:     $coursetypebuf{$env{'request.course.id'}}=
                   5077:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 5078:     if (defined $courselogs{$env{'request.course.id'}}) {
                   5079: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      5080:     } else {
1.620     albertel 5081: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      5082:     }
1.620     albertel 5083:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      5084: 	&flushcourselogs();
                   5085:     }
1.158     www      5086: }
                   5087: 
                   5088: sub courseacclog {
                   5089:     my $fnsymb=shift;
1.620     albertel 5090:     unless ($env{'request.course.id'}) { return ''; }
                   5091:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      5092:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      5093:         $what.=':POST';
1.583     matthew  5094:         # FIXME: Probably ought to escape things....
1.800     albertel 5095: 	foreach my $key (keys(%env)) {
                   5096:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  5097:                 my $formitem = $1;
                   5098:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   5099:                     $what.=':'.$formitem.'='.$env{$key};
                   5100:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131  raeburn  5101:                     if ($formitem eq 'proctorpassword') {
1.1172.2.132  raeburn  5102:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131  raeburn  5103:                     } else {
                   5104:                         $what.=':'.$formitem.'='.$env{$key};
                   5105:                     }
1.975     raeburn  5106:                 }
1.158     www      5107:             }
1.191     harris41 5108:         }
1.583     matthew  5109:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   5110:         # FIXME: We should not be depending on a form parameter that someone
                   5111:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 5112:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  5113:             $what.= ':POST';
                   5114:             # FIXME: Probably ought to escape things....
                   5115:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   5116:                                  'crsdiscuss') {
1.620     albertel 5117:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  5118:             }
                   5119:         }
1.158     www      5120:     }
                   5121:     &courselog($what);
1.149     www      5122: }
                   5123: 
1.185     www      5124: sub countacc {
                   5125:     my $url=&declutter(shift);
1.458     matthew  5126:     return if (! defined($url) || $url eq '');
1.620     albertel 5127:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      5128: #
                   5129: # Mark that this url was used in this course
                   5130: #
1.620     albertel 5131:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      5132: #
                   5133: # Increase the access count for this resource in this child process
                   5134: #
1.281     www      5135:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  5136:     $accesshash{$key}++;
1.185     www      5137: }
1.349     www      5138: 
1.361     www      5139: sub linklog {
                   5140:     my ($from,$to)=@_;
                   5141:     $from=&declutter($from);
                   5142:     $to=&declutter($to);
                   5143:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   5144:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   5145: }
1.1160    www      5146: 
                   5147: sub statslog {
                   5148:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   5149:     if ($users<2) { return; }
                   5150:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   5151:             'course'       => $env{'request.course.id'},
                   5152:             'sections'     => '"all"',
                   5153:             'num_students' => $users,
                   5154:             'part'         => $part,
                   5155:             'symb'         => $symb,
                   5156:             'mean_tries'   => $av_attempts,
                   5157:             'deg_of_diff'  => $degdiff});
                   5158:     foreach my $key (keys(%dynstore)) {
                   5159:         $accesshash{$key}=$dynstore{$key};
                   5160:     }
                   5161: }
1.361     www      5162:   
1.349     www      5163: sub userrolelog {
                   5164:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 5165:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      5166:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5167:        $userrolehash
                   5168:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      5169:                     =$tend.':'.$tstart;
1.662     raeburn  5170:     }
1.1169    droeschl 5171:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 5172:        $userrolehash
                   5173:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   5174:                     =$tend.':'.$tstart;
                   5175:     }
1.1172.2.90  raeburn  5176:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  5177:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5178:        $domainrolehash
                   5179:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   5180:                     = $tend.':'.$tstart;
                   5181:     }
1.351     www      5182: }
                   5183: 
1.957     raeburn  5184: sub courserolelog {
                   5185:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  5186:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   5187:         my $cdom = $1;
                   5188:         my $cnum = $2;
                   5189:         my $sec = $3;
                   5190:         my $namespace = 'rolelog';
                   5191:         my %storehash = (
                   5192:                            role    => $trole,
                   5193:                            start   => $tstart,
                   5194:                            end     => $tend,
                   5195:                            selfenroll => $selfenroll,
                   5196:                            context    => $context,
                   5197:                         );
                   5198:         if ($trole eq 'gr') {
                   5199:             $namespace = 'groupslog';
                   5200:             $storehash{'group'} = $sec;
                   5201:         } else {
                   5202:             $storehash{'section'} = $sec;
1.1172.2.146.  .16(raeb 5203:-23):             my ($curruserdomstr,$newuserdomstr);
                   5204:-23):             if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'})) {
                   5205:-23):                 $curruserdomstr = $env{'course.'.$env{'request.course.id'}.'.internal.userdomains'};
                   5206:-23):             } else {
                   5207:-23):                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
                   5208:-23):                 $curruserdomstr = $courseinfo{'internal.userdomains'};
                   5209:-23):             }
                   5210:-23):             if ($curruserdomstr ne '') {
                   5211:-23):                 my @udoms = split(/,/,$curruserdomstr);
                   5212:-23):                 unless (grep(/^\Q$domain\E/,@udoms)) {
                   5213:-23):                     push(@udoms,$domain);
                   5214:-23):                     $newuserdomstr = join(',',sort(@udoms));
                   5215:-23):                 }
                   5216:-23):             } else {
                   5217:-23):                 $newuserdomstr = $domain;
                   5218:-23):             }
                   5219:-23):             if ($newuserdomstr ne '') {
                   5220:-23):                 my $putresult = &put('environment',{ 'internal.userdomains' => $newuserdomstr },
                   5221:-23):                                      $cdom,$cnum);
                   5222:-23):                 if ($putresult eq 'ok') {
                   5223:-23):                     unless (($selfenroll) || ($context eq 'selfenroll')) {
                   5224:-23):                         if (($context eq 'createcourse') || ($context eq 'requestcourses') ||
                   5225:-23):                             ($context eq 'automated') || ($context eq 'domain')) {
                   5226:-23):                             $env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'} = $newuserdomstr;
                   5227:-23):                         } elsif ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   5228:-23):                             &appenv({'course.'.$cdom.'_'.$cnum.'.internal.userdomains' => $newuserdomstr});
                   5229:-23):                         }
                   5230:-23):                     }
                   5231:-23):                 }
                   5232:-23):             }
1.1172.2.9  raeburn  5233:         }
                   5234:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   5235:                    $domain,$cnum,$cdom);
                   5236:         if (($trole ne 'st') || ($sec ne '')) {
                   5237:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  5238:         }
                   5239:     }
                   5240:     return;
                   5241: }
                   5242: 
1.1172.2.9  raeburn  5243: sub domainrolelog {
                   5244:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5245:     if ($area =~ m{^/($match_domain)/$}) {
                   5246:         my $cdom = $1;
                   5247:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   5248:         my $namespace = 'rolelog';
                   5249:         my %storehash = (
                   5250:                            role    => $trole,
                   5251:                            start   => $tstart,
                   5252:                            end     => $tend,
                   5253:                            context => $context,
                   5254:                         );
                   5255:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5256:                    $domain,$domconfiguser,$cdom);
                   5257:     }
                   5258:     return;
                   5259: 
                   5260: }
                   5261: 
                   5262: sub coauthorrolelog {
                   5263:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5264:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5265:         my $audom = $1;
                   5266:         my $auname = $2;
                   5267:         my $namespace = 'rolelog';
                   5268:         my %storehash = (
                   5269:                            role    => $trole,
                   5270:                            start   => $tstart,
                   5271:                            end     => $tend,
                   5272:                            context => $context,
                   5273:                         );
                   5274:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5275:                    $domain,$auname,$audom);
                   5276:     }
                   5277:     return;
                   5278: }
                   5279: 
1.351     www      5280: sub get_course_adv_roles {
1.948     raeburn  5281:     my ($cid,$codes) = @_;
1.620     albertel 5282:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5283:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5284:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5285:     my %nothide=();
1.800     albertel 5286:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5287:         if ($user !~ /:/) {
                   5288: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5289:         } else {
                   5290:             $nothide{$user}=1;
                   5291:         }
1.470     www      5292:     }
1.1172.2.23  raeburn  5293:     my @possdoms = ($coursehash{'domain'});
                   5294:     if ($coursehash{'checkforpriv'}) {
                   5295:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5296:     }
1.351     www      5297:     my %returnhash=();
                   5298:     my %dumphash=
                   5299:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5300:     my $now=time;
1.997     raeburn  5301:     my %privileged;
1.1000    raeburn  5302:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5303: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5304:         if (($tstart) && ($tstart<0)) { next; }
                   5305:         if (($tend) && ($tend<$now)) { next; }
                   5306:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5307:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5308: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  5309:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5310:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5311: 	if ($role eq 'cr') { next; }
1.948     raeburn  5312:         if ($codes) {
                   5313:             if ($section) { $role .= ':'.$section; }
                   5314:             if ($returnhash{$role}) {
                   5315:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5316:             } else {
                   5317:                 $returnhash{$role}=$username.':'.$domain;
                   5318:             }
1.351     www      5319:         } else {
1.988     raeburn  5320:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5321:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5322:             if ($returnhash{$key}) {
                   5323: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5324:             } else {
                   5325:                 $returnhash{$key}=$username.':'.$domain;
                   5326:             }
1.351     www      5327:         }
1.948     raeburn  5328:     }
1.400     www      5329:     return %returnhash;
                   5330: }
                   5331: 
                   5332: sub get_my_roles {
1.937     raeburn  5333:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5334:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5335:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5336:     my (%dumphash,%nothide);
1.1086    raeburn  5337:     if ($context eq 'userroles') {
1.1166    raeburn  5338:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5339:     } else {
1.1172.2.23  raeburn  5340:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5341:         if ($hidepriv) {
                   5342:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5343:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5344:                 if ($user !~ /:/) {
                   5345:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5346:                 } else {
                   5347:                     $nothide{$user} = 1;
                   5348:                 }
                   5349:             }
                   5350:         }
1.858     raeburn  5351:     }
1.400     www      5352:     my %returnhash=();
                   5353:     my $now=time;
1.999     raeburn  5354:     my %privileged;
1.800     albertel 5355:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5356:         my ($role,$tend,$tstart);
                   5357:         if ($context eq 'userroles') {
1.1149    raeburn  5358:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5359: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5360:         } else {
                   5361:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5362:         }
1.400     www      5363:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5364:         my $status = 'active';
1.939     raeburn  5365:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5366:             $status = 'previous';
                   5367:         } 
                   5368:         if (($tstart) && ($now<$tstart)) {
                   5369:             $status = 'future';
                   5370:         }
                   5371:         if (ref($types) eq 'ARRAY') {
                   5372:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5373:                 next;
                   5374:             } 
                   5375:         } else {
                   5376:             if ($status ne 'active') {
                   5377:                 next;
                   5378:             }
                   5379:         }
1.867     raeburn  5380:         my ($rolecode,$username,$domain,$section,$area);
                   5381:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  5382:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5383:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5384:         } else {
                   5385:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5386:         }
1.832     raeburn  5387:         if (ref($roledoms) eq 'ARRAY') {
                   5388:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5389:                 next;
                   5390:             }
                   5391:         }
                   5392:         if (ref($roles) eq 'ARRAY') {
                   5393:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5394:                 if ($role =~ /^cr\//) {
                   5395:                     if (!grep(/^cr$/,@{$roles})) {
                   5396:                         next;
                   5397:                     }
1.1104    raeburn  5398:                 } elsif ($role =~ /^gr\//) {
                   5399:                     if (!grep(/^gr$/,@{$roles})) {
                   5400:                         next;
                   5401:                     }
1.922     raeburn  5402:                 } else {
                   5403:                     next;
                   5404:                 }
1.832     raeburn  5405:             }
1.867     raeburn  5406:         }
1.937     raeburn  5407:         if ($hidepriv) {
1.1172.2.23  raeburn  5408:             my @privroles = ('dc','su');
1.999     raeburn  5409:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  5410:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5411:             } else {
1.1172.2.23  raeburn  5412:                 my $possdoms = [$domain];
                   5413:                 if (ref($roledoms) eq 'ARRAY') {
                   5414:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5415:                 }
1.1172.2.23  raeburn  5416:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5417:                     if (!$nothide{$username.':'.$domain}) {
                   5418:                         next;
                   5419:                     }
                   5420:                 }
1.937     raeburn  5421:             }
                   5422:         }
1.933     raeburn  5423:         if ($withsec) {
                   5424:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5425:                 $tstart.':'.$tend;
                   5426:         } else {
                   5427:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5428:         }
1.832     raeburn  5429:     }
1.373     www      5430:     return %returnhash;
1.399     www      5431: }
                   5432: 
1.1172.2.89  raeburn  5433: sub get_all_adhocroles {
                   5434:     my ($dom) = @_;
                   5435:     my @roles_by_num = ();
                   5436:     my %domdefaults = &get_domain_defaults($dom);
                   5437:     my (%description,%access_in_dom,%access_info);
                   5438:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5439:         my $count = 0;
                   5440:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5441:         my %ordered;
                   5442:         foreach my $role (sort(keys(%domcurrent))) {
                   5443:             my ($order,$desc,$access_in_dom);
                   5444:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5445:                 $order = $domcurrent{$role}{'order'};
                   5446:                 $desc = $domcurrent{$role}{'desc'};
                   5447:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5448:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5449:             }
                   5450:             if ($order eq '') {
                   5451:                 $order = $count;
                   5452:             }
                   5453:             $ordered{$order} = $role;
                   5454:             if ($desc ne '') {
                   5455:                 $description{$role} = $desc;
                   5456:             } else {
                   5457:                 $description{$role}= $role;
                   5458:             }
                   5459:             $count++;
                   5460:         }
                   5461:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5462:             push(@roles_by_num,$ordered{$item});
                   5463:         }
                   5464:     }
                   5465:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5466: }
                   5467: 
                   5468: sub get_my_adhocroles {
                   5469:     my ($cid,$checkreg) = @_;
                   5470:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5471:     if ($env{'request.course.id'} eq $cid) {
                   5472:         $cdom = $env{'course.'.$cid.'.domain'};
                   5473:         $cnum = $env{'course.'.$cid.'.num'};
                   5474:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5475:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5476:         $cdom = $1;
                   5477:         $cnum = $2;
                   5478:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5479:                                      $cdom,$cnum);
                   5480:     }
                   5481:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5482:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5483:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5484:         if ($rosterhash{$user} ne '') {
                   5485:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5486:             return ([],{}) if ($type eq 'auto');
                   5487:         }
                   5488:     }
                   5489:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5490:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5491:             my $then=$env{'user.login.time'};
                   5492:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5493:             if (!$update) {
                   5494:                 $update = $then;
                   5495:             }
                   5496:             my @liveroles;
                   5497:             foreach my $role ('dh','da') {
                   5498:                 if ($env{"user.role.$role./$cdom/"}) {
                   5499:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5500:                     my $limit = $update;
                   5501:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5502:                         $limit = $then;
                   5503:                     }
                   5504:                     my $activerole = 1;
                   5505:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5506:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5507:                     if ($activerole) {
                   5508:                         push(@liveroles,$role);
                   5509:                     }
                   5510:                 }
                   5511:             }
                   5512:             if (@liveroles) {
1.1172.2.89  raeburn  5513:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5514:                     my ($accessref,$accessinfo,%access_in_dom);
                   5515:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5516:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5517:                         if (@{$roles_by_num}) {
                   5518:                             my %settings;
                   5519:                             if ($env{'request.course.id'} eq $cid) {
                   5520:                                 foreach my $envkey (keys(%env)) {
                   5521:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5522:                                         $settings{$1} = $env{$envkey};
                   5523:                                     }
                   5524:                                 }
                   5525:                             } else {
                   5526:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5527:                             }
                   5528:                             my %setincrs;
                   5529:                             if ($settings{'internal.adhocaccess'}) {
                   5530:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5531:                             }
                   5532:                             my @statuses;
                   5533:                             if ($env{'environment.inststatus'}) {
                   5534:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5535:                             }
                   5536:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5537:                             if (ref($accessref) eq 'HASH') {
                   5538:                                 %access_in_dom = %{$accessref};
                   5539:                             }
                   5540:                             foreach my $role (@{$roles_by_num}) {
                   5541:                                 my ($curraccess,@okstatus,@personnel);
                   5542:                                 if ($setincrs{$role}) {
                   5543:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5544:                                     if ($curraccess eq 'status') {
                   5545:                                         @okstatus = split(/\&/,$rest);
                   5546:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5547:                                         @personnel = split(/\&/,$rest);
                   5548:                                     }
                   5549:                                 } else {
                   5550:                                     $curraccess = $access_in_dom{$role};
                   5551:                                     if (ref($accessinfo) eq 'HASH') {
                   5552:                                         if ($curraccess eq 'status') {
                   5553:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5554:                                                 @okstatus = @{$accessinfo->{$role}};
                   5555:                                             }
                   5556:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5557:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5558:                                                 @personnel = @{$accessinfo->{$role}};
                   5559:                                             }
                   5560:                                         }
                   5561:                                     }
                   5562:                                 }
                   5563:                                 if ($curraccess eq 'none') {
                   5564:                                     next;
                   5565:                                 } elsif ($curraccess eq 'all') {
                   5566:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5567:                                 } elsif ($curraccess eq 'dh') {
                   5568:                                     if (grep(/^dh$/,@liveroles)) {
                   5569:                                         push(@possroles,$role);
                   5570:                                     } else {
                   5571:                                         next;
                   5572:                                     }
                   5573:                                 } elsif ($curraccess eq 'da') {
                   5574:                                     if (grep(/^da$/,@liveroles)) {
                   5575:                                         push(@possroles,$role);
                   5576:                                     } else {
                   5577:                                         next;
                   5578:                                     }
1.1172.2.89  raeburn  5579:                                 } elsif ($curraccess eq 'status') {
                   5580:                                     if (@okstatus) {
                   5581:                                         if (!@statuses) {
                   5582:                                             if (grep(/^default$/,@okstatus)) {
                   5583:                                                 push(@possroles,$role);
                   5584:                                             }
                   5585:                                         } else {
                   5586:                                             foreach my $status (@okstatus) {
                   5587:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5588:                                                     push(@possroles,$role);
                   5589:                                                     last;
                   5590:                                                 }
                   5591:                                             }
                   5592:                                         }
                   5593:                                     }
                   5594:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5595:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5596:                                         if ($curraccess eq 'exc') {
                   5597:                                             push(@possroles,$role);
                   5598:                                         }
                   5599:                                     } elsif ($curraccess eq 'inc') {
                   5600:                                         push(@possroles,$role);
                   5601:                                     }
                   5602:                                 }
                   5603:                             }
                   5604:                         }
                   5605:                     }
                   5606:                 }
                   5607:             }
                   5608:         }
                   5609:     }
                   5610:     unless (ref($description) eq 'HASH') {
                   5611:         if (ref($roles_by_num) eq 'ARRAY') {
                   5612:             my %desc;
                   5613:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5614:             $description = \%desc;
                   5615:         } else {
                   5616:             $description = {};
                   5617:         }
                   5618:     }
                   5619:     return (\@possroles,$description);
                   5620: }
                   5621: 
1.399     www      5622: # ----------------------------------------------------- Frontpage Announcements
                   5623: #
                   5624: #
                   5625: 
                   5626: sub postannounce {
                   5627:     my ($server,$text)=@_;
1.844     albertel 5628:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5629:     unless ($text=~/\w/) { $text=''; }
                   5630:     return &reply('setannounce:'.&escape($text),$server);
                   5631: }
                   5632: 
                   5633: sub getannounce {
1.448     albertel 5634: 
1.1172.2.96  raeburn  5635:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5636: 	my $announcement='';
1.800     albertel 5637: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5638: 	close($fh);
1.399     www      5639: 	if ($announcement=~/\w/) { 
                   5640: 	    return 
                   5641:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5642:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5643: 	} else {
                   5644: 	    return '';
                   5645: 	}
                   5646:     } else {
                   5647: 	return '';
                   5648:     }
1.351     www      5649: }
1.353     www      5650: 
                   5651: # ---------------------------------------------------------- Course ID routines
                   5652: # Deal with domain's nohist_courseid.db files
                   5653: #
                   5654: 
                   5655: sub courseidput {
1.921     raeburn  5656:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5657:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5658:     my $outcome;
                   5659:     if ($caller eq 'timeonly') {
                   5660:         my $cids = '';
                   5661:         foreach my $item (keys(%$storehash)) {
                   5662:             $cids.=&escape($item).'&';
                   5663:         }
                   5664:         $cids=~s/\&$//;
                   5665:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5666:                           $coursehome);       
                   5667:     } else {
                   5668:         my $items = '';
                   5669:         foreach my $item (keys(%$storehash)) {
                   5670:             $items.= &escape($item).'='.
                   5671:                      &freeze_escape($$storehash{$item}).'&';
                   5672:         }
                   5673:         $items=~s/\&$//;
                   5674:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5675:                           $coursehome);
1.918     raeburn  5676:     }
                   5677:     if ($outcome eq 'unknown_cmd') {
                   5678:         my $what;
                   5679:         foreach my $cid (keys(%$storehash)) {
                   5680:             $what .= &escape($cid).'=';
1.921     raeburn  5681:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5682:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5683:             }
                   5684:             $what =~ s/\:$/&/;
                   5685:         }
                   5686:         $what =~ s/\&$//;  
                   5687:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5688:     } else {
                   5689:         return $outcome;
                   5690:     }
1.353     www      5691: }
                   5692: 
                   5693: sub courseiddump {
1.921     raeburn  5694:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5695:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5696:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5697:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5698:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5699:     my $as_hash = 1;
                   5700:     my %returnhash;
                   5701:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5702:     my %libserv = &all_library();
                   5703:     foreach my $tryserver (keys(%libserv)) {
                   5704:         if ( (  $hostidflag == 1 
                   5705: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5706: 	     || (!defined($hostidflag)) ) {
                   5707: 
1.918     raeburn  5708: 	    if (($domfilter eq '') ||
                   5709: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5710:                 my $rep;
                   5711:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5712:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5713:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5714:                                 &escape($descfilter), &escape($instcodefilter),
                   5715:                                 &escape($ownerfilter), &escape($coursefilter),
                   5716:                                 &escape($typefilter), &escape($regexp_ok),
                   5717:                                 $as_hash, &escape($selfenrollonly),
                   5718:                                 &escape($catfilter), $showhidden, $caller,
                   5719:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5720:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5721:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5722:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5723:                 } else {
                   5724:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5725:                              $sincefilter.':'.&escape($descfilter).':'.
                   5726:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5727:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5728:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5729:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5730:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5731:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5732:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5733:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5734:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5735:                 }
                   5736: 
1.918     raeburn  5737:                 my @pairs=split(/\&/,$rep);
                   5738:                 foreach my $item (@pairs) {
                   5739:                     my ($key,$value)=split(/\=/,$item,2);
                   5740:                     $key = &unescape($key);
                   5741:                     next if ($key =~ /^error: 2 /);
                   5742:                     my $result = &thaw_unescape($value);
                   5743:                     if (ref($result) eq 'HASH') {
                   5744:                         $returnhash{$key}=$result;
                   5745:                     } else {
1.921     raeburn  5746:                         my @responses = split(/:/,$value);
                   5747:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5748:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5749:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5750:                         }
1.1008    raeburn  5751:                     }
1.353     www      5752:                 }
                   5753:             }
                   5754:         }
                   5755:     }
                   5756:     return %returnhash;
                   5757: }
                   5758: 
1.1055    raeburn  5759: sub courselastaccess {
                   5760:     my ($cdom,$cnum,$hostidref) = @_;
                   5761:     my %returnhash;
                   5762:     if ($cdom && $cnum) {
                   5763:         my $chome = &homeserver($cnum,$cdom);
                   5764:         if ($chome ne 'no_host') {
                   5765:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5766:             &extract_lastaccess(\%returnhash,$rep);
                   5767:         }
                   5768:     } else {
                   5769:         if (!$cdom) { $cdom=''; }
                   5770:         my %libserv = &all_library();
                   5771:         foreach my $tryserver (keys(%libserv)) {
                   5772:             if (ref($hostidref) eq 'ARRAY') {
                   5773:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5774:             } 
                   5775:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5776:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5777:                 &extract_lastaccess(\%returnhash,$rep);
                   5778:             }
                   5779:         }
                   5780:     }
                   5781:     return %returnhash;
                   5782: }
                   5783: 
                   5784: sub extract_lastaccess {
                   5785:     my ($returnhash,$rep) = @_;
                   5786:     if (ref($returnhash) eq 'HASH') {
                   5787:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5788:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5789:                  $rep eq '') {
                   5790:             my @pairs=split(/\&/,$rep);
                   5791:             foreach my $item (@pairs) {
                   5792:                 my ($key,$value)=split(/\=/,$item,2);
                   5793:                 $key = &unescape($key);
                   5794:                 next if ($key =~ /^error: 2 /);
                   5795:                 $returnhash->{$key} = &thaw_unescape($value);
                   5796:             }
                   5797:         }
                   5798:     }
                   5799:     return;
                   5800: }
                   5801: 
1.658     raeburn  5802: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5803: 
                   5804: sub dcmailput {
1.685     raeburn  5805:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5806:     my $status = &Apache::lonnet::critical(
1.740     www      5807:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5808:        &escape($message),$server);
1.662     raeburn  5809:     return $status;
                   5810: }
                   5811: 
1.658     raeburn  5812: sub dcmaildump {
                   5813:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5814:     my %returnhash=();
1.846     albertel 5815: 
                   5816:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5817:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5818:                                                          &escape($enddate).':';
                   5819: 	my @esc_senders=map { &escape($_)} @$senders;
                   5820: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5821: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5822:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5823:             if (($key) && ($value)) {
                   5824:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5825:             }
                   5826:         }
                   5827:     }
                   5828:     return %returnhash;
                   5829: }
1.662     raeburn  5830: # ---------------------------------------------------------- Domain roles
                   5831: 
                   5832: sub get_domain_roles {
                   5833:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5834:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5835:         $startdate = '.';
                   5836:     }
1.1018    raeburn  5837:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5838:         $enddate = '.';
                   5839:     }
1.922     raeburn  5840:     my $rolelist;
                   5841:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5842:         $rolelist = join('&',@{$roles});
1.922     raeburn  5843:     }
1.662     raeburn  5844:     my %personnel = ();
1.841     albertel 5845: 
                   5846:     my %servers = &get_servers($dom,'library');
                   5847:     foreach my $tryserver (keys(%servers)) {
                   5848: 	%{$personnel{$tryserver}}=();
                   5849: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5850: 					    &escape($startdate).':'.
                   5851: 					    &escape($enddate).':'.
                   5852: 					    &escape($rolelist), $tryserver))) {
                   5853: 	    my ($key,$value) = split(/\=/,$line,2);
                   5854: 	    if (($key) && ($value)) {
                   5855: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5856: 	    }
                   5857: 	}
1.662     raeburn  5858:     }
                   5859:     return %personnel;
                   5860: }
1.658     raeburn  5861: 
1.1172.2.89  raeburn  5862: sub get_active_domroles {
                   5863:     my ($dom,$roles) = @_;
                   5864:     return () unless (ref($roles) eq 'ARRAY');
                   5865:     my $now = time;
                   5866:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5867:     my %domroles;
                   5868:     foreach my $server (keys(%dompersonnel)) {
                   5869:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5870:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5871:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5872:         }
                   5873:     }
                   5874:     return %domroles;
                   5875: }
                   5876: 
1.1057    www      5877: # ----------------------------------------------------------- Interval timing 
1.149     www      5878: 
1.1153    www      5879: {
                   5880: # Caches needed for speedup of navmaps
                   5881: # We don't want to cache this for very long at all (5 seconds at most)
                   5882: # 
                   5883: # The user for whom we cache
                   5884: my $cachedkey='';
                   5885: # The cached times for this user
                   5886: my %cachedtimes=();
                   5887: # When this was last done
1.1172.2.66  raeburn  5888: my $cachedtime='';
1.1153    www      5889: 
                   5890: sub load_all_first_access {
1.1172.2.146.  .1(raebu 5891:22):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5892:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.146.  .1(raebu 5893:22):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5894:22):         (!$ignorecache)) {
1.1154    raeburn  5895:         return;
                   5896:     }
                   5897:     $cachedtime=time;
                   5898:     $cachedkey=$uname.':'.$udom;
                   5899:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5900: }
                   5901: 
1.504     albertel 5902: sub get_first_access {
1.1172.2.146.  .1(raebu 5903:22):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5904:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5905:     if ($argsymb) { $symb=$argsymb; }
                   5906:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5907:     if ($argmap) { $map = $argmap; }
1.926     albertel 5908:     if ($type eq 'course') {
                   5909: 	$res='course';
                   5910:     } elsif ($type eq 'map') {
1.588     albertel 5911: 	$res=&symbread($map);
                   5912:     } else {
                   5913: 	$res=$symb;
                   5914:     }
1.1172.2.146.  .1(raebu 5915:22):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5916:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5917: }
                   5918: 
                   5919: sub set_first_access {
1.1162    raeburn  5920:     my ($type,$interval)=@_;
1.790     albertel 5921:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5922:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5923:     if ($type eq 'course') {
                   5924: 	$res='course';
                   5925:     } elsif ($type eq 'map') {
1.588     albertel 5926: 	$res=&symbread($map);
                   5927:     } else {
                   5928: 	$res=$symb;
                   5929:     }
1.1153    www      5930:     $cachedkey='';
1.1162    raeburn  5931:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5932:     if ($firstaccess) {
                   5933:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5934:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5935:                  "in $courseid");
                   5936:         return 'already_set';
                   5937:     } else {
1.1162    raeburn  5938:         my $start = time;
                   5939: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5940:                           $udom,$uname);
                   5941:         if ($putres eq 'ok') {
                   5942:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5943:                  $udom,$uname); 
                   5944:             &appenv(
                   5945:                      {
                   5946:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5947:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5948:                      }
                   5949:                   );
1.1172.2.97  raeburn  5950:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5951:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5952:             }
1.1172.2.102  raeburn  5953:         } elsif ($putres ne 'refused') {
                   5954:             &logthis("Result: $putres when attempting to set first access time ".
                   5955:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5956:         }
                   5957:         return $putres;
1.505     albertel 5958:     }
                   5959:     return 'already_set';
1.504     albertel 5960: }
1.1153    www      5961: }
1.1172.2.32  raeburn  5962: 
                   5963: sub checkout {
                   5964:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5965:     my $now=time;
                   5966:     my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134  raeburn  5967:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5968:     my $infostr=&escape(
                   5969:                  'CHECKOUTTOKEN&'.
                   5970:                  $tuname.'&'.
                   5971:                  $tudom.'&'.
                   5972:                  $tcrsid.'&'.
                   5973:                  $symb.'&'.
1.1172.2.134  raeburn  5974:                  $now.'&'.$ip);
1.1172.2.32  raeburn  5975:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5976:     if ($token=~/^error\:/) {
                   5977:         &logthis("<font color=\"blue\">WARNING: ".
                   5978:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5979:                  "</font>");
                   5980:         return '';
                   5981:     }
                   5982: 
                   5983:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5984:     $token=~tr/a-z/A-Z/;
                   5985: 
                   5986:     my %infohash=('resource.0.outtoken' => $token,
                   5987:                   'resource.0.checkouttime' => $now,
1.1172.2.134  raeburn  5988:                   'resource.0.outremote' => $ip);
1.1172.2.32  raeburn  5989: 
                   5990:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5991:        return '';
                   5992:     } else {
                   5993:         &logthis("<font color=\"blue\">WARNING: ".
                   5994:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5995:                  "</font>");
                   5996:     }
                   5997: 
                   5998:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5999:                          &escape('Checkout '.$infostr.' - '.
                   6000:                                                  $token)) ne 'ok') {
                   6001:         return '';
                   6002:     } else {
                   6003:         &logthis("<font color=\"blue\">WARNING: ".
                   6004:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   6005:                  "</font>");
                   6006:     }
                   6007:     return $token;
                   6008: }
                   6009: 
                   6010: # ------------------------------------------------------------ Check in an item
                   6011: 
                   6012: sub checkin {
                   6013:     my $token=shift;
                   6014:     my $now=time;
                   6015:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   6016:     $lonhost=~tr/A-Z/a-z/;
                   6017:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   6018:     $dtoken=~s/\W/\_/g;
1.1172.2.134  raeburn  6019:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  6020:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   6021:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   6022: 
                   6023:     unless (($tuname) && ($tudom)) {
                   6024:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   6025:         return '';
                   6026:     }
                   6027: 
                   6028:     unless (&allowed('mgr',$tcrsid)) {
                   6029:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   6030:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   6031:         return '';
                   6032:     }
                   6033: 
                   6034:     my %infohash=('resource.0.intoken' => $token,
                   6035:                   'resource.0.checkintime' => $now,
1.1172.2.134  raeburn  6036:                   'resource.0.inremote' => $ip);
1.1172.2.32  raeburn  6037: 
                   6038:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   6039:        return '';
                   6040:     }
                   6041: 
                   6042:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   6043:                          &escape('Checkin - '.$token)) ne 'ok') {
                   6044:         return '';
                   6045:     }
                   6046: 
                   6047:     return ($symb,$tuname,$tudom,$tcrsid);
                   6048: }
                   6049: 
1.110     www      6050: # --------------------------------------------- Set Expire Date for Spreadsheet
                   6051: 
                   6052: sub expirespread {
                   6053:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 6054:     my $cid=$env{'request.course.id'}; 
1.110     www      6055:     if ($cid) {
                   6056:        my $now=time;
                   6057:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 6058:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   6059:                             $env{'course.'.$cid.'.num'}.
1.110     www      6060: 	        	    ':nohist_expirationdates:'.
                   6061:                             &escape($key).'='.$now,
1.620     albertel 6062:                             $env{'course.'.$cid.'.home'})
1.110     www      6063:     }
                   6064:     return 'ok';
1.14      www      6065: }
                   6066: 
1.109     www      6067: # ----------------------------------------------------- Devalidate Spreadsheets
                   6068: 
                   6069: sub devalidate {
1.325     www      6070:     my ($symb,$uname,$udom)=@_;
1.620     albertel 6071:     my $cid=$env{'request.course.id'}; 
1.109     www      6072:     if ($cid) {
1.391     matthew  6073:         # delete the stored spreadsheets for
                   6074:         # - the student level sheet of this user in course's homespace
                   6075:         # - the assessment level sheet for this resource 
                   6076:         #   for this user in user's homespace
1.553     albertel 6077: 	# - current conditional state info
1.325     www      6078: 	my $key=$uname.':'.$udom.':';
1.109     www      6079:         my $status=
1.299     matthew  6080: 	    &del('nohist_calculatedsheets',
1.391     matthew  6081: 		 [$key.'studentcalc:'],
1.620     albertel 6082: 		 $env{'course.'.$cid.'.domain'},
                   6083: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 6084: 		.' '.
                   6085: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  6086: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      6087:         unless ($status eq 'ok ok') {
                   6088:            &logthis('Could not devalidate spreadsheet '.
1.325     www      6089:                     $uname.' at '.$udom.' for '.
1.109     www      6090: 		    $symb.': '.$status);
1.133     albertel 6091:         }
1.553     albertel 6092: 	&delenv('user.state.'.$cid);
1.109     www      6093:     }
                   6094: }
                   6095: 
1.265     albertel 6096: sub get_scalar {
                   6097:     my ($string,$end) = @_;
                   6098:     my $value;
                   6099:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   6100: 	$value = $1;
                   6101:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   6102: 	$value = $1;
                   6103:     }
                   6104:     return &unescape($value);
                   6105: }
                   6106: 
                   6107: sub array2str {
                   6108:   my (@array) = @_;
                   6109:   my $result=&arrayref2str(\@array);
                   6110:   $result=~s/^__ARRAY_REF__//;
                   6111:   $result=~s/__END_ARRAY_REF__$//;
                   6112:   return $result;
                   6113: }
                   6114: 
1.204     albertel 6115: sub arrayref2str {
                   6116:   my ($arrayref) = @_;
1.265     albertel 6117:   my $result='__ARRAY_REF__';
1.204     albertel 6118:   foreach my $elem (@$arrayref) {
1.265     albertel 6119:     if(ref($elem) eq 'ARRAY') {
                   6120:       $result.=&arrayref2str($elem).'&';
                   6121:     } elsif(ref($elem) eq 'HASH') {
                   6122:       $result.=&hashref2str($elem).'&';
                   6123:     } elsif(ref($elem)) {
                   6124:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 6125:     } else {
                   6126:       $result.=&escape($elem).'&';
                   6127:     }
                   6128:   }
                   6129:   $result=~s/\&$//;
1.265     albertel 6130:   $result .= '__END_ARRAY_REF__';
1.204     albertel 6131:   return $result;
                   6132: }
                   6133: 
1.168     albertel 6134: sub hash2str {
1.204     albertel 6135:   my (%hash) = @_;
                   6136:   my $result=&hashref2str(\%hash);
1.265     albertel 6137:   $result=~s/^__HASH_REF__//;
                   6138:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 6139:   return $result;
                   6140: }
                   6141: 
                   6142: sub hashref2str {
                   6143:   my ($hashref)=@_;
1.265     albertel 6144:   my $result='__HASH_REF__';
1.800     albertel 6145:   foreach my $key (sort(keys(%$hashref))) {
                   6146:     if (ref($key) eq 'ARRAY') {
                   6147:       $result.=&arrayref2str($key).'=';
                   6148:     } elsif (ref($key) eq 'HASH') {
                   6149:       $result.=&hashref2str($key).'=';
                   6150:     } elsif (ref($key)) {
1.265     albertel 6151:       $result.='=';
1.800     albertel 6152:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 6153:     } else {
1.1132    raeburn  6154: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 6155:     }
                   6156: 
1.800     albertel 6157:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   6158:       $result.=&arrayref2str($hashref->{$key}).'&';
                   6159:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   6160:       $result.=&hashref2str($hashref->{$key}).'&';
                   6161:     } elsif(ref($hashref->{$key})) {
1.265     albertel 6162:        $result.='&';
1.800     albertel 6163:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 6164:     } else {
1.800     albertel 6165:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 6166:     }
                   6167:   }
1.168     albertel 6168:   $result=~s/\&$//;
1.265     albertel 6169:   $result .= '__END_HASH_REF__';
1.168     albertel 6170:   return $result;
                   6171: }
                   6172: 
                   6173: sub str2hash {
1.265     albertel 6174:     my ($string)=@_;
                   6175:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   6176:     return %$hash;
                   6177: }
                   6178: 
                   6179: sub str2hashref {
1.168     albertel 6180:   my ($string) = @_;
1.265     albertel 6181: 
                   6182:   my %hash;
                   6183: 
                   6184:   if($string !~ /^__HASH_REF__/) {
                   6185:       if (! ($string eq '' || !defined($string))) {
                   6186: 	  $hash{'error'}='Not hash reference';
                   6187:       }
                   6188:       return (\%hash, $string);
                   6189:   }
                   6190: 
                   6191:   $string =~ s/^__HASH_REF__//;
                   6192: 
                   6193:   while($string !~ /^__END_HASH_REF__/) {
                   6194:       #key
                   6195:       my $key='';
                   6196:       if($string =~ /^__HASH_REF__/) {
                   6197:           ($key, $string)=&str2hashref($string);
                   6198:           if(defined($key->{'error'})) {
                   6199:               $hash{'error'}='Bad data';
                   6200:               return (\%hash, $string);
                   6201:           }
                   6202:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6203:           ($key, $string)=&str2arrayref($string);
                   6204:           if($key->[0] eq 'Array reference error') {
                   6205:               $hash{'error'}='Bad data';
                   6206:               return (\%hash, $string);
                   6207:           }
                   6208:       } else {
                   6209:           $string =~ s/^(.*?)=//;
1.267     albertel 6210: 	  $key=&unescape($1);
1.265     albertel 6211:       }
                   6212:       $string =~ s/^=//;
                   6213: 
                   6214:       #value
                   6215:       my $value='';
                   6216:       if($string =~ /^__HASH_REF__/) {
                   6217:           ($value, $string)=&str2hashref($string);
                   6218:           if(defined($value->{'error'})) {
                   6219:               $hash{'error'}='Bad data';
                   6220:               return (\%hash, $string);
                   6221:           }
                   6222:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6223:           ($value, $string)=&str2arrayref($string);
                   6224:           if($value->[0] eq 'Array reference error') {
                   6225:               $hash{'error'}='Bad data';
                   6226:               return (\%hash, $string);
                   6227:           }
                   6228:       } else {
                   6229: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   6230:       }
                   6231:       $string =~ s/^&//;
                   6232: 
                   6233:       $hash{$key}=$value;
1.204     albertel 6234:   }
1.265     albertel 6235: 
                   6236:   $string =~ s/^__END_HASH_REF__//;
                   6237: 
                   6238:   return (\%hash, $string);
1.204     albertel 6239: }
                   6240: 
                   6241: sub str2array {
1.265     albertel 6242:     my ($string)=@_;
                   6243:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   6244:     return @$array;
                   6245: }
                   6246: 
                   6247: sub str2arrayref {
1.204     albertel 6248:   my ($string) = @_;
1.265     albertel 6249:   my @array;
                   6250: 
                   6251:   if($string !~ /^__ARRAY_REF__/) {
                   6252:       if (! ($string eq '' || !defined($string))) {
                   6253: 	  $array[0]='Array reference error';
                   6254:       }
                   6255:       return (\@array, $string);
                   6256:   }
                   6257: 
                   6258:   $string =~ s/^__ARRAY_REF__//;
                   6259: 
                   6260:   while($string !~ /^__END_ARRAY_REF__/) {
                   6261:       my $value='';
                   6262:       if($string =~ /^__HASH_REF__/) {
                   6263:           ($value, $string)=&str2hashref($string);
                   6264:           if(defined($value->{'error'})) {
                   6265:               $array[0] ='Array reference error';
                   6266:               return (\@array, $string);
                   6267:           }
                   6268:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6269:           ($value, $string)=&str2arrayref($string);
                   6270:           if($value->[0] eq 'Array reference error') {
                   6271:               $array[0] ='Array reference error';
                   6272:               return (\@array, $string);
                   6273:           }
                   6274:       } else {
                   6275: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   6276:       }
                   6277:       $string =~ s/^&//;
                   6278: 
                   6279:       push(@array, $value);
1.191     harris41 6280:   }
1.265     albertel 6281: 
                   6282:   $string =~ s/^__END_ARRAY_REF__//;
                   6283: 
                   6284:   return (\@array, $string);
1.168     albertel 6285: }
                   6286: 
1.167     albertel 6287: # -------------------------------------------------------------------Temp Store
                   6288: 
1.168     albertel 6289: sub tmpreset {
                   6290:   my ($symb,$namespace,$domain,$stuname) = @_;
                   6291:   if (!$symb) {
                   6292:     $symb=&symbread();
1.620     albertel 6293:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6294:   }
                   6295:   $symb=escape($symb);
                   6296: 
1.620     albertel 6297:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 6298:   $namespace=~s/\//\_/g;
                   6299:   $namespace=~s/\W//g;
                   6300: 
1.620     albertel 6301:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6302:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6303:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6304:       $stuname=&get_requestor_ip();
1.591     albertel 6305:   }
1.1117    foxr     6306:   my $path=LONCAPA::tempdir();
1.168     albertel 6307:   my %hash;
                   6308:   if (tie(%hash,'GDBM_File',
                   6309: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6310: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6311:     foreach my $key (keys(%hash)) {
1.180     albertel 6312:       if ($key=~ /:$symb/) {
1.168     albertel 6313: 	delete($hash{$key});
                   6314:       }
                   6315:     }
                   6316:   }
                   6317: }
                   6318: 
1.167     albertel 6319: sub tmpstore {
1.168     albertel 6320:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6321: 
                   6322:   if (!$symb) {
                   6323:     $symb=&symbread();
1.620     albertel 6324:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6325:   }
                   6326:   $symb=escape($symb);
                   6327: 
                   6328:   if (!$namespace) {
                   6329:     # I don't think we would ever want to store this for a course.
                   6330:     # it seems this will only be used if we don't have a course.
1.620     albertel 6331:     #$namespace=$env{'request.course.id'};
1.168     albertel 6332:     #if (!$namespace) {
1.620     albertel 6333:       $namespace=$env{'request.state'};
1.168     albertel 6334:     #}
                   6335:   }
                   6336:   $namespace=~s/\//\_/g;
                   6337:   $namespace=~s/\W//g;
1.620     albertel 6338:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6339:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6340:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6341:       $stuname=&get_requestor_ip();
1.591     albertel 6342:   }
1.168     albertel 6343:   my $now=time;
                   6344:   my %hash;
1.1117    foxr     6345:   my $path=LONCAPA::tempdir();
1.168     albertel 6346:   if (tie(%hash,'GDBM_File',
                   6347: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6348: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6349:     $hash{"version:$symb"}++;
                   6350:     my $version=$hash{"version:$symb"};
                   6351:     my $allkeys=''; 
                   6352:     foreach my $key (keys(%$storehash)) {
                   6353:       $allkeys.=$key.':';
1.591     albertel 6354:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6355:     }
                   6356:     $hash{"$version:$symb:timestamp"}=$now;
                   6357:     $allkeys.='timestamp';
                   6358:     $hash{"$version:keys:$symb"}=$allkeys;
                   6359:     if (untie(%hash)) {
                   6360:       return 'ok';
                   6361:     } else {
                   6362:       return "error:$!";
                   6363:     }
                   6364:   } else {
                   6365:     return "error:$!";
                   6366:   }
                   6367: }
1.167     albertel 6368: 
1.168     albertel 6369: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6370: 
1.168     albertel 6371: sub tmprestore {
                   6372:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6373: 
1.168     albertel 6374:   if (!$symb) {
                   6375:     $symb=&symbread();
1.620     albertel 6376:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6377:   }
                   6378:   $symb=escape($symb);
                   6379: 
1.620     albertel 6380:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6381: 
1.620     albertel 6382:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6383:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6384:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6385:       $stuname=&get_requestor_ip();
1.591     albertel 6386:   }
1.168     albertel 6387:   my %returnhash;
                   6388:   $namespace=~s/\//\_/g;
                   6389:   $namespace=~s/\W//g;
                   6390:   my %hash;
1.1117    foxr     6391:   my $path=LONCAPA::tempdir();
1.168     albertel 6392:   if (tie(%hash,'GDBM_File',
                   6393: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6394: 	  &GDBM_READER(),0640)) {
1.168     albertel 6395:     my $version=$hash{"version:$symb"};
                   6396:     $returnhash{'version'}=$version;
                   6397:     my $scope;
                   6398:     for ($scope=1;$scope<=$version;$scope++) {
                   6399:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6400:       my @keys=split(/:/,$vkeys);
                   6401:       my $key;
                   6402:       $returnhash{"$scope:keys"}=$vkeys;
                   6403:       foreach $key (@keys) {
1.591     albertel 6404: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6405: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6406:       }
                   6407:     }
1.168     albertel 6408:     if (!(untie(%hash))) {
                   6409:       return "error:$!";
                   6410:     }
                   6411:   } else {
                   6412:     return "error:$!";
                   6413:   }
                   6414:   return %returnhash;
1.167     albertel 6415: }
                   6416: 
1.9       www      6417: # ----------------------------------------------------------------------- Store
                   6418: 
                   6419: sub store {
1.1172.2.64  raeburn  6420:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6421:     my $home='';
                   6422: 
1.168     albertel 6423:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6424: 
1.213     www      6425:     $symb=&symbclean($symb);
1.122     albertel 6426:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6427: 
1.620     albertel 6428:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6429:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6430: 
                   6431:     &devalidate($symb,$stuname,$domain);
1.109     www      6432: 
                   6433:     $symb=escape($symb);
1.187     www      6434:     if (!$namespace) { 
1.620     albertel 6435:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6436:           return ''; 
                   6437:        } 
                   6438:     }
1.620     albertel 6439:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6440: 
1.1172.2.138  raeburn  6441:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6442:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6443: 
1.12      www      6444:     my $namevalue='';
1.800     albertel 6445:     foreach my $key (keys(%$storehash)) {
                   6446:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6447:     }
1.12      www      6448:     $namevalue=~s/\&$//;
1.187     www      6449:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6450:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6451: }
                   6452: 
1.47      www      6453: # -------------------------------------------------------------- Critical Store
                   6454: 
                   6455: sub cstore {
1.1172.2.64  raeburn  6456:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6457:     my $home='';
                   6458: 
1.168     albertel 6459:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6460: 
1.213     www      6461:     $symb=&symbclean($symb);
1.122     albertel 6462:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6463: 
1.620     albertel 6464:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6465:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6466: 
                   6467:     &devalidate($symb,$stuname,$domain);
1.109     www      6468: 
                   6469:     $symb=escape($symb);
1.187     www      6470:     if (!$namespace) { 
1.620     albertel 6471:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6472:           return ''; 
                   6473:        } 
                   6474:     }
1.620     albertel 6475:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6476: 
1.1172.2.138  raeburn  6477:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6478:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6479: 
1.47      www      6480:     my $namevalue='';
1.800     albertel 6481:     foreach my $key (keys(%$storehash)) {
                   6482:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6483:     }
1.47      www      6484:     $namevalue=~s/\&$//;
1.187     www      6485:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6486:     return critical
1.1172.2.64  raeburn  6487:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6488: }
                   6489: 
1.9       www      6490: # --------------------------------------------------------------------- Restore
                   6491: 
                   6492: sub restore {
1.124     www      6493:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6494:     my $home='';
                   6495: 
1.168     albertel 6496:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6497: 
1.122     albertel 6498:     if (!$symb) {
1.1172.2.26  raeburn  6499:         return if ($namespace eq 'courserequests');
                   6500:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6501:     } else {
1.1172.2.26  raeburn  6502:         unless ($namespace eq 'courserequests') {
                   6503:             $symb=&escape(&symbclean($symb));
                   6504:         }
1.122     albertel 6505:     }
1.188     www      6506:     if (!$namespace) { 
1.620     albertel 6507:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6508:           return ''; 
                   6509:        } 
                   6510:     }
1.620     albertel 6511:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6512:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6513:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6514:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6515: 
1.12      www      6516:     my %returnhash=();
1.800     albertel 6517:     foreach my $line (split(/\&/,$answer)) {
                   6518: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6519:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6520:     }
1.75      www      6521:     my $version;
                   6522:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6523:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6524:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6525:        }
1.75      www      6526:     }
1.13      www      6527:     return %returnhash;
1.34      www      6528: }
                   6529: 
                   6530: # ---------------------------------------------------------- Course Description
1.1118    foxr     6531: #
                   6532: #  
1.34      www      6533: 
                   6534: sub coursedescription {
1.731     albertel 6535:     my ($courseid,$args)=@_;
1.34      www      6536:     $courseid=~s/^\///;
1.49      www      6537:     $courseid=~s/\_/\//g;
1.34      www      6538:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6539:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6540:     my $normalid=$cdomain.'_'.$cnum;
                   6541:     # need to always cache even if we get errors otherwise we keep 
                   6542:     # trying and trying and trying to get the course description.
                   6543:     my %envhash=();
                   6544:     my %returnhash=();
1.731     albertel 6545:     
                   6546:     my $expiretime=600;
                   6547:     if ($env{'request.course.id'} eq $normalid) {
                   6548: 	$expiretime=120;
                   6549:     }
                   6550: 
                   6551:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6552:     if (!$args->{'freshen_cache'}
                   6553: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6554: 	foreach my $key (keys(%env)) {
                   6555: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6556: 	    my ($setting) = $1;
                   6557: 	    $returnhash{$setting} = $env{$key};
                   6558: 	}
                   6559: 	return %returnhash;
                   6560:     }
                   6561: 
1.1118    foxr     6562:     # get the data again
                   6563: 
1.731     albertel 6564:     if (!$args->{'one_time'}) {
                   6565: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6566:     }
1.811     albertel 6567: 
1.34      www      6568:     if ($chome ne 'no_host') {
1.302     albertel 6569:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6570:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6571: 	   my $username = $env{'user.name'}; # Defult username
                   6572: 	   if(defined $args->{'user'}) {
                   6573: 	       $username = $args->{'user'};
                   6574: 	   }
1.129     albertel 6575:            $returnhash{'home'}= $chome;
                   6576: 	   $returnhash{'domain'} = $cdomain;
                   6577: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6578:            if (!defined($returnhash{'type'})) {
                   6579:                $returnhash{'type'} = 'Course';
                   6580:            }
1.130     albertel 6581:            while (my ($name,$value) = each %returnhash) {
1.53      www      6582:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6583:            }
1.270     www      6584:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6585:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6586: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6587:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6588:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6589:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6590:        }
                   6591:     }
1.731     albertel 6592:     if (!$args->{'one_time'}) {
1.949     raeburn  6593: 	&appenv(\%envhash);
1.731     albertel 6594:     }
1.302     albertel 6595:     return %returnhash;
1.461     www      6596: }
                   6597: 
1.1080    raeburn  6598: sub update_released_required {
                   6599:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6600:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6601:         $cid = $env{'request.course.id'};
                   6602:         $cdom = $env{'course.'.$cid.'.domain'};
                   6603:         $cnum = $env{'course.'.$cid.'.num'};
                   6604:         $chome = $env{'course.'.$cid.'.home'};
                   6605:     }
                   6606:     if ($needsrelease) {
                   6607:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6608:         my $needsupdate;
                   6609:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6610:             $needsupdate = 1;
                   6611:         } else {
                   6612:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6613:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6614:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6615:                 $needsupdate = 1;
                   6616:             }
                   6617:         }
                   6618:         if ($needsupdate) {
                   6619:             my %needshash = (
                   6620:                              'internal.releaserequired' => $needsrelease,
                   6621:                             );
                   6622:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6623:             if ($putresult eq 'ok') {
                   6624:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6625:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6626:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6627:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6628:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6629:                 }
                   6630:             }
                   6631:         }
                   6632:     }
                   6633:     return;
                   6634: }
                   6635: 
1.461     www      6636: # -------------------------------------------------See if a user is privileged
                   6637: 
                   6638: sub privileged {
1.1172.2.23  raeburn  6639:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6640:     my $now = time;
1.1172.2.23  raeburn  6641:     my $roles;
                   6642:     if (ref($possroles) eq 'ARRAY') {
                   6643:         $roles = $possroles;
                   6644:     } else {
                   6645:         $roles = ['dc','su'];
                   6646:     }
                   6647:     if (ref($possdomains) eq 'ARRAY') {
                   6648:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6649:         foreach my $dom (@{$possdomains}) {
                   6650:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6651:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6652:                 foreach my $role (@{$roles}) {
                   6653:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6654:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6655:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6656:                             return 1 unless (($end && $end < $now) ||
                   6657:                                              ($start && $start > $now));
                   6658:                         }
                   6659:                     }
                   6660:                 }
                   6661:             }
                   6662:         }
                   6663:     } else {
                   6664:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6665:         my $now = time;
1.1170    droeschl 6666: 
1.1172.2.58  raeburn  6667:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6668:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6669:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6670:                 return 1 unless ($tend && $tend < $now)
                   6671:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6672:             }
1.1172.2.23  raeburn  6673:         }
                   6674:     }
1.461     www      6675:     return 0;
1.9       www      6676: }
1.1       albertel 6677: 
1.1172.2.23  raeburn  6678: sub privileged_by_domain {
                   6679:     my ($domains,$roles) = @_;
                   6680:     my %privileged = ();
                   6681:     my $cachetime = 60*60*24;
                   6682:     my $now = time;
                   6683:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6684:         return %privileged;
                   6685:     }
                   6686:     foreach my $dom (@{$domains}) {
                   6687:         next if (ref($privileged{$dom}) eq 'HASH');
                   6688:         my $needroles;
                   6689:         foreach my $role (@{$roles}) {
                   6690:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6691:             if (defined($cached)) {
                   6692:                 if (ref($result) eq 'HASH') {
                   6693:                     $privileged{$dom}{$role} = $result;
                   6694:                 }
                   6695:             } else {
                   6696:                 $needroles = 1;
                   6697:             }
                   6698:         }
                   6699:         if ($needroles) {
                   6700:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6701:             $privileged{$dom} = {};
                   6702:             foreach my $server (keys(%dompersonnel)) {
                   6703:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6704:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6705:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6706:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6707:                         next if ($end && $end < $now);
                   6708:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6709:                             $dompersonnel{$server}{$item};
                   6710:                     }
                   6711:                 }
                   6712:             }
                   6713:             if (ref($privileged{$dom}) eq 'HASH') {
                   6714:                 foreach my $role (@{$roles}) {
                   6715:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6716:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6717:                     } else {
                   6718:                         my %hash = ();
                   6719:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6720:                     }
                   6721:                 }
                   6722:             }
                   6723:         }
                   6724:     }
                   6725:     return %privileged;
                   6726: }
                   6727: 
1.103     harris41 6728: # -------------------------------------------------------- Get user privileges
1.11      www      6729: 
                   6730: sub rolesinit {
1.1169    droeschl 6731:     my ($domain, $username) = @_;
                   6732:     my %userroles = ('user.login.time' => time);
                   6733:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6734: 
                   6735:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6736:     # also, blocking can be triggered by an activating timer
                   6737:     # it's saved in the user's %env.
                   6738:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6739:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6740:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
1.1172.2.146.  .18(raeb 6741:-24):         %timerintchk, %timerintenv,%coauthorenv);
1.1169    droeschl 6742: 
1.1162    raeburn  6743:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6744:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6745:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6746:     }
1.1169    droeschl 6747: 
1.1162    raeburn  6748:     foreach my $key (keys(%timerinterval)) {
                   6749:         my ($cid,$rest) = split(/\0/,$key);
                   6750:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6751:     }
1.1169    droeschl 6752: 
1.11      www      6753:     my %allroles=();
1.1162    raeburn  6754:     my %allgroups=();
1.1172.2.146.  .18(raeb 6755:-24):     my %gotcoauconfig=();
1.11      www      6756: 
1.1172.2.58  raeburn  6757:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6758:         my $role = $rolesdump{$area};
                   6759:         $area =~ s/\_\w\w$//;
                   6760: 
                   6761:         my ($trole, $tend, $tstart, $group_privs);
                   6762: 
                   6763:         if ($role =~ /^cr/) {
                   6764:         # Custom role, defined by a user 
                   6765:         # e.g., user.role.cr/msu/smith/mynewrole
                   6766:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6767:                 $trole = $1;
                   6768:                 ($tend, $tstart) = split('_', $2);
                   6769:             } else {
                   6770:                 $trole = $role;
                   6771:             }
                   6772:         } elsif ($role =~ m|^gr/|) {
                   6773:         # Role of member in a group, defined within a course/community
                   6774:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6775:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6776:             next if $tstart eq '-1';
                   6777:             ($trole, $group_privs) = split(/\//, $trole);
                   6778:             $group_privs = &unescape($group_privs);
                   6779:         } else {
                   6780:         # Just a normal role, defined in roles.tab
                   6781:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6782:         }
                   6783: 
                   6784:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6785:                  $username);
                   6786:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6787: 
                   6788:         # role expired or not available yet?
                   6789:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6790:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6791: 
                   6792:         next if $area eq '' or $trole eq '';
                   6793: 
                   6794:         my $spec = "$trole.$area";
                   6795:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6796: 
                   6797:         if ($trole =~ /^cr\//) {
                   6798:         # Custom role, defined by a user
                   6799:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6800:         } elsif ($trole eq 'gr') {
                   6801:         # Role of a member in a group, defined within a course/community
                   6802:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6803:             next;
                   6804:         } else {
                   6805:         # Normal role, defined in roles.tab
                   6806:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.1172.2.146.  .18(raeb 6807:-24):             if (($trole eq 'ca') || ($trole eq 'aa')) {
                   6808:-24):                 (undef,my ($audom,$auname)) = split(/\//,$area);
                   6809:-24):                 unless ($gotcoauconfig{$area}) {
                   6810:-24):                     my @ca_settings = ('authoreditors');
                   6811:-24):                     my %info = &userenvironment($audom,$auname,@ca_settings);
                   6812:-24):                     $gotcoauconfig{$area} = 1;
                   6813:-24):                     foreach my $item (@ca_settings) {
                   6814:-24):                         if (exists($info{$item})) {
                   6815:-24):                             my $name = $item;
                   6816:-24):                             if ($item eq 'authoreditors') {
                   6817:-24):                                 $name = 'editors';
                   6818:-24):                             }
                   6819:-24):                             $coauthorenv{"environment.internal.$name.$area"} = $info{$item};
                   6820:-24):                         }
                   6821:-24):                     }
                   6822:-24):                 }
                   6823:-24):             }
1.1169    droeschl 6824:         }
                   6825: 
                   6826:         my $cid = $tdomain.'_'.$trest;
                   6827:         unless ($firstaccchk{$cid}) {
                   6828:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6829:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6830:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6831:                         $coursetimerstarts{$cid}{$item}; 
                   6832:                 }
                   6833:             }
                   6834:             $firstaccchk{$cid} = 1;
                   6835:         }
                   6836:         unless ($timerintchk{$cid}) {
                   6837:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6838:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6839:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6840:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6841:                 }
1.12      www      6842:             }
1.1169    droeschl 6843:             $timerintchk{$cid} = 1;
1.191     harris41 6844:         }
1.11      www      6845:     }
1.1169    droeschl 6846: 
1.1172.2.91  raeburn  6847:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6848:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6849:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6850:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6851: 
1.1172.2.146.  .18(raeb 6852:-24):     return (\%userroles,\%firstaccenv,\%timerintenv,\%coauthorenv);
1.11      www      6853: }
                   6854: 
1.567     raeburn  6855: sub set_arearole {
1.1172.2.19  raeburn  6856:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6857:     unless ($nolog) {
1.567     raeburn  6858: # log the associated role with the area
1.1172.2.19  raeburn  6859:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6860:     }
1.743     albertel 6861:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6862: }
                   6863: 
                   6864: sub custom_roleprivs {
                   6865:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6866:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6867:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6868:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6869:         my ($rdummy,$roledef)=
                   6870:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6871:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6872:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6873:             if (defined($syspriv)) {
1.1043    raeburn  6874:                 if ($trest =~ /^$match_community$/) {
                   6875:                     $syspriv =~ s/bre\&S//; 
                   6876:                 }
1.567     raeburn  6877:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6878:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6879:             }
                   6880:             if ($tdomain ne '') {
                   6881:                 if (defined($dompriv)) {
                   6882:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6883:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6884:                 }
                   6885:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6886:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6887:                         my $rolename = $1;
                   6888:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6889:                     }
1.567     raeburn  6890:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6891:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6892:                 }
                   6893:             }
                   6894:         }
                   6895:     }
                   6896: }
                   6897: 
1.1172.2.89  raeburn  6898: sub course_adhocrole_privs {
                   6899:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6900:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6901:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6902:         my (%currprivs,%storeprivs);
                   6903:         foreach my $item (split(/:/,$coursepriv)) {
                   6904:             my ($priv,$restrict) = split(/\&/,$item);
                   6905:             $currprivs{$priv} = $restrict;
                   6906:         }
                   6907:         my (%possadd,%possremove,%full);
                   6908:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6909:             my ($priv,$restrict)=split(/\&/,$item);
                   6910:             $full{$priv} = $restrict;
                   6911:         }
                   6912:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
1.1172.2.146.  .6(raebu 6913:22):             next if ($item eq '');
                   6914:22):             my ($rule,$rest) = split(/=/,$item);
                   6915:22):             next unless (($rule eq 'off') || ($rule eq 'on'));
                   6916:22):             foreach my $priv (split(/:/,$rest)) {
                   6917:22):                 if ($priv ne '') {
                   6918:22):                     if ($rule eq 'off') {
                   6919:22):                         $possremove{$priv} = 1;
                   6920:22):                     } else {
                   6921:22):                         $possadd{$priv} = 1;
                   6922:22):                     }
                   6923:22):                 }
                   6924:22):             }
                   6925:22):         }
                   6926:22):         foreach my $priv (sort(keys(%full))) {
                   6927:22):             if (exists($currprivs{$priv})) {
                   6928:22):                 unless (exists($possremove{$priv})) {
                   6929:22):                     $storeprivs{$priv} = $currprivs{$priv};
                   6930:22):                 }
                   6931:22):             } elsif (exists($possadd{$priv})) {
                   6932:22):                 $storeprivs{$priv} = $full{$priv};
                   6933:22):             }
                   6934:22):         }
                   6935:22):         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6936:22):     }
                   6937:22):     return $coursepriv;
1.1172.2.89  raeburn  6938: }
                   6939: 
1.678     raeburn  6940: sub group_roleprivs {
                   6941:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6942:     my $access = 1;
                   6943:     my $now = time;
                   6944:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6945:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6946:     if ($access) {
1.811     albertel 6947:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6948:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6949:     }
                   6950: }
1.567     raeburn  6951: 
                   6952: sub standard_roleprivs {
                   6953:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6954:     if (defined($pr{$trole.':s'})) {
                   6955:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6956:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6957:     }
                   6958:     if ($tdomain ne '') {
                   6959:         if (defined($pr{$trole.':d'})) {
                   6960:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6961:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6962:         }
                   6963:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6964:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6965:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6966:         }
                   6967:     }
                   6968: }
                   6969: 
                   6970: sub set_userprivs {
1.1064    raeburn  6971:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6972:     my $author=0;
                   6973:     my $adv=0;
1.1172.2.91  raeburn  6974:     my $rar=0;
1.678     raeburn  6975:     my %grouproles = ();
                   6976:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6977:         my @groupkeys; 
1.1000    raeburn  6978:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6979:             push(@groupkeys,$role);
                   6980:         }
                   6981:         if (ref($groups_roles) eq 'HASH') {
                   6982:             foreach my $key (keys(%{$groups_roles})) {
                   6983:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6984:                     push(@groupkeys,$key);
                   6985:                 }
                   6986:             }
                   6987:         }
                   6988:         if (@groupkeys > 0) {
                   6989:             foreach my $role (@groupkeys) {
                   6990:                 my ($trole,$area,$sec,$extendedarea);
                   6991:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6992:                     $trole = $1;
                   6993:                     $area = $2;
                   6994:                     $sec = $3;
                   6995:                     $extendedarea = $area.$sec;
                   6996:                     if (exists($$allgroups{$area})) {
                   6997:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6998:                             my $spec = $trole.'.'.$extendedarea;
                   6999:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  7000:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  7001:                         }
1.678     raeburn  7002:                     }
                   7003:                 }
                   7004:             }
                   7005:         }
                   7006:     }
1.800     albertel 7007:     foreach my $group (keys(%grouproles)) {
                   7008:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  7009:     }
1.800     albertel 7010:     foreach my $role (keys(%{$allroles})) {
                   7011:         my %thesepriv;
1.941     raeburn  7012:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 7013:         foreach my $item (split(/:/,$$allroles{$role})) {
                   7014:             if ($item ne '') {
                   7015:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  7016:                 if ($restrictions eq '') {
                   7017:                     $thesepriv{$privilege}='F';
                   7018:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   7019:                     $thesepriv{$privilege}.=$restrictions;
                   7020:                 }
                   7021:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  7022:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  7023:             }
                   7024:         }
                   7025:         my $thesestr='';
1.1104    raeburn  7026:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 7027: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   7028: 	}
                   7029:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  7030:     }
1.1172.2.91  raeburn  7031:     return ($author,$adv,$rar);
1.567     raeburn  7032: }
                   7033: 
1.994     raeburn  7034: sub role_status {
1.1104    raeburn  7035:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  7036:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  7037:         my ($one,$two) = split(m{\./},$rolekey,2);
                   7038:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  7039:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  7040:             $$where = '/'.$two;
1.994     raeburn  7041:             $$trolecode=$$role.'.'.$$where;
                   7042:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   7043:             $$tstatus='is';
1.1104    raeburn  7044:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  7045:                 $$tstatus='future';
1.1034    raeburn  7046:                 if ($$tstart<$now) {
                   7047:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  7048:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  7049:                             my (%allroles,%allgroups,$group_privs,
                   7050:                                 %groups_roles,@rolecodes);
1.1002    raeburn  7051:                             my %userroles = (
                   7052:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   7053:                             );
1.1064    raeburn  7054:                             @rolecodes = ('cm'); 
1.1002    raeburn  7055:                             my $spec=$$role.'.'.$$where;
                   7056:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   7057:                             if ($$role =~ /^cr\//) {
                   7058:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  7059:                                 push(@rolecodes,'cr');
1.1002    raeburn  7060:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  7061:                                 push(@rolecodes,$$role);
1.1002    raeburn  7062:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   7063:                                                     $env{'user.name'});
1.1064    raeburn  7064:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  7065:                                 (undef,my $group_privs) = split(/\//,$trole);
                   7066:                                 $group_privs = &unescape($group_privs);
                   7067:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  7068:                                 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  7069:                                 &get_groups_roles($tdomain,$trest,
                   7070:                                                   \%course_roles,\@rolecodes,
                   7071:                                                   \%groups_roles);
1.1002    raeburn  7072:                             } else {
1.1064    raeburn  7073:                                 push(@rolecodes,$$role);
1.1002    raeburn  7074:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   7075:                             }
1.1172.2.91  raeburn  7076:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   7077:                                                                    \%groups_roles);
1.1064    raeburn  7078:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  7079:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  7080:                         }
                   7081:                     }
1.1034    raeburn  7082:                     $$tstatus = 'is';
1.1002    raeburn  7083:                 }
1.994     raeburn  7084:             }
                   7085:             if ($$tend) {
1.1104    raeburn  7086:                 if ($$tend<$update) {
1.994     raeburn  7087:                     $$tstatus='expired';
                   7088:                 } elsif ($$tend<$now) {
                   7089:                     $$tstatus='will_not';
                   7090:                 }
                   7091:             }
                   7092:         }
                   7093:     }
                   7094: }
                   7095: 
1.1104    raeburn  7096: sub get_groups_roles {
                   7097:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   7098:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   7099:                   (ref($rolecodes) eq 'ARRAY') && 
                   7100:                   (ref($groups_roles) eq 'HASH')); 
                   7101:     if (keys(%{$cdom_courseroles}) > 0) {
                   7102:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   7103:         if ($cdom ne '' && $cnum ne '') {
                   7104:             foreach my $key (keys(%{$cdom_courseroles})) {
                   7105:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   7106:                     my $crsrole = $1;
                   7107:                     my $crssec = $2;
                   7108:                     if ($crsrole =~ /^cr/) {
                   7109:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   7110:                             push(@{$rolecodes},'cr');
                   7111:                         }
                   7112:                     } else {
                   7113:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   7114:                             push(@{$rolecodes},$crsrole);
                   7115:                         }
                   7116:                     }
                   7117:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   7118:                     if ($crssec ne '') {
                   7119:                         $rolekey .= "/$crssec";
                   7120:                     }
                   7121:                     $rolekey .= './';
                   7122:                     $groups_roles->{$rolekey} = $rolecodes;
                   7123:                 }
                   7124:             }
                   7125:         }
                   7126:     }
                   7127:     return;
                   7128: }
                   7129: 
                   7130: sub delete_env_groupprivs {
                   7131:     my ($where,$courseroles,$possroles) = @_;
                   7132:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   7133:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   7134:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   7135:         %{$courseroles->{$udom}} =
                   7136:             &get_my_roles('','','userroles',['active'],
                   7137:                           $possroles,[$udom],1);
                   7138:     }
                   7139:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   7140:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   7141:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   7142:             my $area = '/'.$cdom.'/'.$cnum;
                   7143:             my $privkey = "user.priv.$crsrole.$area";
                   7144:             if ($crssec ne '') {
                   7145:                 $privkey .= '/'.$crssec;
                   7146:             }
                   7147:             $privkey .= ".$area/$group";
                   7148:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   7149:         }
                   7150:     }
                   7151:     return;
                   7152: }
                   7153: 
1.994     raeburn  7154: sub check_adhoc_privs {
1.1172.2.86  raeburn  7155:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  7156:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  7157:     if ($sec) {
                   7158:         $cckey .= '/'.$sec;
                   7159:     }
1.1172.2.9  raeburn  7160:     my $setprivs;
1.994     raeburn  7161:     if ($env{$cckey}) {
                   7162:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  7163:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  7164:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  7165:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  7166:             $setprivs = 1;
1.994     raeburn  7167:         }
                   7168:     } else {
1.1172.2.87  raeburn  7169:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  7170:         $setprivs = 1;
1.994     raeburn  7171:     }
1.1172.2.9  raeburn  7172:     return $setprivs;
1.994     raeburn  7173: }
                   7174: 
                   7175: sub set_adhoc_privileges {
1.1172.2.84  raeburn  7176: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  7177:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  7178:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  7179:     if ($sec ne '') {
                   7180:         $area .= '/'.$sec;
                   7181:     }
1.994     raeburn  7182:     my $spec = $role.'.'.$area;
                   7183:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  7184:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  7185:     my %rolehash = ();
1.1172.2.89  raeburn  7186:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   7187:         my $rolename = $1;
1.1172.2.84  raeburn  7188:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  7189:         my %domdef = &get_domain_defaults($dcdom);
                   7190:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   7191:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   7192:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   7193:             }
                   7194:         }
1.1172.2.84  raeburn  7195:     } else {
                   7196:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   7197:     }
1.1172.2.91  raeburn  7198:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  7199:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  7200:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1172.2.146.  .1(raebu 7201:22):     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   7202:22):             ($caller eq 'tiny')) {
1.1088    raeburn  7203:         &appenv( {'request.role'        => $spec,
                   7204:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  7205:                   'request.course.sec'  => $sec, 
1.1088    raeburn  7206:                  }
                   7207:                );
                   7208:         my $tadv=0;
                   7209:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   7210:         &appenv({'request.role.adv'    => $tadv});
                   7211:     }
1.994     raeburn  7212: }
                   7213: 
1.12      www      7214: # --------------------------------------------------------------- get interface
                   7215: 
                   7216: sub get {
1.131     albertel 7217:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7218:    my $items='';
1.800     albertel 7219:    foreach my $item (@$storearr) {
                   7220:        $items.=&escape($item).'&';
1.191     harris41 7221:    }
1.12      www      7222:    $items=~s/\&$//;
1.620     albertel 7223:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7224:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 7225:    my $uhome=&homeserver($uname,$udomain);
                   7226: 
1.133     albertel 7227:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7228:    my @pairs=split(/\&/,$rep);
1.273     albertel 7229:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   7230:      return @pairs;
                   7231:    }
1.15      www      7232:    my %returnhash=();
1.42      www      7233:    my $i=0;
1.800     albertel 7234:    foreach my $item (@$storearr) {
                   7235:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7236:       $i++;
1.191     harris41 7237:    }
1.15      www      7238:    return %returnhash;
1.27      www      7239: }
                   7240: 
                   7241: # --------------------------------------------------------------- del interface
                   7242: 
                   7243: sub del {
1.133     albertel 7244:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      7245:    my $items='';
1.800     albertel 7246:    foreach my $item (@$storearr) {
                   7247:        $items.=&escape($item).'&';
1.191     harris41 7248:    }
1.984     neumanie 7249: 
1.27      www      7250:    $items=~s/\&$//;
1.620     albertel 7251:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7252:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7253:    my $uhome=&homeserver($uname,$udomain);
                   7254:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7255: }
                   7256: 
                   7257: # -------------------------------------------------------------- dump interface
                   7258: 
1.1172.2.22  raeburn  7259: sub unserialize {
                   7260:     my ($rep, $escapedkeys) = @_;
                   7261: 
                   7262:     return {} if $rep =~ /^error/;
                   7263: 
                   7264:     my %returnhash=();
                   7265:     foreach my $item (split(/\&/,$rep)) {
                   7266:         my ($key, $value) = split(/=/, $item, 2);
                   7267:         $key = unescape($key) unless $escapedkeys;
                   7268:         next if $key =~ /^error: 2 /;
                   7269:         $returnhash{$key} = &thaw_unescape($value);
                   7270:     }
                   7271:     return \%returnhash;
                   7272: }
                   7273: 
                   7274: # see Lond::dump_with_regexp
                   7275: # if $escapedkeys hash keys won't get unescaped.
1.15      www      7276: sub dump {
1.1172.2.146.  .1(raebu 7277:22):     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755     albertel 7278:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7279:     if (!$uname) { $uname=$env{'user.name'}; }
                   7280:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 7281: 
1.1172.2.55  raeburn  7282:     if ($regexp) {
                   7283:         $regexp=&escape($regexp);
                   7284:     } else {
                   7285:         $regexp='.';
                   7286:     }
1.1172.2.22  raeburn  7287:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   7288:         # user is hosted on this machine
1.1172.2.55  raeburn  7289:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  7290:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  7291:         return %{&unserialize($reply, $escapedkeys)};
                   7292:     }
1.1172.2.146.  .1(raebu 7293:22):     my $rep;
                   7294:22):     if ($encrypt) {
                   7295:22):         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7296:22):     } else {
                   7297:22):         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7298:22):     }
1.755     albertel 7299:     my @pairs=split(/\&/,$rep);
                   7300:     my %returnhash=();
1.1098    foxr     7301:     if (!($rep =~ /^error/ )) {
                   7302: 	foreach my $item (@pairs) {
                   7303: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  7304:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     7305: 	    next if ($key =~ /^error: 2 /);
                   7306: 	    $returnhash{$key}=&thaw_unescape($value);
                   7307: 	}
1.755     albertel 7308:     }
                   7309:     return %returnhash;
1.407     www      7310: }
                   7311: 
1.1098    foxr     7312: 
1.717     albertel 7313: # --------------------------------------------------------- dumpstore interface
                   7314: 
                   7315: sub dumpstore {
                   7316:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  7317:    # same as dump but keys must be escaped. They may contain colon separated
                   7318:    # lists of values that may themself contain colons (e.g. symbs).
                   7319:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7320: }
                   7321: 
1.407     www      7322: # -------------------------------------------------------------- keys interface
                   7323: 
                   7324: sub getkeys {
                   7325:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7326:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7327:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7328:    my $uhome=&homeserver($uname,$udomain);
                   7329:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7330:    my @keyarray=();
1.800     albertel 7331:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7332:       next if ($key =~ /^error: 2 /);
1.800     albertel 7333:       push(@keyarray,&unescape($key));
1.407     www      7334:    }
                   7335:    return @keyarray;
1.318     matthew  7336: }
                   7337: 
1.319     matthew  7338: # --------------------------------------------------------------- currentdump
                   7339: sub currentdump {
1.328     matthew  7340:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7341:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7342:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7343:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7344:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  7345:    my $rep;
                   7346: 
                   7347:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7348:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   7349:                    $courseid)));
                   7350:    } else {
                   7351:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7352:    }
                   7353: 
1.318     matthew  7354:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7355:    #
1.318     matthew  7356:    my %returnhash=();
1.319     matthew  7357:    #
                   7358:    if ($rep eq "unknown_cmd") { 
                   7359:        # an old lond will not know currentdump
                   7360:        # Do a dump and make it look like a currentdump
1.822     albertel 7361:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7362:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7363:        my %hash = @tmp;
                   7364:        @tmp=();
1.424     matthew  7365:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7366:    } else {
                   7367:        my @pairs=split(/\&/,$rep);
1.800     albertel 7368:        foreach my $pair (@pairs) {
                   7369:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7370:            my ($symb,$param) = split(/:/,$key);
                   7371:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7372:                                                         &thaw_unescape($value);
1.319     matthew  7373:        }
1.191     harris41 7374:    }
1.12      www      7375:    return %returnhash;
1.424     matthew  7376: }
                   7377: 
                   7378: sub convert_dump_to_currentdump{
                   7379:     my %hash = %{shift()};
                   7380:     my %returnhash;
                   7381:     # Code ripped from lond, essentially.  The only difference
                   7382:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7383:     # we might run in to problems with parameter names =~ /^v\./
                   7384:     while (my ($key,$value) = each(%hash)) {
                   7385:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7386: 	$symb  = &unescape($symb);
                   7387: 	$param = &unescape($param);
1.424     matthew  7388:         next if ($v eq 'version' || $symb eq 'keys');
                   7389:         next if (exists($returnhash{$symb}) &&
                   7390:                  exists($returnhash{$symb}->{$param}) &&
                   7391:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7392:         $returnhash{$symb}->{$param}=$value;
                   7393:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7394:     }
                   7395:     #
                   7396:     # Remove all of the keys in the hashes which keep track of
                   7397:     # the version of the parameter.
                   7398:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7399:         # use a foreach because we are going to delete from the hash.
                   7400:         foreach my $key (keys(%$param_hash)) {
                   7401:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7402:         }
                   7403:     }
                   7404:     return \%returnhash;
1.12      www      7405: }
                   7406: 
1.627     albertel 7407: # ------------------------------------------------------ critical inc interface
                   7408: 
                   7409: sub cinc {
                   7410:     return &inc(@_,'critical');
                   7411: }
                   7412: 
1.449     matthew  7413: # --------------------------------------------------------------- inc interface
                   7414: 
                   7415: sub inc {
1.627     albertel 7416:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7417:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7418:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7419:     my $uhome=&homeserver($uname,$udomain);
                   7420:     my $items='';
                   7421:     if (! ref($store)) {
                   7422:         # got a single value, so use that instead
                   7423:         $items = &escape($store).'=&';
                   7424:     } elsif (ref($store) eq 'SCALAR') {
                   7425:         $items = &escape($$store).'=&';        
                   7426:     } elsif (ref($store) eq 'ARRAY') {
                   7427:         $items = join('=&',map {&escape($_);} @{$store});
                   7428:     } elsif (ref($store) eq 'HASH') {
                   7429:         while (my($key,$value) = each(%{$store})) {
                   7430:             $items.= &escape($key).'='.&escape($value).'&';
                   7431:         }
                   7432:     }
                   7433:     $items=~s/\&$//;
1.627     albertel 7434:     if ($critical) {
                   7435: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7436:     } else {
                   7437: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7438:     }
1.449     matthew  7439: }
                   7440: 
1.12      www      7441: # --------------------------------------------------------------- put interface
                   7442: 
                   7443: sub put {
1.1172.2.146.  .1(raebu 7444:22):    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620     albertel 7445:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7446:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7447:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7448:    my $items='';
1.800     albertel 7449:    foreach my $item (keys(%$storehash)) {
                   7450:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7451:    }
1.12      www      7452:    $items=~s/\&$//;
1.1172.2.146.  .1(raebu 7453:22):    if ($encrypt) {
                   7454:22):        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
                   7455:22):    } else {
                   7456:22):        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   7457:22):    }
1.47      www      7458: }
                   7459: 
1.631     albertel 7460: # ------------------------------------------------------------ newput interface
                   7461: 
                   7462: sub newput {
                   7463:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7464:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7465:    if (!$uname) { $uname=$env{'user.name'}; }
                   7466:    my $uhome=&homeserver($uname,$udomain);
                   7467:    my $items='';
                   7468:    foreach my $key (keys(%$storehash)) {
                   7469:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7470:    }
                   7471:    $items=~s/\&$//;
                   7472:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7473: }
                   7474: 
                   7475: # ---------------------------------------------------------  putstore interface
                   7476: 
1.524     raeburn  7477: sub putstore {
1.1172.2.59  raeburn  7478:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7479:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7480:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7481:    my $uhome=&homeserver($uname,$udomain);
                   7482:    my $items='';
1.715     albertel 7483:    foreach my $key (keys(%$storehash)) {
                   7484:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7485:    }
1.715     albertel 7486:    $items=~s/\&$//;
1.716     albertel 7487:    my $esc_symb=&escape($symb);
                   7488:    my $esc_v=&escape($version);
1.715     albertel 7489:    my $reply =
1.716     albertel 7490:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7491: 	      $uhome);
1.1172.2.59  raeburn  7492:    if (($tolog) && ($reply eq 'ok')) {
                   7493:        my $namevalue='';
                   7494:        foreach my $key (keys(%{$storehash})) {
                   7495:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7496:        }
1.1172.2.134  raeburn  7497:        my $ip = &get_requestor_ip();
1.1172.2.135  raeburn  7498:        $namevalue .= 'ip='.&escape($ip).
1.1172.2.59  raeburn  7499:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7500:                      '&version='.$esc_v.
                   7501:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7502:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7503:    }
1.715     albertel 7504:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7505:        # gfall back to way things use to be done
1.715     albertel 7506:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7507: 			    $uname);
1.524     raeburn  7508:    }
1.715     albertel 7509:    return $reply;
                   7510: }
                   7511: 
                   7512: sub old_putstore {
1.716     albertel 7513:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7514:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7515:     if (!$uname) { $uname=$env{'user.name'}; }
                   7516:     my $uhome=&homeserver($uname,$udomain);
                   7517:     my %newstorehash;
1.800     albertel 7518:     foreach my $item (keys(%$storehash)) {
                   7519: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7520: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7521:     }
                   7522:     my $items='';
                   7523:     my %allitems = ();
1.800     albertel 7524:     foreach my $item (keys(%newstorehash)) {
                   7525: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7526: 	    my $key = $1.':keys:'.$2;
                   7527: 	    $allitems{$key} .= $3.':';
                   7528: 	}
1.800     albertel 7529: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7530:     }
1.800     albertel 7531:     foreach my $item (keys(%allitems)) {
                   7532: 	$allitems{$item} =~ s/\:$//;
                   7533: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7534:     }
                   7535:     $items=~s/\&$//;
                   7536:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7537: }
                   7538: 
1.47      www      7539: # ------------------------------------------------------ critical put interface
                   7540: 
                   7541: sub cput {
1.134     albertel 7542:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7543:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7544:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7545:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7546:    my $items='';
1.800     albertel 7547:    foreach my $item (keys(%$storehash)) {
                   7548:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7549:    }
1.47      www      7550:    $items=~s/\&$//;
1.134     albertel 7551:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7552: }
                   7553: 
                   7554: # -------------------------------------------------------------- eget interface
                   7555: 
                   7556: sub eget {
1.133     albertel 7557:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7558:    my $items='';
1.800     albertel 7559:    foreach my $item (@$storearr) {
                   7560:        $items.=&escape($item).'&';
1.191     harris41 7561:    }
1.12      www      7562:    $items=~s/\&$//;
1.620     albertel 7563:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7564:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7565:    my $uhome=&homeserver($uname,$udomain);
                   7566:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7567:    my @pairs=split(/\&/,$rep);
                   7568:    my %returnhash=();
1.42      www      7569:    my $i=0;
1.800     albertel 7570:    foreach my $item (@$storearr) {
                   7571:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7572:       $i++;
1.191     harris41 7573:    }
1.12      www      7574:    return %returnhash;
                   7575: }
                   7576: 
1.667     albertel 7577: # ------------------------------------------------------------ tmpput interface
                   7578: sub tmpput {
1.802     raeburn  7579:     my ($storehash,$server,$context)=@_;
1.667     albertel 7580:     my $items='';
1.800     albertel 7581:     foreach my $item (keys(%$storehash)) {
                   7582: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7583:     }
                   7584:     $items=~s/\&$//;
1.802     raeburn  7585:     if (defined($context)) {
                   7586:         $items .= ':'.&escape($context);
                   7587:     }
1.667     albertel 7588:     return &reply("tmpput:$items",$server);
                   7589: }
                   7590: 
                   7591: # ------------------------------------------------------------ tmpget interface
                   7592: sub tmpget {
1.688     albertel 7593:     my ($token,$server)=@_;
                   7594:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7595:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7596:     my %returnhash;
1.1172.2.85  raeburn  7597:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7598:         return %returnhash;
                   7599:     }
1.667     albertel 7600:     foreach my $item (split(/\&/,$rep)) {
                   7601: 	my ($key,$value)=split(/=/,$item);
                   7602: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7603:     }
                   7604:     return %returnhash;
                   7605: }
                   7606: 
1.1113    raeburn  7607: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7608: sub tmpdel {
                   7609:     my ($token,$server)=@_;
                   7610:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7611:     return &reply("tmpdel:$token",$server);
                   7612: }
                   7613: 
1.1172.2.13  raeburn  7614: # ------------------------------------------------------------ get_timebased_id
                   7615: 
                   7616: sub get_timebased_id {
                   7617:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7618:         $maxtries) = @_;
                   7619:     my ($newid,$error,$dellock);
                   7620:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7621:         return ('','ok','invalid call to get suffix');
                   7622:     }
                   7623: 
                   7624: # set defaults for any optional args for which values were not supplied
                   7625:     if ($who eq '') {
                   7626:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7627:     }
                   7628:     if (!$locktries) {
                   7629:         $locktries = 3;
                   7630:     }
                   7631:     if (!$maxtries) {
                   7632:         $maxtries = 10;
                   7633:     }
                   7634: 
                   7635:     if (($cdom eq '') || ($cnum eq '')) {
                   7636:         if ($env{'request.course.id'}) {
                   7637:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7638:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7639:         }
                   7640:         if (($cdom eq '') || ($cnum eq '')) {
                   7641:             return ('','ok','call to get suffix not in course context');
                   7642:         }
                   7643:     }
                   7644: 
                   7645: # construct locking item
                   7646:     my $lockhash = {
                   7647:                       $prefix."\0".'locked_'.$keyid => $who,
                   7648:                    };
                   7649:     my $tries = 0;
                   7650: 
                   7651: # attempt to get lock on nohist_$namespace file
                   7652:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7653:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7654:         $tries ++;
                   7655:         sleep 1;
                   7656:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7657:     }
                   7658: 
                   7659: # attempt to get unique identifier, based on current timestamp
                   7660:     if ($gotlock eq 'ok') {
                   7661:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7662:         my $id = time;
                   7663:         $newid = $id;
1.1172.2.56  raeburn  7664:         if ($idtype eq 'addcode') {
                   7665:             $newid .= &sixnum_code();
                   7666:         }
1.1172.2.13  raeburn  7667:         my $idtries = 0;
                   7668:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7669:             if ($idtype eq 'concat') {
                   7670:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7671:             } elsif ($idtype eq 'addcode') {
                   7672:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7673:             } else {
                   7674:                 $newid ++;
                   7675:             }
                   7676:             $idtries ++;
                   7677:         }
                   7678:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7679:             my %new_item =  (
                   7680:                               $prefix."\0".$newid => $who,
                   7681:                             );
                   7682:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7683:                                                  $cdom,$cnum);
                   7684:             if ($putresult ne 'ok') {
                   7685:                 undef($newid);
                   7686:                 $error = 'error saving new item: '.$putresult;
                   7687:             }
                   7688:         } else {
1.1172.2.56  raeburn  7689:              undef($newid);
1.1172.2.13  raeburn  7690:              $error = ('error: no unique suffix available for the new item ');
                   7691:         }
                   7692: #  remove lock
                   7693:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7694:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7695:     } else {
                   7696:         $error = "error: could not obtain lockfile\n";
                   7697:         $dellock = 'ok';
1.1172.2.58  raeburn  7698:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7699:             $dellock = 'nolock';
                   7700:         }
1.1172.2.13  raeburn  7701:     }
                   7702:     return ($newid,$dellock,$error);
                   7703: }
                   7704: 
1.1172.2.56  raeburn  7705: sub sixnum_code {
                   7706:     my $code;
                   7707:     for (0..6) {
                   7708:         $code .= int( rand(9) );
                   7709:     }
                   7710:     return $code;
                   7711: }
                   7712: 
1.765     albertel 7713: # -------------------------------------------------- portfolio access checking
                   7714: 
                   7715: sub portfolio_access {
1.1172.2.77  raeburn  7716:     my ($requrl,$clientip) = @_;
1.765     albertel 7717:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7718:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7719:     if ($result) {
                   7720:         my %setters;
                   7721:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142  raeburn  7722:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7723:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
                   7724:             if (($startblock && $endblock) || ($by_ip))  {
1.814     raeburn  7725:                 return 'B';
                   7726:             }
                   7727:         } else {
1.1172.2.142  raeburn  7728:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
                   7729:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7730:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7731:                 return 'B';
                   7732:             }
                   7733:         }
                   7734:     }
1.765     albertel 7735:     if ($result eq 'ok') {
1.766     albertel 7736:        return 'F';
1.765     albertel 7737:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7738:        return 'A';
1.765     albertel 7739:     }
1.766     albertel 7740:     return '';
1.765     albertel 7741: }
                   7742: 
                   7743: sub get_portfolio_access {
1.1172.2.77  raeburn  7744:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7745: 
                   7746:     if (!ref($access_hash)) {
                   7747: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7748: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7749: 						   $file_name);
                   7750: 	$access_hash = $access_controls{$file_name};
                   7751:     }
                   7752: 
1.1172.2.77  raeburn  7753:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7754:     my $now = time;
                   7755:     if (ref($access_hash) eq 'HASH') {
                   7756:         foreach my $key (keys(%{$access_hash})) {
                   7757:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7758:             if ($start > $now) {
                   7759:                 next;
                   7760:             }
                   7761:             if ($end && $end<$now) {
                   7762:                 next;
                   7763:             }
                   7764:             if ($scope eq 'public') {
                   7765:                 $public = $key;
                   7766:                 last;
                   7767:             } elsif ($scope eq 'guest') {
                   7768:                 $guest = $key;
                   7769:             } elsif ($scope eq 'domains') {
                   7770:                 push(@domains,$key);
                   7771:             } elsif ($scope eq 'users') {
                   7772:                 push(@users,$key);
                   7773:             } elsif ($scope eq 'course') {
                   7774:                 push(@courses,$key);
                   7775:             } elsif ($scope eq 'group') {
                   7776:                 push(@groups,$key);
1.1172.2.77  raeburn  7777:             } elsif ($scope eq 'ip') {
                   7778:                 push(@ips,$key);
1.765     albertel 7779:             }
                   7780:         }
                   7781:         if ($public) {
                   7782:             return 'ok';
1.1172.2.77  raeburn  7783:         } elsif (@ips > 0) {
                   7784:             my $allowed;
                   7785:             foreach my $ipkey (@ips) {
                   7786:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7787:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7788:                         $allowed = 1;
                   7789:                         last;
                   7790:                     }
                   7791:                 }
                   7792:             }
                   7793:             if ($allowed) {
                   7794:                 return 'ok';
                   7795:             }
1.765     albertel 7796:         }
                   7797:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7798:             if ($guest) {
                   7799:                 return $guest;
                   7800:             }
                   7801:         } else {
                   7802:             if (@domains > 0) {
                   7803:                 foreach my $domkey (@domains) {
                   7804:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7805:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7806:                             return 'ok';
                   7807:                         }
                   7808:                     }
                   7809:                 }
                   7810:             }
                   7811:             if (@users > 0) {
                   7812:                 foreach my $userkey (@users) {
1.865     raeburn  7813:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7814:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7815:                             if (ref($item) eq 'HASH') {
                   7816:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7817:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7818:                                     return 'ok';
                   7819:                                 }
                   7820:                             }
                   7821:                         }
                   7822:                     } 
1.765     albertel 7823:                 }
                   7824:             }
                   7825:             my %roleshash;
                   7826:             my @courses_and_groups = @courses;
                   7827:             push(@courses_and_groups,@groups); 
                   7828:             if (@courses_and_groups > 0) {
                   7829:                 my (%allgroups,%allroles); 
                   7830:                 my ($start,$end,$role,$sec,$group);
                   7831:                 foreach my $envkey (%env) {
1.1060    raeburn  7832:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7833:                         my $cid = $2.'_'.$3; 
                   7834:                         if ($1 eq 'gr') {
                   7835:                             $group = $4;
                   7836:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7837:                         } else {
                   7838:                             if ($4 eq '') {
                   7839:                                 $sec = 'none';
                   7840:                             } else {
                   7841:                                 $sec = $4;
                   7842:                             }
                   7843:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7844:                         }
1.811     albertel 7845:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7846:                         my $cid = $2.'_'.$3;
                   7847:                         if ($4 eq '') {
                   7848:                             $sec = 'none';
                   7849:                         } else {
                   7850:                             $sec = $4;
                   7851:                         }
                   7852:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7853:                     }
                   7854:                 }
                   7855:                 if (keys(%allroles) == 0) {
                   7856:                     return;
                   7857:                 }
                   7858:                 foreach my $key (@courses_and_groups) {
                   7859:                     my %content = %{$$access_hash{$key}};
                   7860:                     my $cnum = $content{'number'};
                   7861:                     my $cdom = $content{'domain'};
                   7862:                     my $cid = $cdom.'_'.$cnum;
                   7863:                     if (!exists($allroles{$cid})) {
                   7864:                         next;
                   7865:                     }    
                   7866:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7867:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7868:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7869:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7870:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7871:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7872:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7873:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7874:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7875:                                         if (grep/^all$/,@sections) {
                   7876:                                             return 'ok';
                   7877:                                         } else {
                   7878:                                             if (grep/^$sec$/,@sections) {
                   7879:                                                 return 'ok';
                   7880:                                             }
                   7881:                                         }
                   7882:                                     }
                   7883:                                 }
                   7884:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7885:                                     if (grep/^none$/,@groups) {
                   7886:                                         return 'ok';
                   7887:                                     }
                   7888:                                 } else {
                   7889:                                     if (grep/^all$/,@groups) {
                   7890:                                         return 'ok';
                   7891:                                     } 
                   7892:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7893:                                         if (grep/^$group$/,@groups) {
                   7894:                                             return 'ok';
                   7895:                                         }
                   7896:                                     }
                   7897:                                 } 
                   7898:                             }
                   7899:                         }
                   7900:                     }
                   7901:                 }
                   7902:             }
                   7903:             if ($guest) {
                   7904:                 return $guest;
                   7905:             }
                   7906:         }
                   7907:     }
                   7908:     return;
                   7909: }
                   7910: 
                   7911: sub course_group_datechecker {
                   7912:     my ($dates,$now,$status) = @_;
                   7913:     my ($start,$end) = split(/\./,$dates);
                   7914:     if (!$start && !$end) {
                   7915:         return 'ok';
                   7916:     }
                   7917:     if (grep/^active$/,@{$status}) {
                   7918:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7919:             return 'ok';
                   7920:         }
                   7921:     }
                   7922:     if (grep/^previous$/,@{$status}) {
                   7923:         if ($end > $now ) {
                   7924:             return 'ok';
                   7925:         }
                   7926:     }
                   7927:     if (grep/^future$/,@{$status}) {
                   7928:         if ($start > $now) {
                   7929:             return 'ok';
                   7930:         }
                   7931:     }
                   7932:     return; 
                   7933: }
                   7934: 
                   7935: sub parse_portfolio_url {
                   7936:     my ($url) = @_;
                   7937: 
                   7938:     my ($type,$udom,$unum,$group,$file_name);
                   7939:     
1.823     albertel 7940:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7941: 	$type = 1;
                   7942:         $udom = $1;
                   7943:         $unum = $2;
                   7944:         $file_name = $3;
1.823     albertel 7945:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7946: 	$type = 2;
                   7947:         $udom = $1;
                   7948:         $unum = $2;
                   7949:         $group = $3;
                   7950:         $file_name = $3.'/'.$4;
                   7951:     }
                   7952:     if (wantarray) {
                   7953: 	return ($type,$udom,$unum,$file_name,$group);
                   7954:     }
                   7955:     return $type;
                   7956: }
                   7957: 
                   7958: sub is_portfolio_url {
                   7959:     my ($url) = @_;
                   7960:     return scalar(&parse_portfolio_url($url));
                   7961: }
                   7962: 
1.798     raeburn  7963: sub is_portfolio_file {
                   7964:     my ($file) = @_;
1.820     raeburn  7965:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7966:         return 1;
                   7967:     }
                   7968:     return;
                   7969: }
                   7970: 
1.1172.2.146.  .13(raeb 7971:-23): sub is_coursetool_logo {
                   7972:-23):     my ($uri) = @_;
                   7973:-23):     if ($env{'request.course.id'}) {
                   7974:-23):         my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   7975:-23):         if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
                   7976:-23):             return 1;
                   7977:-23):         }
                   7978:-23):     }
                   7979:-23):     return;
                   7980:-23): }
                   7981:-23): 
1.976     raeburn  7982: sub usertools_access {
1.1084    raeburn  7983:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7984:     my ($access,%tools);
                   7985:     if ($context eq '') {
                   7986:         $context = 'tools';
                   7987:     }
                   7988:     if ($context eq 'requestcourses') {
                   7989:         %tools = (
                   7990:                       official   => 1,
                   7991:                       unofficial => 1,
1.1006    raeburn  7992:                       community  => 1,
1.1172.2.37  raeburn  7993:                       textbook   => 1,
1.1172.2.146.  .13(raeb 7994:-23):                       lti        => 1,
1.985     raeburn  7995:                  );
1.1172.2.9  raeburn  7996:     } elsif ($context eq 'requestauthor') {
                   7997:         %tools = (
                   7998:                       requestauthor => 1,
                   7999:                  );
1.1172.2.146.  .18(raeb 8000:-24):     } elsif ($context eq 'authordefaults') {
                   8001:-24):         %tools = (
                   8002:-24):                       webdav    => 1,
                   8003:-24):                  );
1.985     raeburn  8004:     } else {
                   8005:         %tools = (
                   8006:                       aboutme   => 1,
                   8007:                       blog      => 1,
                   8008:                       portfolio => 1,
1.1172.2.146.  .6(raebu 8009:22):                       timezone  => 1,
1.985     raeburn  8010:                  );
                   8011:     }
1.976     raeburn  8012:     return if (!defined($tools{$tool}));
                   8013: 
1.1172.2.35  raeburn  8014:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  8015:         $udom = $env{'user.domain'};
                   8016:         $uname = $env{'user.name'};
                   8017:     }
                   8018: 
1.978     raeburn  8019:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   8020:         if ($action ne 'reload') {
1.985     raeburn  8021:             if ($context eq 'requestcourses') {
                   8022:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  8023:             } elsif ($context eq 'requestauthor') {
                   8024:                 return $env{'environment.canrequest.author'};
1.1172.2.146.  .18(raeb 8025:-24):             } elsif ($context eq 'authordefaults') {
                   8026:-24):                 if ($tool eq 'webdav') {
                   8027:-24):                     return $env{'environment.availabletools.'.$tool};
                   8028:-24):                 }
1.985     raeburn  8029:             } else {
                   8030:                 return $env{'environment.availabletools.'.$tool};
                   8031:             }
                   8032:         }
1.976     raeburn  8033:     }
                   8034: 
1.1172.2.9  raeburn  8035:     my ($toolstatus,$inststatus,$envkey);
                   8036:     if ($context eq 'requestauthor') {
                   8037:         $envkey = $context;
1.1172.2.146.  .18(raeb 8038:-24):     } elsif ($context eq 'authordefaults') {
                   8039:-24):         if ($tool eq 'webdav') {
                   8040:-24):             $envkey = 'tools.'.$tool;
                   8041:-24):         }
1.1172.2.9  raeburn  8042:     } else {
                   8043:         $envkey = $context.'.'.$tool;
                   8044:     }
1.976     raeburn  8045: 
1.985     raeburn  8046:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8047:          ($action ne 'reload')) {
1.1172.2.9  raeburn  8048:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  8049:         $inststatus = $env{'environment.inststatus'};
                   8050:     } else {
1.1084    raeburn  8051:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  8052:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  8053:             $inststatus = $userenvref->{'inststatus'};
                   8054:         } else {
1.1172.2.9  raeburn  8055:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   8056:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  8057:             $inststatus = $userenv{'inststatus'};
                   8058:         }
1.976     raeburn  8059:     }
                   8060: 
                   8061:     if ($toolstatus ne '') {
                   8062:         if ($toolstatus) {
                   8063:             $access = 1;
                   8064:         } else {
                   8065:             $access = 0;
                   8066:         }
                   8067:         return $access;
                   8068:     }
                   8069: 
1.1084    raeburn  8070:     my ($is_adv,%domdef);
                   8071:     if (ref($is_advref) eq 'HASH') {
                   8072:         $is_adv = $is_advref->{'is_adv'};
                   8073:     } else {
                   8074:         $is_adv = &is_advanced_user($udom,$uname);
                   8075:     }
                   8076:     if (ref($domdefref) eq 'HASH') {
                   8077:         %domdef = %{$domdefref};
                   8078:     } else {
                   8079:         %domdef = &get_domain_defaults($udom);
                   8080:     }
1.976     raeburn  8081:     if (ref($domdef{$tool}) eq 'HASH') {
                   8082:         if ($is_adv) {
                   8083:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   8084:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   8085:                     $access = 1;
                   8086:                 } else {
                   8087:                     $access = 0;
                   8088:                 }
                   8089:                 return $access;
                   8090:             }
                   8091:         }
                   8092:         if ($inststatus ne '') {
                   8093:             my ($hasaccess,$hasnoaccess);
                   8094:             foreach my $affiliation (split(/:/,$inststatus)) {
                   8095:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   8096:                     if ($domdef{$tool}{$affiliation}) {
                   8097:                         $hasaccess = 1;
                   8098:                     } else {
                   8099:                         $hasnoaccess = 1;
                   8100:                     }
                   8101:                 }
                   8102:             }
                   8103:             if ($hasaccess || $hasnoaccess) {
                   8104:                 if ($hasaccess) {
                   8105:                     $access = 1;
                   8106:                 } elsif ($hasnoaccess) {
                   8107:                     $access = 0; 
                   8108:                 }
                   8109:                 return $access;
                   8110:             }
                   8111:         } else {
                   8112:             if ($domdef{$tool}{'default'} ne '') {
                   8113:                 if ($domdef{$tool}{'default'}) {
                   8114:                     $access = 1;
                   8115:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   8116:                     $access = 0;
                   8117:                 }
                   8118:                 return $access;
                   8119:             }
                   8120:         }
                   8121:     } else {
1.1172.2.6  raeburn  8122:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  8123:             $access = 1;
                   8124:         } else {
                   8125:             $access = 0;
                   8126:         }
1.976     raeburn  8127:         return $access;
                   8128:     }
                   8129: }
                   8130: 
1.1050    raeburn  8131: sub is_course_owner {
                   8132:     my ($cdom,$cnum,$udom,$uname) = @_;
                   8133:     if (($udom eq '') || ($uname eq '')) {
                   8134:         $udom = $env{'user.domain'};
                   8135:         $uname = $env{'user.name'};
                   8136:     }
                   8137:     unless (($udom eq '') || ($uname eq '')) {
                   8138:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   8139:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   8140:                 return 1;
                   8141:             } else {
                   8142:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   8143:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   8144:                     return 1;
                   8145:                 }
                   8146:             }
                   8147:         }
                   8148:     }
                   8149:     return;
                   8150: }
                   8151: 
1.976     raeburn  8152: sub is_advanced_user {
                   8153:     my ($udom,$uname) = @_;
1.1085    raeburn  8154:     if ($udom ne '' && $uname ne '') {
                   8155:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  8156:             if (wantarray) {
                   8157:                 return ($env{'user.adv'},$env{'user.author'});
                   8158:             } else {
                   8159:                 return $env{'user.adv'};
                   8160:             }
1.1085    raeburn  8161:         }
                   8162:     }
1.976     raeburn  8163:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   8164:     my %allroles;
1.1128    raeburn  8165:     my ($is_adv,$is_author);
1.976     raeburn  8166:     foreach my $role (keys(%roleshash)) {
                   8167:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   8168:         my $area = '/'.$tdomain.'/'.$trest;
                   8169:         if ($sec ne '') {
                   8170:             $area .= '/'.$sec;
                   8171:         }
                   8172:         if (($area ne '') && ($trole ne '')) {
                   8173:             my $spec=$trole.'.'.$area;
                   8174:             if ($trole =~ /^cr\//) {
                   8175:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   8176:             } elsif ($trole ne 'gr') {
                   8177:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   8178:             }
1.1128    raeburn  8179:             if ($trole eq 'au') {
                   8180:                 $is_author = 1;
                   8181:             }
1.976     raeburn  8182:         }
                   8183:     }
                   8184:     foreach my $role (keys(%allroles)) {
                   8185:         last if ($is_adv);
                   8186:         foreach my $item (split(/:/,$allroles{$role})) {
                   8187:             if ($item ne '') {
                   8188:                 my ($privilege,$restrictions)=split(/&/,$item);
                   8189:                 if ($privilege eq 'adv') {
                   8190:                     $is_adv = 1;
                   8191:                     last;
                   8192:                 }
                   8193:             }
                   8194:         }
                   8195:     }
1.1128    raeburn  8196:     if (wantarray) {
                   8197:         return ($is_adv,$is_author);
                   8198:     }
1.976     raeburn  8199:     return $is_adv;
                   8200: }
1.798     raeburn  8201: 
1.1035    raeburn  8202: sub check_can_request {
1.1172.2.146.  .13(raeb 8203:-23):     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  8204:     my $canreq = 0;
1.1172.2.146.  .13(raeb 8205:-23):     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8206:-23):         $uname = $env{'user.name'};
                   8207:-23):         $udom = $env{'user.domain'};
                   8208:-23):     }
1.1035    raeburn  8209:     my ($types,$typename) = &Apache::loncommon::course_types();
                   8210:     my @options = ('approval','validate','autolimit');
                   8211:     my $optregex = join('|',@options);
                   8212:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   8213:         foreach my $type (@{$types}) {
1.1172.2.146.  .13(raeb 8214:-23):             if (&usertools_access($uname,$udom,$type,undef,
                   8215:-23):                                   'requestcourses')) {
1.1035    raeburn  8216:                 $canreq ++;
1.1036    raeburn  8217:                 if (ref($request_domains) eq 'HASH') {
1.1172.2.146.  .13(raeb 8218:-23):                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  8219:                 }
1.1172.2.146.  .13(raeb 8220:-23):                 if ($dom eq $udom) {
1.1035    raeburn  8221:                     $can_request->{$type} = 1;
                   8222:                 }
                   8223:             }
1.1172.2.146.  .13(raeb 8224:-23):             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   8225:-23):                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  8226:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   8227:                 if (@curr > 0) {
1.1036    raeburn  8228:                     foreach my $item (@curr) {
                   8229:                         if (ref($request_domains) eq 'HASH') {
                   8230:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   8231:                             if ($otherdom ne '') {
                   8232:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   8233:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   8234:                                         push(@{$request_domains->{$type}},$otherdom);
                   8235:                                     }
                   8236:                                 } else {
                   8237:                                     push(@{$request_domains->{$type}},$otherdom);
                   8238:                                 }
                   8239:                             }
                   8240:                         }
                   8241:                     }
1.1172.2.146.  .13(raeb 8242:-23):                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  8243:                         $canreq ++;
1.1035    raeburn  8244:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   8245:                             $can_request->{$type} = 1;
                   8246:                         }
                   8247:                     }
                   8248:                 }
                   8249:             }
                   8250:         }
                   8251:     }
                   8252:     return $canreq;
                   8253: }
                   8254: 
1.341     www      8255: # ---------------------------------------------- Custom access rule evaluation
                   8256: 
                   8257: sub customaccess {
                   8258:     my ($priv,$uri)=@_;
1.807     albertel 8259:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      8260:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 8261:     $udom = &LONCAPA::clean_domain($udom);
                   8262:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      8263:     my $access=0;
1.800     albertel 8264:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 8265: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   8266: 	if ($type eq 'user') {
                   8267: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 8268: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 8269: 		if ($tdom) {
                   8270: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   8271: 		}
1.896     albertel 8272: 		if ($tuname) {
                   8273: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 8274: 		}
                   8275: 		$access=($effect eq 'allow');
                   8276: 		last;
                   8277: 	    }
                   8278: 	} else {
                   8279: 	    if ($role) {
                   8280: 		if ($role ne $urole) { next; }
                   8281: 	    }
                   8282: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   8283: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   8284: 		if ($tdom) {
                   8285: 		    if ($tdom ne $udom) { next; }
                   8286: 		}
                   8287: 		if ($tcrs) {
                   8288: 		    if ($tcrs ne $ucrs) { next; }
                   8289: 		}
                   8290: 		if ($tsec) {
                   8291: 		    if ($tsec ne $usec) { next; }
                   8292: 		}
                   8293: 		$access=($effect eq 'allow');
                   8294: 		last;
                   8295: 	    }
                   8296: 	    if ($realm eq '' && $role eq '') {
                   8297: 		$access=($effect eq 'allow');
                   8298: 	    }
1.402     bowersj2 8299: 	}
1.341     www      8300:     }
                   8301:     return $access;
                   8302: }
                   8303: 
1.103     harris41 8304: # ------------------------------------------------- Check for a user privilege
1.12      www      8305: 
                   8306: sub allowed {
1.1172.2.146.  .1(raebu 8307:22):     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705     albertel 8308:     my $ver_orguri=$uri;
1.439     www      8309:     $uri=&deversion($uri);
1.152     www      8310:     my $orguri=$uri;
1.52      www      8311:     $uri=&declutter($uri);
1.809     raeburn  8312: 
1.810     raeburn  8313:     if ($priv eq 'evb') {
1.1172.2.146.  .3(raebu 8314:22): # Evade communication block restrictions for specified role in a course or domain
1.810     raeburn  8315:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   8316:             return $1;
                   8317:         } else {
                   8318:             return;
                   8319:         }
                   8320:     }
                   8321: 
1.620     albertel 8322:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      8323: # Free bre access to adm and meta resources
1.1172.2.146.  .1(raebu 8324:22):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 8325: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   8326: 	&& ($priv eq 'bre')) {
1.14      www      8327: 	return 'F';
1.159     www      8328:     }
                   8329: 
1.545     banghart 8330: # Free bre access to user's own portfolio contents
1.714     raeburn  8331:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  8332:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  8333: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8334:         my %setters;
1.1172.2.142  raeburn  8335:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   8336:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   8337:         if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  8338:             return 'B';
                   8339:         } else {
                   8340:             return 'F';
                   8341:         }
1.545     banghart 8342:     }
                   8343: 
1.762     raeburn  8344: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8345:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8346:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8347:         if (exists($env{'request.course.id'})) {
                   8348:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8349:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8350:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8351:                 my $courseprivid=$env{'request.course.id'};
                   8352:                 $courseprivid=~s/\_/\//;
                   8353:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8354:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8355:                     return $1; 
1.762     raeburn  8356:                 } else {
                   8357:                     if ($env{'request.course.sec'}) {
                   8358:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8359:                     }
                   8360:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8361:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8362:                         return $2;
                   8363:                     }
1.714     raeburn  8364:                 }
                   8365:             }
                   8366:         }
                   8367:     }
                   8368: 
1.159     www      8369: # Free bre to public access
                   8370: 
                   8371:     if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8372:22):         my $copyright;
                   8373:22):         unless ($uri =~ /ext\.tool/) {
                   8374:22):             $copyright=&metadata($uri,'copyright');
                   8375:22):         }
1.620     albertel 8376: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8377:            return 'F'; 
                   8378:         }
1.238     www      8379:         if ($copyright eq 'priv') {
                   8380:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8381: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8382: 		return '';
                   8383:             }
                   8384:         }
                   8385:         if ($copyright eq 'domain') {
                   8386:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8387: 	    unless (($env{'user.domain'} eq $1) ||
                   8388:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8389: 		return '';
                   8390:             }
1.262     matthew  8391:         }
1.620     albertel 8392:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8393:             # Library role, so allow browsing of resources in this domain.
                   8394:             return 'F';
1.238     www      8395:         }
1.341     www      8396:         if ($copyright eq 'custom') {
                   8397: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8398:         }
1.14      www      8399:     }
1.264     matthew  8400:     # Domain coordinator is trying to create a course
1.620     albertel 8401:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8402:         # uri is the requested domain in this case.
                   8403:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8404:         # a role of dc for the domain in question.
1.620     albertel 8405:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8406:     }
1.29      www      8407: 
1.52      www      8408:     my $thisallowed='';
                   8409:     my $statecond=0;
                   8410:     my $courseprivid='';
                   8411: 
1.1039    raeburn  8412:     my $ownaccess;
1.1043    raeburn  8413:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8414:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8415:         if ($uri eq '') {
                   8416:             $ownaccess = 1;
                   8417:         } else {
                   8418:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8419:                 my $udom = $env{'user.domain'};
                   8420:                 my $uname = $env{'user.name'};
                   8421:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8422:                     $ownaccess = 1;
1.1040    raeburn  8423:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8424:                     unless ($uri =~ m{\.\./}) {
                   8425:                         $ownaccess = 1;
                   8426:                     }
                   8427:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8428:                     my $now = time;
                   8429:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8430:                         my $adom = $1;
                   8431:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8432:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142  raeburn  8433:                                 my ($start,$end) = split(/\./,$env{$key});
                   8434:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  8435:                                     $ownaccess = 1;
                   8436:                                     last;
                   8437:                                 }
                   8438:                             }
                   8439:                         }
                   8440:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8441:                         my $adom = $1;
                   8442:                         my $aname = $2;
1.1042    raeburn  8443:                         foreach my $role ('ca','aa') { 
                   8444:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8445:                                 my ($start,$end) =
1.1172.2.142  raeburn  8446:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8447:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8448:                                     $ownaccess = 1;
                   8449:                                     last;
                   8450:                                 }
1.1039    raeburn  8451:                             }
                   8452:                         }
                   8453:                     }
                   8454:                 }
                   8455:             }
                   8456:         }
                   8457:     }
                   8458: 
1.52      www      8459: # Course
                   8460: 
1.620     albertel 8461:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8462:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8463:             $thisallowed.=$1;
                   8464:         }
1.52      www      8465:     }
1.29      www      8466: 
1.52      www      8467: # Domain
                   8468: 
1.620     albertel 8469:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8470:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8471:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8472:             $thisallowed.=$1;
                   8473:         }
1.12      www      8474:     }
1.52      www      8475: 
1.1141    raeburn  8476: # User who is not author or co-author might still be able to edit
                   8477: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8478:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8479:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8480:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8481:             $thisallowed.=$1;
                   8482:         }
                   8483:     }
                   8484: 
1.52      www      8485: # Course: uri itself is a course
1.66      www      8486:     my $courseuri=$uri;
                   8487:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8488:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8489: 
1.620     albertel 8490:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8491:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8492:         if ($priv eq 'mip') {
                   8493:             my $rem = $1;
                   8494:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8495:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8496:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8497:                 if ($cdom ne '') {
                   8498:                     my %passwdconf = &get_passwdconf($cdom);
                   8499:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8500:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8501:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8502:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8503:                                 unless (@inststatuses) {
                   8504:                                     @inststatuses = ('default');
                   8505:                                 }
                   8506:                                 foreach my $status (@inststatuses) {
                   8507:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8508:                                         $thisallowed.=$rem;
                   8509:                                     }
                   8510:                                 }
                   8511:                             }
                   8512:                         }
                   8513:                     }
                   8514:                 }
                   8515:             }
                   8516:         } else {
                   8517:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8518:                 $thisallowed.=$1;
                   8519:             }
1.1039    raeburn  8520:         }
1.12      www      8521:     }
1.29      www      8522: 
1.665     albertel 8523: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8524: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8525:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8526: 	$thisallowed='';
1.671     raeburn  8527:         my ($match)=&is_on_map($uri);
                   8528:         if ($match) {
                   8529:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8530:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8531:                 my $value = $1;
1.1172.2.146.  .1(raebu 8532:22):                 my $deeplinkblock;
                   8533:22):                 unless ($nodeeplinkcheck) {
                   8534:22):                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8535:22):                 }
                   8536:22):                 if ($deeplinkblock) {
                   8537:22):                     $thisallowed='D';
                   8538:22):                 } elsif ($noblockcheck) {
1.1172.2.65  raeburn  8539:                     $thisallowed.=$value;
1.1162    raeburn  8540:                 } else {
1.1172.2.126  raeburn  8541:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8542:                     if (@blockers > 0) {
                   8543:                         $thisallowed = 'B';
                   8544:                     } else {
                   8545:                         $thisallowed.=$value;
                   8546:                     }
1.1162    raeburn  8547:                 }
1.671     raeburn  8548:             }
                   8549:         } else {
1.705     albertel 8550:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8551:             if ($refuri) {
                   8552:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8553:                     $thisallowed='F';
1.671     raeburn  8554:                 } else {
                   8555:                     $refuri=&declutter($refuri);
                   8556:                     my ($match) = &is_on_map($refuri);
                   8557:                     if ($match) {
1.1172.2.146.  .1(raebu 8558:22):                         my $deeplinkblock;
                   8559:22):                         unless ($nodeeplinkcheck) {
                   8560:22):                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8561:22):                         }
                   8562:22):                         if ($deeplinkblock) {
                   8563:22):                             $thisallowed='D';
                   8564:22):                         } elsif ($noblockcheck) {
1.1162    raeburn  8565:                             $thisallowed='F';
1.1172.2.65  raeburn  8566:                         } else {
1.1172.2.127  raeburn  8567:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8568:                             if (@blockers > 0) {
                   8569:                                 $thisallowed = 'B';
                   8570:                             } else {
                   8571:                                 $thisallowed='F';
                   8572:                             }
1.1162    raeburn  8573:                         }
1.671     raeburn  8574:                     }
1.669     raeburn  8575:                 }
1.671     raeburn  8576:             }
                   8577:         }
1.314     www      8578:     }
1.492     albertel 8579: 
1.766     albertel 8580:     if ($priv eq 'bre'
                   8581: 	&& $thisallowed ne 'F' 
                   8582: 	&& $thisallowed ne '2'
                   8583: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8584: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8585:     }
                   8586:     
1.52      www      8587: # Full access at system, domain or course-wide level? Exit.
1.29      www      8588:     if ($thisallowed=~/F/) {
                   8589: 	return 'F';
                   8590:     }
                   8591: 
1.52      www      8592: # If this is generating or modifying users, exit with special codes
1.29      www      8593: 
1.643     www      8594:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8595: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8596: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8597: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8598: 	    unless ($auname) { return $thisallowed; }
                   8599: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8600: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8601: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8602: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8603: 	}
1.52      www      8604: 	return $thisallowed;
                   8605:     }
                   8606: #
1.103     harris41 8607: # Gathered so far: system, domain and course wide privileges
1.52      www      8608: #
                   8609: # Course: See if uri or referer is an individual resource that is part of 
                   8610: # the course
                   8611: 
1.620     albertel 8612:     if ($env{'request.course.id'}) {
1.232     www      8613: 
1.1172.2.146.  .13(raeb 8614:-23):         if ($priv eq 'bre') {
                   8615:-23):             if (&is_coursetool_logo($uri)) {
                   8616:-23):                 return 'F';
                   8617:-23):             }
                   8618:-23):         }
                   8619:-23): 
1.1172.2.115  raeburn  8620: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8621: 
                   8622:         if ($priv eq 'mip') {
                   8623:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8624:                 return $thisallowed;
                   8625:             } else {
                   8626:                 return '';
                   8627:             }
                   8628:         }
                   8629: 
1.620     albertel 8630:        $courseprivid=$env{'request.course.id'};
                   8631:        if ($env{'request.course.sec'}) {
                   8632:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8633:        }
                   8634:        $courseprivid=~s/\_/\//;
                   8635:        my $checkreferer=1;
1.232     www      8636:        my ($match,$cond)=&is_on_map($uri);
                   8637:        if ($match) {
                   8638:            $statecond=$cond;
1.620     albertel 8639:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8640:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8641:                my $value = $1;
                   8642:                if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8643:22):                    my $deeplinkblock;
                   8644:22):                    unless ($nodeeplinkcheck) {
                   8645:22):                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8646:22):                    }
                   8647:22):                    if ($deeplinkblock) {
                   8648:22):                        $thisallowed = 'D';
                   8649:22):                    } elsif ($noblockcheck) {
1.1162    raeburn  8650:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8651:                    } else {
1.1172.2.126  raeburn  8652:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8653:                        if (@blockers > 0) {
                   8654:                            $thisallowed = 'B';
                   8655:                        } else {
                   8656:                            $thisallowed.=$value;
                   8657:                        }
1.1162    raeburn  8658:                    }
                   8659:                } else {
                   8660:                    $thisallowed.=$value;
                   8661:                }
1.52      www      8662:                $checkreferer=0;
                   8663:            }
1.29      www      8664:        }
1.1172.2.126  raeburn  8665: 
1.148     www      8666:        if ($checkreferer) {
1.620     albertel 8667: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8668:             unless ($refuri) {
1.800     albertel 8669:                 foreach my $key (keys(%env)) {
                   8670: 		    if ($key=~/^httpref\..*\*/) {
                   8671: 			my $pattern=$key;
1.156     www      8672:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8673:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8674:                         $pattern=~s/\//\\\//g;
1.152     www      8675:                         if ($orguri=~/$pattern/) {
1.800     albertel 8676: 			    $refuri=$env{$key};
1.148     www      8677:                         }
                   8678:                     }
1.191     harris41 8679:                 }
1.148     www      8680:             }
1.232     www      8681: 
1.148     www      8682:          if ($refuri) { 
1.152     www      8683: 	  $refuri=&declutter($refuri);
1.232     www      8684:           my ($match,$cond)=&is_on_map($refuri);
                   8685:             if ($match) {
                   8686:               my $refstatecond=$cond;
1.620     albertel 8687:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8688:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8689:                   my $value = $1;
                   8690:                   if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8691:22):                       my $deeplinkblock;
                   8692:22):                       unless ($nodeeplinkcheck) {
                   8693:22):                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8694:22):                       }
                   8695:22):                       if ($deeplinkblock) {
                   8696:22):                           $thisallowed = 'D';
                   8697:22):                       } elsif ($noblockcheck) {
1.1162    raeburn  8698:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8699:                       } else {
1.1172.2.127  raeburn  8700:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8701:                           if (@blockers > 0) {
                   8702:                               $thisallowed = 'B';
                   8703:                           } else {
                   8704:                               $thisallowed.=$value;
                   8705:                           }
1.1162    raeburn  8706:                       }
                   8707:                   } else {
                   8708:                       $thisallowed.=$value;
                   8709:                   }
1.53      www      8710:                   $uri=$refuri;
                   8711:                   $statecond=$refstatecond;
1.52      www      8712:               }
                   8713:           }
1.148     www      8714:         }
1.29      www      8715:        }
1.52      www      8716:    }
1.29      www      8717: 
1.52      www      8718: #
1.103     harris41 8719: # Gathered now: all privileges that could apply, and condition number
1.52      www      8720: # 
                   8721: #
                   8722: # Full or no access?
                   8723: #
1.29      www      8724: 
1.52      www      8725:     if ($thisallowed=~/F/) {
                   8726: 	return 'F';
                   8727:     }
1.29      www      8728: 
1.52      www      8729:     unless ($thisallowed) {
                   8730:         return '';
                   8731:     }
1.29      www      8732: 
1.52      www      8733: # Restrictions exist, deal with them
                   8734: #
                   8735: #   C:according to course preferences
                   8736: #   R:according to resource settings
                   8737: #   L:unless locked
                   8738: #   X:according to user session state
                   8739: #
                   8740: 
                   8741: # Possibly locked functionality, check all courses
1.1172.2.142  raeburn  8742: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      8743: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142  raeburn  8744: # courses, and 2 minutes for current course, in which user has st or ta role
                   8745: # which is neither expired nor a future role (unless current course).
1.52      www      8746: 
1.1172.2.142  raeburn  8747:     my ($needlockcheck,$now,$crsonly);
1.52      www      8748:     if ($thisallowed=~/L/) {
1.1172.2.142  raeburn  8749:         $now = time;
                   8750:         if ($priv eq 'bre') {
                   8751:             if ($uri ne '') {
                   8752:                 if ($orguri =~ m{^/+res/}) {
                   8753:                     if ($uri =~ m{^lib/templates/}) {
                   8754:                         if ($env{'request.course.id'}) {
                   8755:                             $crsonly = 1;
                   8756:                             $needlockcheck = 1;
                   8757:                         }
                   8758:                     } else {
                   8759:                         $needlockcheck = 1;
                   8760:                     }
                   8761:                 } elsif ($env{'request.course.id'}) {
                   8762:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   8763:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   8764:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   8765:                         $crsonly = 1;
                   8766:                     }
                   8767:                     $needlockcheck = 1;
                   8768:                 }
                   8769:             }
                   8770:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   8771:             $needlockcheck = 1;
                   8772:         }
                   8773:     }
                   8774:     if ($needlockcheck) {
                   8775:         foreach my $envkey (keys(%env)) {
1.54      www      8776:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8777:                my $courseid=$2;
                   8778:                my $roleid=$1.'.'.$2;
1.92      www      8779:                $courseid=~s/^\///;
1.1172.2.142  raeburn  8780:                unless ($env{'request.role'} eq $roleid) {
                   8781:                    my ($start,$end) = split(/\./,$env{$envkey});
                   8782:                    next unless (($now >= $start) && (!$end || $end > $now));
                   8783:                }
1.54      www      8784:                my $expiretime=600;
1.620     albertel 8785:                if ($env{'request.role'} eq $roleid) {
1.54      www      8786: 		  $expiretime=120;
                   8787:                }
                   8788: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8789:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8790:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8791: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8792:                }
1.620     albertel 8793:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8794:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8795: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8796:                        &log($env{'user.domain'},$env{'user.name'},
                   8797:                             $env{'user.home'},
1.57      www      8798:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8799:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8800:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8801: 		       return '';
                   8802:                    }
                   8803:                }
1.620     albertel 8804:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8805:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142  raeburn  8806: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 8807:                        &log($env{'user.domain'},$env{'user.name'},
                   8808:                             $env{'user.home'},
1.57      www      8809:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8810:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8811:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8812: 		       return '';
                   8813:                    }
                   8814:                }
                   8815: 	   }
1.29      www      8816:        }
1.52      www      8817:     }
1.1172.2.126  raeburn  8818: 
1.52      www      8819: #
                   8820: # Rest of the restrictions depend on selected course
                   8821: #
                   8822: 
1.620     albertel 8823:     unless ($env{'request.course.id'}) {
1.766     albertel 8824: 	if ($thisallowed eq 'A') {
                   8825: 	    return 'A';
1.814     raeburn  8826:         } elsif ($thisallowed eq 'B') {
                   8827:             return 'B';
1.766     albertel 8828: 	} else {
                   8829: 	    return '1';
                   8830: 	}
1.52      www      8831:     }
1.29      www      8832: 
1.52      www      8833: #
                   8834: # Now user is definitely in a course
                   8835: #
1.53      www      8836: 
                   8837: 
                   8838: # Course preferences
                   8839: 
                   8840:    if ($thisallowed=~/C/) {
1.620     albertel 8841:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8842:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8843:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8844: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8845: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8846: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8847: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8848: 			$env{'request.course.id'});
                   8849: 	   }
1.237     www      8850:            return '';
                   8851:        }
                   8852: 
1.620     albertel 8853:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8854: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8855: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8856: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8857: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8858: 			$env{'request.course.id'});
                   8859: 	   }
1.54      www      8860:            return '';
                   8861:        }
1.53      www      8862:    }
                   8863: 
                   8864: # Resource preferences
                   8865: 
                   8866:    if ($thisallowed=~/R/) {
1.620     albertel 8867:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8868:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8869: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8870: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8871: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8872: 	   }
                   8873: 	   return '';
1.54      www      8874:        }
1.53      www      8875:    }
1.30      www      8876: 
1.1172.2.146.  .1(raebu 8877:22): # Restricted for deeplinked session?
                   8878:22): 
                   8879:22):     if ($env{'request.deeplink.login'}) {
                   8880:22):         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
                   8881:22):             if (!$symb) { $symb=&symbread($uri,1); }
                   8882:22):             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
                   8883:22):                 return '';
                   8884:22):             }
                   8885:22):         }
                   8886:22):     }
                   8887:22): 
1.246     www      8888: # Restricted by state or randomout?
1.30      www      8889: 
1.52      www      8890:    if ($thisallowed=~/X/) {
1.620     albertel 8891:       if ($env{'acc.randomout'}) {
1.579     albertel 8892: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8893:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8894:             return ''; 
                   8895:          }
1.247     www      8896:       }
                   8897:       if (&condval($statecond)) {
1.52      www      8898: 	 return '2';
                   8899:       } else {
                   8900:          return '';
                   8901:       }
                   8902:    }
1.30      www      8903: 
1.766     albertel 8904:     if ($thisallowed eq 'A') {
                   8905: 	return 'A';
1.814     raeburn  8906:     } elsif ($thisallowed eq 'B') {
                   8907:         return 'B';
1.1172.2.146.  .1(raebu 8908:22):     } elsif ($thisallowed eq 'D') {
                   8909:22):         return 'D';
1.766     albertel 8910:     }
1.52      www      8911:    return 'F';
1.232     www      8912: }
1.1162    raeburn  8913: 
1.1172.2.13  raeburn  8914: # ------------------------------------------- Check construction space access
                   8915: 
                   8916: sub constructaccess {
                   8917:     my ($url,$setpriv)=@_;
                   8918: 
                   8919: # We do not allow editing of previous versions of files
                   8920:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8921: 
                   8922: # Get username and domain from URL
                   8923:     my ($ownername,$ownerdomain,$ownerhome);
                   8924: 
                   8925:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8926:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8927: 
                   8928: # The URL does not really point to any authorspace, forget it
                   8929:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8930: 
                   8931: # Now we need to see if the user has access to the authorspace of
                   8932: # $ownername at $ownerdomain
                   8933: 
                   8934:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8935: # Real author for this?
                   8936:        $ownerhome = $env{'user.home'};
                   8937:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8938:           return ($ownername,$ownerdomain,$ownerhome);
                   8939:        }
                   8940:     } else {
                   8941: # Co-author for this?
                   8942:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8943:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8944:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8945:             return ($ownername,$ownerdomain,$ownerhome);
                   8946:         }
                   8947:     }
                   8948: 
                   8949: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8950: # we might as well leave
                   8951:    unless ($setpriv) { return ''; }
                   8952: 
                   8953: # Backdoor access?
                   8954:     my $allowed=&allowed('eco',$ownerdomain);
                   8955: # Nope
                   8956:     unless ($allowed) { return ''; }
                   8957: # Looks like we may have access, but could be locked by the owner of the construction space
                   8958:     if ($allowed eq 'U') {
                   8959:         my %blocked=&get('environment',['domcoord.author'],
                   8960:                          $ownerdomain,$ownername);
                   8961: # Is blocked by owner
                   8962:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8963:     }
                   8964:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8965: # Grant temporary access
                   8966:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8967:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8968:         if (!$update) { $update = $then; }
                   8969:         my $refresh=$env{'user.refresh.time'};
                   8970:         if (!$refresh) { $refresh = $update; }
                   8971:         my $now = time;
                   8972:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8973:                            $now,'ca','constructaccess');
                   8974:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8975:         return($ownername,$ownerdomain,$ownerhome);
                   8976:     }
                   8977: # No business here
                   8978:     return '';
                   8979: }
                   8980: 
1.1172.2.66  raeburn  8981: # ----------------------------------------------------------- Content Blocking
                   8982: 
                   8983: {
                   8984: # Caches for faster Course Contents display where content blocking
                   8985: # is in operation (i.e., interval param set) for timed quiz.
                   8986: #
                   8987: # User for whom data are being temporarily cached.
                   8988: my $cacheduser='';
1.1172.2.126  raeburn  8989: # Course for which data are being temporarily cached.
                   8990: my $cachedcid='';
1.1172.2.66  raeburn  8991: # Cached blockers for this user (a hash of blocking items).
                   8992: my %cachedblockers=();
                   8993: # When the data were last cached.
                   8994: my $cachedlast='';
                   8995: 
                   8996: sub load_all_blockers {
1.1172.2.128  raeburn  8997:     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8998:     if (($uname ne '') && ($udom ne '')) {
                   8999:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126  raeburn  9000:             ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128  raeburn  9001:             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  9002:             return;
                   9003:         }
                   9004:     }
                   9005:     $cachedlast=time;
                   9006:     $cacheduser=$uname.':'.$udom;
1.1172.2.126  raeburn  9007:     $cachedcid=$env{'request.course.id'};
1.1172.2.128  raeburn  9008:     %cachedblockers = &get_commblock_resources();
1.1172.2.126  raeburn  9009:     return;
1.1172.2.66  raeburn  9010: }
                   9011: 
1.1162    raeburn  9012: sub get_comm_blocks {
                   9013:     my ($cdom,$cnum) = @_;
                   9014:     if ($cdom eq '' || $cnum eq '') {
                   9015:         return unless ($env{'request.course.id'});
                   9016:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9017:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9018:     }
                   9019:     my %commblocks;
                   9020:     my $hashid=$cdom.'_'.$cnum;
                   9021:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   9022:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   9023:         %commblocks = %{$blocksref};
                   9024:     } else {
                   9025:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   9026:         my $cachetime = 600;
                   9027:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   9028:     }
                   9029:     return %commblocks;
                   9030: }
                   9031: 
1.1172.2.66  raeburn  9032: sub get_commblock_resources {
                   9033:     my ($blocks) = @_;
                   9034:     my %blockers = ();
                   9035:     return %blockers unless ($env{'request.course.id'});
1.1172.2.142  raeburn  9036:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   9037:     if ($env{'request.course.sec'}) {
                   9038:         $courseurl .= '/'.$env{'request.course.sec'};
                   9039:     }
                   9040:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  9041:     my %commblocks;
                   9042:     if (ref($blocks) eq 'HASH') {
                   9043:         %commblocks = %{$blocks};
                   9044:     } else {
                   9045:         %commblocks = &get_comm_blocks();
                   9046:     }
1.1172.2.66  raeburn  9047:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  9048:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  9049:     return %blockers unless (ref($navmap));
                   9050:     my $now = time;
1.1162    raeburn  9051:     foreach my $block (keys(%commblocks)) {
                   9052:         if ($block =~ /^(\d+)____(\d+)$/) {
                   9053:             my ($start,$end) = ($1,$2);
                   9054:             if ($start <= $now && $end >= $now) {
                   9055:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   9056:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   9057:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  9058:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   9059:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  9060:                             }
                   9061:                         }
                   9062:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  9063:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   9064:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  9065:                             }
                   9066:                         }
                   9067:                     }
                   9068:                 }
                   9069:             }
                   9070:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   9071:             my $item = $1;
                   9072:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   9073:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142  raeburn  9074:                     my (@interval,$mapname);
1.1172.2.66  raeburn  9075:                     my $type = 'map';
                   9076:                     if ($item eq 'course') {
                   9077:                         $type = 'course';
                   9078:                         @interval=&EXT("resource.0.interval");
                   9079:                     } else {
                   9080:                         if ($item =~ /___\d+___/) {
                   9081:                             $type = 'resource';
                   9082:                             @interval=&EXT("resource.0.interval",$item);
1.1162    raeburn  9083:                         } else {
1.1172.2.142  raeburn  9084:                             $mapname = &deversion($item);
                   9085:                             if (ref($navmap)) {
                   9086:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
                   9087:                                 @interval = ($timelimit,'map');
1.1162    raeburn  9088:                             }
                   9089:                         }
1.1172.2.66  raeburn  9090:                     }
1.1172.2.146.  .1(raebu 9091:22):                     if ($interval[0] =~ /^(\d+)/) {
                   9092:22):                         my $timelimit = $1;
1.1172.2.66  raeburn  9093:                         my $first_access;
                   9094:                         if ($type eq 'resource') {
                   9095:                             $first_access=&get_first_access($interval[1],$item);
                   9096:                         } elsif ($type eq 'map') {
                   9097:                             $first_access=&get_first_access($interval[1],undef,$item);
                   9098:                         } else {
                   9099:                             $first_access=&get_first_access($interval[1]);
                   9100:                         }
                   9101:                         if ($first_access) {
1.1172.2.146.  .1(raebu 9102:22):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  9103:                             if ($timesup > $now) {
                   9104:                                 my $activeblock;
1.1172.2.142  raeburn  9105:                                 if ($type eq 'resource') {
                   9106:                                     if (ref($navmap)) {
                   9107:                                         my $res = $navmap->getBySymb($item);
                   9108:                                         if ($res->answerable()) {
                   9109:                                             $activeblock = 1;
                   9110:                                         }
                   9111:                                     }
                   9112:                                 } elsif ($type eq 'map') {
                   9113:                                     my $mapsymb = &symbread($mapname,1);
                   9114:                                     if (($mapsymb) && (ref($navmap))) {
                   9115:                                         my $mapres = $navmap->getBySymb($mapsymb);
                   9116:                                         if (ref($mapres)) {
                   9117:                                             my $first = $mapres->map_start();
                   9118:                                             my $finish = $mapres->map_finish();
                   9119:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   9120:                                             if (ref($it)) {
                   9121:                                                 my $res;
                   9122:                                                 while ($res = $it->next(undef,1)) {
                   9123:                                                     next unless (ref($res));
                   9124:                                                     my $symb = $res->symb();
                   9125:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
                   9126:                                                     @interval=&EXT("resource.0.interval",$symb);
                   9127:                                                     if ($interval[1] eq 'map') {
                   9128:                                                         if ($res->answerable()) {
                   9129:                                                             $activeblock = 1;
                   9130:                                                             last;
                   9131:                                                         }
                   9132:                                                     }
                   9133:                                                 }
                   9134:                                             }
                   9135:                                         }
1.1172.2.66  raeburn  9136:                                     }
                   9137:                                 }
                   9138:                                 if ($activeblock) {
                   9139:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   9140:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   9141:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   9142:                                          }
                   9143:                                     }
                   9144:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   9145:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   9146:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  9147:                                         }
1.1162    raeburn  9148:                                     }
                   9149:                                 }
                   9150:                             }
                   9151:                         }
                   9152:                     }
                   9153:                 }
                   9154:             }
                   9155:         }
                   9156:     }
1.1172.2.66  raeburn  9157:     return %blockers;
1.1162    raeburn  9158: }
                   9159: 
1.1172.2.66  raeburn  9160: sub has_comm_blocking {
1.1172.2.128  raeburn  9161:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  9162:     my @blockers;
                   9163:     return unless ($env{'request.course.id'});
                   9164:     return unless ($priv eq 'bre');
                   9165:     return if ($env{'request.state'} eq 'construct');
1.1172.2.142  raeburn  9166:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   9167:     if ($env{'request.course.sec'}) {
                   9168:         $courseurl .= '/'.$env{'request.course.sec'};
                   9169:     }
                   9170:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128  raeburn  9171:     my %blockinfo;
                   9172:     if (ref($blocks) eq 'HASH') {
                   9173:         %blockinfo = &get_commblock_resources($blocks);
                   9174:     } else {
                   9175:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   9176:         %blockinfo = %cachedblockers;
                   9177:     }
                   9178:     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  9179:     my (%possibles,@symbs);
                   9180:     if (!$symb) {
1.1172.2.128  raeburn  9181:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  9182:     }
1.1172.2.66  raeburn  9183:     if ($symb) {
                   9184:         @symbs = ($symb);
                   9185:     } elsif (keys(%possibles)) {
                   9186:         @symbs = keys(%possibles);
                   9187:     }
                   9188:     my $noblock;
                   9189:     foreach my $symb (@symbs) {
                   9190:         last if ($noblock);
                   9191:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128  raeburn  9192:         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  9193:             if ($block =~ /^firstaccess____(.+)$/) {
                   9194:                 my $item = $1;
1.1172.2.126  raeburn  9195:                 unless ($blocked) {
                   9196:                     if (($item eq $map) || ($item eq $symb)) {
                   9197:                         $noblock = 1;
                   9198:                         last;
                   9199:                     }
1.1172.2.66  raeburn  9200:                 }
1.1162    raeburn  9201:             }
1.1172.2.128  raeburn  9202:             if (ref($blockinfo{$block}) eq 'HASH') {
                   9203:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   9204:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  9205:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9206:                             push(@blockers,$block);
                   9207:                         }
                   9208:                     }
                   9209:                 }
1.1172.2.128  raeburn  9210:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   9211:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126  raeburn  9212:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9213:                             push(@blockers,$block);
                   9214:                         }
1.1172.2.66  raeburn  9215:                     }
                   9216:                 }
1.1162    raeburn  9217:             }
                   9218:         }
                   9219:     }
1.1172.2.126  raeburn  9220:     unless ($noblock) {
                   9221:         return @blockers;
                   9222:     }
                   9223:     return;
1.1172.2.66  raeburn  9224: }
1.1162    raeburn  9225: }
                   9226: 
1.1172.2.146.  .1(raebu 9227:22): sub deeplink_check {
                   9228:22):     my ($priv,$symb,$uri) = @_;
                   9229:22):     return unless ($env{'request.course.id'});
                   9230:22):     return unless ($priv eq 'bre');
                   9231:22):     return if ($env{'request.state'} eq 'construct');
                   9232:22):     return if ($env{'request.role.adv'});
                   9233:22):     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9234:22):     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9235:22):     my (%possibles,@symbs);
                   9236:22):     if (!$symb) {
                   9237:22):         $symb = &symbread($uri,1,1,1,\%possibles);
                   9238:22):     }
                   9239:22):     if ($symb) {
                   9240:22):         @symbs = ($symb);
                   9241:22):     } elsif (keys(%possibles)) {
                   9242:22):         @symbs = keys(%possibles);
                   9243:22):     }
                   9244:22): 
                   9245:22):     my ($deeplink_symb,$allow);
                   9246:22):     if ($env{'request.deeplink.login'}) {
                   9247:22):         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
                   9248:22):     }
                   9249:22):     foreach my $symb (@symbs) {
                   9250:22):         last if ($allow);
                   9251:22):         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   9252:22):         if ($deeplink eq '') {
                   9253:22):             $allow = 1;
                   9254:22):         } else {
                   9255:22):             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
                   9256:22):             if ($state ne 'only') {
                   9257:22):                 $allow = 1;
                   9258:22):             } else {
                   9259:22):                 my $check_deeplink_entry;
                   9260:22):                 if ($protect ne 'none') {
                   9261:22):                     my ($acctype,$item) = split(/:/,$protect);
                   9262:22):                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
                   9263:22):                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
                   9264:22):                             $check_deeplink_entry = 1
                   9265:22):                         }
                   9266:22):                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
                   9267:22):                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
                   9268:22):                             $check_deeplink_entry = 1;
                   9269:22):                         }
                   9270:22):                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   9271:22):                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   9272:22):                             $check_deeplink_entry = 1;
                   9273:22):                         }
                   9274:22):                     }
                   9275:22):                 }
                   9276:22):                 if (($protect eq 'none') || ($check_deeplink_entry)) {
                   9277:22):                     if ($scope eq 'res') {
                   9278:22):                         if ($symb eq $deeplink_symb) {
                   9279:22):                             $allow = 1;
                   9280:22):                         }
                   9281:22):                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
                   9282:22):                         my ($map_from_symb,$map_from_login);
                   9283:22):                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
                   9284:22):                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9285:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
                   9286:22):                         } else {
                   9287:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
                   9288:22):                         }
                   9289:22):                         if (($map_from_symb) && ($map_from_login)) {
                   9290:22):                             if ($map_from_symb eq $map_from_login) {
                   9291:22):                                 $allow = 1;
                   9292:22):                             } elsif ($scope eq 'rec') {
                   9293:22):                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
                   9294:22):                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
                   9295:22):                                     $allow = 1;
                   9296:22):                                 }
                   9297:22):                             }
                   9298:22):                         }
                   9299:22):                     }
                   9300:22):                 }
                   9301:22):             }
                   9302:22):         }
                   9303:22):     }
                   9304:22):     return if ($allow);
                   9305:22):     return 1;
                   9306:22): }
                   9307:22): 
1.1172.2.66  raeburn  9308: # -------------------------------- Deversion and split uri into path an filename
                   9309: 
1.1133    foxr     9310: #
1.1172.2.66  raeburn  9311: #   Removes the version from a URI and
1.1133    foxr     9312: #   splits it in to its filename and path to the filename.
                   9313: #   Seems like File::Basename could have done this more clearly.
                   9314: #   Parameters:
                   9315: #      $uri   - input URI
                   9316: #   Returns:
                   9317: #     Two element list consisting of 
                   9318: #     $pathname  - the URI up to and excluding the trailing /
                   9319: #     $filename  - The part of the URI following the last /
                   9320: #  NOTE:
                   9321: #    Another realization of this is simply:
                   9322: #    use File::Basename;
                   9323: #    ...
                   9324: #    $uri = shift;
                   9325: #    $filename = basename($uri);
                   9326: #    $path     = dirname($uri);
                   9327: #    return ($filename, $path);
                   9328: #
                   9329: #     The implementation below is probably faster however.
                   9330: #
1.710     albertel 9331: sub split_uri_for_cond {
                   9332:     my $uri=&deversion(&declutter(shift));
                   9333:     my @uriparts=split(/\//,$uri);
                   9334:     my $filename=pop(@uriparts);
                   9335:     my $pathname=join('/',@uriparts);
                   9336:     return ($pathname,$filename);
                   9337: }
1.232     www      9338: # --------------------------------------------------- Is a resource on the map?
                   9339: 
                   9340: sub is_on_map {
1.710     albertel 9341:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 9342:     #Trying to find the conditional for the file
1.620     albertel 9343:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 9344: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      9345:     if ($match) {
1.289     bowersj2 9346: 	return (1,$1);
                   9347:     } else {
1.434     www      9348: 	return (0,0);
1.289     bowersj2 9349:     }
1.12      www      9350: }
                   9351: 
1.427     www      9352: # --------------------------------------------------------- Get symb from alias
                   9353: 
                   9354: sub get_symb_from_alias {
                   9355:     my $symb=shift;
                   9356:     my ($map,$resid,$url)=&decode_symb($symb);
                   9357: # Already is a symb
                   9358:     if ($url) { return $symb; }
                   9359: # Must be an alias
                   9360:     my $aliassymb='';
                   9361:     my %bighash;
1.620     albertel 9362:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      9363:                             &GDBM_READER(),0640)) {
                   9364:         my $rid=$bighash{'mapalias_'.$symb};
                   9365: 	if ($rid) {
                   9366: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 9367: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   9368: 				    $resid,$bighash{'src_'.$rid});
1.427     www      9369: 	}
                   9370:         untie %bighash;
                   9371:     }
                   9372:     return $aliassymb;
                   9373: }
                   9374: 
1.12      www      9375: # ----------------------------------------------------------------- Define Role
                   9376: 
                   9377: sub definerole {
                   9378:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  9379:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9380:     foreach my $role (split(':',$sysrole)) {
                   9381: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9382:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9383:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9384: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9385:                return "refused:s:$crole&$cqual"; 
                   9386:             }
                   9387:         }
1.191     harris41 9388:     }
1.800     albertel 9389:     foreach my $role (split(':',$domrole)) {
                   9390: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9391:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9392:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9393: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9394:                return "refused:d:$crole&$cqual"; 
                   9395:             }
                   9396:         }
1.191     harris41 9397:     }
1.800     albertel 9398:     foreach my $role (split(':',$courole)) {
                   9399: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9400:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9401:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9402: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9403:                return "refused:c:$crole&$cqual"; 
                   9404:             }
                   9405:         }
1.191     harris41 9406:     }
1.1172.2.84  raeburn  9407:     my $uhome;
                   9408:     if (($uname ne '') && ($udom ne '')) {
                   9409:         $uhome = &homeserver($uname,$udom);
                   9410:         return $uhome if ($uhome eq 'no_host');
                   9411:     } else {
                   9412:         $uname = $env{'user.name'};
                   9413:         $udom = $env{'user.domain'};
                   9414:         $uhome = $env{'user.home'};
                   9415:     }
1.620     albertel 9416:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  9417:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9418:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  9419:     return reply($command,$uhome);
1.12      www      9420:   } else {
                   9421:     return 'refused';
                   9422:   }
1.105     harris41 9423: }
                   9424: 
                   9425: # ---------------- Make a metadata query against the network of library servers
                   9426: 
                   9427: sub metadata_query {
1.1172.2.33  raeburn  9428:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9429:     my %rhash;
1.845     albertel 9430:     my %libserv = &all_library();
1.244     matthew  9431:     my @server_list = (defined($server_array) ? @$server_array
                   9432:                                               : keys(%libserv) );
                   9433:     for my $server (@server_list) {
1.1172.2.33  raeburn  9434:         my $domains = '';
                   9435:         if (ref($domains_hash) eq 'HASH') {
                   9436:             $domains = $domains_hash->{$server};    
                   9437:         }
1.118     harris41 9438: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  9439: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9440: 	    $rhash{$server}=$reply;
                   9441: 	}
                   9442: 	else {
                   9443: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  9444: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9445: 			     $server);
                   9446: 	    $rhash{$server}=$reply;
                   9447: 	}
1.112     harris41 9448:     }
1.118     harris41 9449:     return \%rhash;
1.240     www      9450: }
                   9451: 
                   9452: # ----------------------------------------- Send log queries and wait for reply
                   9453: 
                   9454: sub log_query {
                   9455:     my ($uname,$udom,$query,%filters)=@_;
                   9456:     my $uhome=&homeserver($uname,$udom);
                   9457:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9458:     my $uhost=&hostname($uhome);
1.800     albertel 9459:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9460:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9461:                        $uhome);
1.479     albertel 9462:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9463:     return get_query_reply($queryid);
                   9464: }
                   9465: 
1.818     raeburn  9466: # -------------------------- Update MySQL table for portfolio file
                   9467: 
                   9468: sub update_portfolio_table {
1.821     raeburn  9469:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9470:     if ($group ne '') {
                   9471:         $file_name =~s /^\Q$group\E//;
                   9472:     }
1.818     raeburn  9473:     my $homeserver = &homeserver($uname,$udom);
                   9474:     my $queryid=
1.821     raeburn  9475:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9476:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9477:     my $reply = &get_query_reply($queryid);
                   9478:     return $reply;
                   9479: }
                   9480: 
1.899     raeburn  9481: # -------------------------- Update MySQL allusers table
                   9482: 
                   9483: sub update_allusers_table {
                   9484:     my ($uname,$udom,$names) = @_;
                   9485:     my $homeserver = &homeserver($uname,$udom);
                   9486:     my $queryid=
                   9487:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9488:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9489:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9490:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9491:                'generation='.&escape($names->{'generation'}).'%%'.
                   9492:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9493:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9494:     return;
1.899     raeburn  9495: }
                   9496: 
1.508     raeburn  9497: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9498: 
                   9499: sub fetch_enrollment_query {
1.511     raeburn  9500:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  9501:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9502:     my $maxtries = 1;
1.508     raeburn  9503:     if ($context eq 'automated') {
                   9504:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  9505:         $sleep = 2;
                   9506:         $loopmax = 100;
1.547     raeburn  9507:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9508:     } else {
                   9509:         $homeserver = &homeserver($cnum,$dom);
                   9510:     }
1.838     albertel 9511:     my $host=&hostname($homeserver);
1.506     raeburn  9512:     my $cmd = '';
1.1000    raeburn  9513:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9514:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9515:     }
                   9516:     $cmd =~ s/%%$//;
                   9517:     $cmd = &escape($cmd);
                   9518:     my $query = 'fetchenrollment';
1.620     albertel 9519:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9520:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9521:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9522:         return 'error: '.$queryid;
                   9523:     }
1.1172.2.93  raeburn  9524:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9525:     my $tries = 1;
                   9526:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  9527:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9528:         $tries ++;
                   9529:     }
1.526     raeburn  9530:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9531:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9532:     } else {
1.901     albertel 9533:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  9534:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9535:             foreach my $line (@responses) {
                   9536:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9537:                 $$replyref{$key} = $value;
                   9538:             }
                   9539:         } else {
1.1117    foxr     9540:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9541:             foreach my $line (@responses) {
                   9542:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9543:                 $$replyref{$key} = $value;
                   9544:                 if ($value > 0) {
1.800     albertel 9545:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9546:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9547:                         my $destname = $pathname.'/'.$filename;
                   9548:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9549:                         if ($xml_classlist =~ /^error/) {
                   9550:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9551:                         } else {
1.1172.2.96  raeburn  9552:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9553:                                 print FILE &unescape($xml_classlist);
                   9554:                                 close(FILE);
1.526     raeburn  9555:                             } else {
                   9556:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9557:                             }
                   9558:                         }
                   9559:                     }
                   9560:                 }
                   9561:             }
                   9562:         }
                   9563:         return 'ok';
                   9564:     }
                   9565:     return 'error';
                   9566: }
                   9567: 
1.242     www      9568: sub get_query_reply {
1.1172.2.79  raeburn  9569:     my ($queryid,$sleep,$loopmax) = @_;
                   9570:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9571:         $sleep = 0.2;
                   9572:     }
                   9573:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9574:         $loopmax = 100;
                   9575:     }
1.1117    foxr     9576:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9577:     my $reply='';
1.1172.2.79  raeburn  9578:     for (1..$loopmax) {
                   9579: 	sleep($sleep);
1.240     www      9580:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  9581: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9582: 		$reply = join('',<$fh>);
                   9583: 		close($fh);
1.240     www      9584: 	   } else { return 'error: reply_file_error'; }
1.242     www      9585:            return &unescape($reply);
                   9586: 	}
1.240     www      9587:     }
1.242     www      9588:     return 'timeout:'.$queryid;
1.240     www      9589: }
                   9590: 
                   9591: sub courselog_query {
1.241     www      9592: #
                   9593: # possible filters:
                   9594: # url: url or symb
                   9595: # username
                   9596: # domain
                   9597: # action: view, submit, grade
                   9598: # start: timestamp
                   9599: # end: timestamp
                   9600: #
1.240     www      9601:     my (%filters)=@_;
1.620     albertel 9602:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9603:     if ($filters{'url'}) {
                   9604: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9605:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9606:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9607:     }
1.620     albertel 9608:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9609:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9610:     return &log_query($cname,$cdom,'courselog',%filters);
                   9611: }
                   9612: 
                   9613: sub userlog_query {
1.858     raeburn  9614: #
                   9615: # possible filters:
                   9616: # action: log check role
                   9617: # start: timestamp
                   9618: # end: timestamp
                   9619: #
1.240     www      9620:     my ($uname,$udom,%filters)=@_;
                   9621:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9622: }
                   9623: 
1.506     raeburn  9624: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9625: 
                   9626: sub auto_run {
1.508     raeburn  9627:     my ($cnum,$cdom) = @_;
1.876     raeburn  9628:     my $response = 0;
                   9629:     my $settings;
                   9630:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9631:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9632:         $settings = $domconfig{'autoenroll'};
                   9633:         if ($settings->{'run'} eq '1') {
                   9634:             $response = 1;
                   9635:         }
                   9636:     } else {
1.934     raeburn  9637:         my $homeserver;
                   9638:         if (&is_course($cdom,$cnum)) {
                   9639:             $homeserver = &homeserver($cnum,$cdom);
                   9640:         } else {
                   9641:             $homeserver = &domain($cdom,'primary');
                   9642:         }
                   9643:         if ($homeserver ne 'no_host') {
                   9644:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9645:         }
1.876     raeburn  9646:     }
1.506     raeburn  9647:     return $response;
                   9648: }
1.776     albertel 9649: 
1.506     raeburn  9650: sub auto_get_sections {
1.508     raeburn  9651:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9652:     my $homeserver;
                   9653:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9654:         $homeserver = &homeserver($cnum,$cdom);
                   9655:     }
                   9656:     if (!defined($homeserver)) { 
                   9657:         if ($cdom =~ /^$match_domain$/) {
                   9658:             $homeserver = &domain($cdom,'primary');
                   9659:         }
                   9660:     }
                   9661:     my @secs;
                   9662:     if (defined($homeserver)) {
                   9663:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9664:         unless ($response eq 'refused') {
                   9665:             @secs = split(/:/,$response);
                   9666:         }
1.506     raeburn  9667:     }
                   9668:     return @secs;
                   9669: }
1.776     albertel 9670: 
1.506     raeburn  9671: sub auto_new_course {
1.1099    raeburn  9672:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9673:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9674:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9675:     return $response;
                   9676: }
1.776     albertel 9677: 
1.506     raeburn  9678: sub auto_validate_courseID {
1.508     raeburn  9679:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9680:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9681:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9682:     return $response;
                   9683: }
1.776     albertel 9684: 
1.1007    raeburn  9685: sub auto_validate_instcode {
1.1020    raeburn  9686:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9687:     my ($homeserver,$response);
                   9688:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9689:         $homeserver = &homeserver($cnum,$cdom);
                   9690:     }
                   9691:     if (!defined($homeserver)) {
                   9692:         if ($cdom =~ /^$match_domain$/) {
                   9693:             $homeserver = &domain($cdom,'primary');
                   9694:         }
                   9695:     }
1.1065    raeburn  9696:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9697:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9698:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9699:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9700: }
                   9701: 
1.1172.2.141  raeburn  9702: sub auto_validate_inst_crosslist {
                   9703:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   9704:     my ($homeserver,$response);
                   9705:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9706:         $homeserver = &homeserver($cnum,$cdom);
                   9707:     }
                   9708:     if (!defined($homeserver)) {
                   9709:         if ($cdom =~ /^$match_domain$/) {
                   9710:             $homeserver = &domain($cdom,'primary');
                   9711:         }
                   9712:     }
                   9713:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   9714:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   9715:                          &escape($instcode).':'.&escape($inst_xlist).':'.
                   9716:                          &escape($coowner),$homeserver);
                   9717:     }
                   9718:     return $response;
                   9719: }
                   9720: 
1.506     raeburn  9721: sub auto_create_password {
1.873     raeburn  9722:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9723:     my ($homeserver,$response);
1.506     raeburn  9724:     my $create_passwd = 0;
                   9725:     my $authchk = '';
1.873     raeburn  9726:     if ($udom =~ /^$match_domain$/) {
                   9727:         $homeserver = &domain($udom,'primary');
                   9728:     }
                   9729:     if ($homeserver eq '') {
                   9730:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9731:             $homeserver = &homeserver($cnum,$cdom);
                   9732:         }
                   9733:     }
                   9734:     if ($homeserver eq '') {
                   9735:         $authchk = 'nodomain';
1.506     raeburn  9736:     } else {
1.873     raeburn  9737:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9738:         if ($response eq 'refused') {
                   9739:             $authchk = 'refused';
                   9740:         } else {
1.901     albertel 9741:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9742:         }
1.506     raeburn  9743:     }
                   9744:     return ($authparam,$create_passwd,$authchk);
                   9745: }
                   9746: 
1.706     raeburn  9747: sub auto_photo_permission {
                   9748:     my ($cnum,$cdom,$students) = @_;
                   9749:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9750:     my ($outcome,$perm_reqd,$conditions) = 
                   9751: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9752:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9753: 	return (undef,undef);
                   9754:     }
1.706     raeburn  9755:     return ($outcome,$perm_reqd,$conditions);
                   9756: }
                   9757: 
                   9758: sub auto_checkphotos {
                   9759:     my ($uname,$udom,$pid) = @_;
                   9760:     my $homeserver = &homeserver($uname,$udom);
                   9761:     my ($result,$resulttype);
                   9762:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9763: 				   &escape($uname).':'.&escape($pid),
                   9764: 				   $homeserver));
1.709     albertel 9765:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9766: 	return (undef,undef);
                   9767:     }
1.706     raeburn  9768:     if ($outcome) {
                   9769:         ($result,$resulttype) = split(/:/,$outcome);
                   9770:     } 
                   9771:     return ($result,$resulttype);
                   9772: }
                   9773: 
                   9774: sub auto_photochoice {
                   9775:     my ($cnum,$cdom) = @_;
                   9776:     my $homeserver = &homeserver($cnum,$cdom);
                   9777:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9778: 						       &escape($cdom),
                   9779: 						       $homeserver)));
1.709     albertel 9780:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9781: 	return (undef,undef);
                   9782:     }
1.706     raeburn  9783:     return ($update,$comment);
                   9784: }
                   9785: 
                   9786: sub auto_photoupdate {
                   9787:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9788:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9789:     my $host=&hostname($homeserver);
1.706     raeburn  9790:     my $cmd = '';
                   9791:     my $maxtries = 1;
1.800     albertel 9792:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9793:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9794:     }
                   9795:     $cmd =~ s/%%$//;
                   9796:     $cmd = &escape($cmd);
                   9797:     my $query = 'institutionalphotos';
                   9798:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9799:     unless ($queryid=~/^\Q$host\E\_/) {
                   9800:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9801:         return 'error: '.$queryid;
                   9802:     }
                   9803:     my $reply = &get_query_reply($queryid);
                   9804:     my $tries = 1;
                   9805:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9806:         $reply = &get_query_reply($queryid);
                   9807:         $tries ++;
                   9808:     }
                   9809:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9810:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9811:     } else {
                   9812:         my @responses = split(/:/,$reply);
                   9813:         my $outcome = shift(@responses); 
                   9814:         foreach my $item (@responses) {
                   9815:             my ($key,$value) = split(/=/,$item);
                   9816:             $$photo{$key} = $value;
                   9817:         }
                   9818:         return $outcome;
                   9819:     }
                   9820:     return 'error';
                   9821: }
                   9822: 
1.521     raeburn  9823: sub auto_instcode_format {
1.793     albertel 9824:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9825: 	$cat_order) = @_;
1.521     raeburn  9826:     my $courses = '';
1.772     raeburn  9827:     my @homeservers;
1.521     raeburn  9828:     if ($caller eq 'global') {
1.841     albertel 9829: 	my %servers = &get_servers($codedom,'library');
                   9830: 	foreach my $tryserver (keys(%servers)) {
                   9831: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9832: 		push(@homeservers,$tryserver);
                   9833: 	    }
1.584     raeburn  9834:         }
1.1022    raeburn  9835:     } elsif ($caller eq 'requests') {
                   9836:         if ($codedom =~ /^$match_domain$/) {
                   9837:             my $chome = &domain($codedom,'primary');
                   9838:             unless ($chome eq 'no_host') {
                   9839:                 push(@homeservers,$chome);
                   9840:             }
                   9841:         }
1.521     raeburn  9842:     } else {
1.772     raeburn  9843:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9844:     }
1.793     albertel 9845:     foreach my $code (keys(%{$instcodes})) {
                   9846:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9847:     }
                   9848:     chop($courses);
1.772     raeburn  9849:     my $ok_response = 0;
                   9850:     my $response;
                   9851:     while (@homeservers > 0 && $ok_response == 0) {
                   9852:         my $server = shift(@homeservers); 
                   9853:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9854:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9855:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9856: 		split(/:/,$response);
1.772     raeburn  9857:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9858:             push(@{$codetitles},&str2array($codetitles_str));
                   9859:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9860:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9861:             $ok_response = 1;
                   9862:         }
                   9863:     }
                   9864:     if ($ok_response) {
1.521     raeburn  9865:         return 'ok';
1.772     raeburn  9866:     } else {
                   9867:         return $response;
1.521     raeburn  9868:     }
                   9869: }
                   9870: 
1.792     raeburn  9871: sub auto_instcode_defaults {
                   9872:     my ($domain,$returnhash,$code_order) = @_;
                   9873:     my @homeservers;
1.841     albertel 9874: 
                   9875:     my %servers = &get_servers($domain,'library');
                   9876:     foreach my $tryserver (keys(%servers)) {
                   9877: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9878: 	    push(@homeservers,$tryserver);
                   9879: 	}
1.792     raeburn  9880:     }
1.841     albertel 9881: 
1.792     raeburn  9882:     my $response;
1.841     albertel 9883:     foreach my $server (@homeservers) {
1.792     raeburn  9884:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9885:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9886: 	
                   9887: 	foreach my $pair (split(/\&/,$response)) {
                   9888: 	    my ($name,$value)=split(/\=/,$pair);
                   9889: 	    if ($name eq 'code_order') {
                   9890: 		@{$code_order} = split(/\&/,&unescape($value));
                   9891: 	    } else {
                   9892: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9893: 	    }
                   9894: 	}
                   9895: 	return 'ok';
1.792     raeburn  9896:     }
1.841     albertel 9897: 
                   9898:     return $response;
1.1003    raeburn  9899: }
                   9900: 
                   9901: sub auto_possible_instcodes {
1.1007    raeburn  9902:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9903:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9904:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9905:         return;
                   9906:     }
1.1003    raeburn  9907:     my (@homeservers,$uhome);
                   9908:     if (defined(&domain($domain,'primary'))) {
                   9909:         $uhome=&domain($domain,'primary');
                   9910:         push(@homeservers,&domain($domain,'primary'));
                   9911:     } else {
                   9912:         my %servers = &get_servers($domain,'library');
                   9913:         foreach my $tryserver (keys(%servers)) {
                   9914:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9915:                 push(@homeservers,$tryserver);
                   9916:             }
                   9917:         }
                   9918:     }
                   9919:     my $response;
                   9920:     foreach my $server (@homeservers) {
                   9921:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9922:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9923:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9924:             split(':',$response);
                   9925:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9926:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9927:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9928:             my ($name,$value)=split('=',$item);
                   9929:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9930:         }
                   9931:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9932:             my ($name,$value)=split('=',$item);
                   9933:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9934:         }
                   9935:         return 'ok';
                   9936:     }
                   9937:     return $response;
                   9938: }
1.792     raeburn  9939: 
1.1010    raeburn  9940: sub auto_courserequest_checks {
                   9941:     my ($dom) = @_;
1.1020    raeburn  9942:     my ($homeserver,%validations);
                   9943:     if ($dom =~ /^$match_domain$/) {
                   9944:         $homeserver = &domain($dom,'primary');
                   9945:     }
                   9946:     unless ($homeserver eq 'no_host') {
                   9947:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9948:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9949:             my @items = split(/&/,$response);
                   9950:             foreach my $item (@items) {
                   9951:                 my ($key,$value) = split('=',$item);
                   9952:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9953:             }
                   9954:         }
                   9955:     }
1.1010    raeburn  9956:     return %validations; 
                   9957: }
                   9958: 
1.1020    raeburn  9959: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9960:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9961:     my ($homeserver,$response);
                   9962:     if ($dom =~ /^$match_domain$/) {
                   9963:         $homeserver = &domain($dom,'primary');
                   9964:     }
1.1172.2.43  raeburn  9965:     unless ($homeserver eq 'no_host') {
                   9966:         my $customdata;
                   9967:         if (ref($custominfo) eq 'HASH') {
                   9968:             $customdata = &freeze_escape($custominfo);
                   9969:         }
1.1020    raeburn  9970:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9971:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9972:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9973:                                     $customdata,$homeserver));
1.1020    raeburn  9974:     }
                   9975:     return $response;
                   9976: }
                   9977: 
1.777     albertel 9978: sub auto_validate_class_sec {
1.918     raeburn  9979:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9980:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9981:     my $ownerlist;
                   9982:     if (ref($owners) eq 'ARRAY') {
                   9983:         $ownerlist = join(',',@{$owners});
                   9984:     } else {
                   9985:         $ownerlist = $owners;
                   9986:     }
1.773     raeburn  9987:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9988:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9989:     return $response;
                   9990: }
                   9991: 
1.1172.2.141  raeburn  9992: sub auto_instsec_reformat {
                   9993:     my ($cdom,$action,$instsecref) = @_;
                   9994:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   9995:     my @homeservers;
                   9996:     if (defined(&domain($cdom,'primary'))) {
                   9997:         push(@homeservers,&domain($cdom,'primary'));
                   9998:     } else {
                   9999:         my %servers = &get_servers($cdom,'library');
                   10000:         foreach my $tryserver (keys(%servers)) {
                   10001:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   10002:                 push(@homeservers,$tryserver);
                   10003:             }
                   10004:         }
                   10005:     }
                   10006:     my $response;
                   10007:     my %reformatted = %{$instsecref};
                   10008:     foreach my $server (@homeservers) {
                   10009:         if (ref($instsecref) eq 'HASH') {
                   10010:             my $info = &freeze_escape($instsecref);
                   10011:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   10012:                                 $action.':'.$info,$server);
                   10013:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   10014:             my @items = split(/&/,$response);
                   10015:             foreach my $item (@items) {
                   10016:                 my ($key,$value) = split(/=/,$item);
                   10017:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   10018:             }
                   10019:         }
                   10020:     }
                   10021:     return %reformatted;
                   10022: }
                   10023: 
1.1172.2.94  raeburn  10024: sub auto_validate_instclasses {
                   10025:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   10026:     my ($homeserver,%validations);
                   10027:     $homeserver = &homeserver($cnum,$cdom);
                   10028:     unless ($homeserver eq 'no_host') {
                   10029:         my $ownerlist;
                   10030:         if (ref($owners) eq 'ARRAY') {
                   10031:             $ownerlist = join(',',@{$owners});
                   10032:         } else {
                   10033:             $ownerlist = $owners;
                   10034:         }
                   10035:         if (ref($classesref) eq 'HASH') {
                   10036:             my $classes = &freeze_escape($classesref);
                   10037:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   10038:                                 ':'.$cdom.':'.$classes,$homeserver);
                   10039:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   10040:                 my @items = split(/&/,$response);
                   10041:                 foreach my $item (@items) {
                   10042:                     my ($key,$value) = split('=',$item);
                   10043:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   10044:                 }
                   10045:             }
                   10046:         }
                   10047:     }
                   10048:     return %validations;
                   10049: }
                   10050: 
1.1172.2.38  raeburn  10051: sub auto_crsreq_update {
                   10052:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  10053:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  10054:     my ($homeserver,%crsreqresponse);
                   10055:     if ($cdom =~ /^$match_domain$/) {
                   10056:         $homeserver = &domain($cdom,'primary');
                   10057:     }
                   10058:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   10059:         my $info;
                   10060:         if (ref($inbound) eq 'HASH') {
                   10061:             $info = &freeze_escape($inbound);
                   10062:         }
                   10063:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   10064:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   10065:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  10066:                             &escape($title).':'.&escape($code).':'.
                   10067:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  10068:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   10069:             my @items = split(/&/,$response);
                   10070:             foreach my $item (@items) {
                   10071:                 my ($key,$value) = split('=',$item);
                   10072:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   10073:             }
                   10074:         }
                   10075:     }
                   10076:     return \%crsreqresponse;
                   10077: }
                   10078: 
1.1172.2.78  raeburn  10079: sub auto_export_grades {
                   10080:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   10081:     my ($homeserver,%exportresponse);
                   10082:     if ($cdom =~ /^$match_domain$/) {
                   10083:         $homeserver = &domain($cdom,'primary');
                   10084:     }
                   10085:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   10086:         my $info;
                   10087:         if (ref($inforef) eq 'HASH') {
                   10088:             $info = &freeze_escape($inforef);
                   10089:         }
                   10090:         if (ref($gradesref) eq 'HASH') {
                   10091:             my $grades = &freeze_escape($gradesref);
                   10092:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   10093:                                 $info.':'.$grades,$homeserver);
                   10094:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   10095:                 my @items = split(/&/,$response);
                   10096:                 foreach my $item (@items) {
                   10097:                     my ($key,$value) = split('=',$item);
                   10098:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   10099:                 }
                   10100:             }
                   10101:         }
                   10102:     }
                   10103:     return \%exportresponse;
                   10104: }
                   10105: 
1.1172.2.68  raeburn  10106: sub check_instcode_cloning {
                   10107:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   10108:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   10109:         return;
                   10110:     }
                   10111:     my $canclone;
                   10112:     if (@{$code_order} > 0) {
                   10113:         my $instcoderegexp ='^';
                   10114:         my @clonecodes = split(/\&/,$cloner);
                   10115:         foreach my $item (@{$code_order}) {
                   10116:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   10117:                 foreach my $pair (@clonecodes) {
                   10118:                     my ($key,$val) = split(/\=/,$pair,2);
                   10119:                     $val = &unescape($val);
                   10120:                     if ($key eq $item) {
                   10121:                         $instcoderegexp .= '('.$val.')';
                   10122:                         last;
                   10123:                     }
                   10124:                 }
                   10125:             } else {
                   10126:                 $instcoderegexp .= $codedefaults->{$item};
                   10127:             }
                   10128:         }
                   10129:         $instcoderegexp .= '$';
                   10130:         my (@from,@to);
                   10131:         eval {
                   10132:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10133:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10134:         };
                   10135:         if ((@from > 0) && (@to > 0)) {
                   10136:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10137:             if (!@diffs) {
                   10138:                 $canclone = 1;
                   10139:             }
                   10140:         }
                   10141:     }
                   10142:     return $canclone;
                   10143: }
                   10144: 
                   10145: sub default_instcode_cloning {
                   10146:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   10147:     my (%codedefaults,@code_order,$canclone);
                   10148:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   10149:         %codedefaults = %{$codedefaultsref};
                   10150:         @code_order = @{$codeorderref};
                   10151:     } elsif ($clonedom) {
                   10152:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   10153:     }
                   10154:     if (($domdefclone) && (@code_order)) {
                   10155:         my @clonecodes = split(/\+/,$domdefclone);
                   10156:         my $instcoderegexp ='^';
                   10157:         foreach my $item (@code_order) {
                   10158:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   10159:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   10160:             } else {
                   10161:                 $instcoderegexp .= $codedefaults{$item};
                   10162:             }
                   10163:         }
                   10164:         $instcoderegexp .= '$';
                   10165:         my (@from,@to);
                   10166:         eval {
                   10167:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10168:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10169:         };
                   10170:         if ((@from > 0) && (@to > 0)) {
                   10171:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10172:             if (!@diffs) {
                   10173:                 $canclone = 1;
                   10174:             }
                   10175:         }
                   10176:     }
                   10177:     return $canclone;
                   10178: }
                   10179: 
1.679     raeburn  10180: # ------------------------------------------------------- Course Group routines
                   10181: 
                   10182: sub get_coursegroups {
1.809     raeburn  10183:     my ($cdom,$cnum,$group,$namespace) = @_;
                   10184:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  10185: }
                   10186: 
1.679     raeburn  10187: sub modify_coursegroup {
                   10188:     my ($cdom,$cnum,$groupsettings) = @_;
                   10189:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   10190: }
                   10191: 
1.809     raeburn  10192: sub toggle_coursegroup_status {
                   10193:     my ($cdom,$cnum,$group,$action) = @_;
                   10194:     my ($from_namespace,$to_namespace);
                   10195:     if ($action eq 'delete') {
                   10196:         $from_namespace = 'coursegroups';
                   10197:         $to_namespace = 'deleted_groups';
                   10198:     } else {
                   10199:         $from_namespace = 'deleted_groups';
                   10200:         $to_namespace = 'coursegroups';
                   10201:     }
                   10202:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  10203:     if (my $tmp = &error(%curr_group)) {
                   10204:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   10205:         return ('read error',$tmp);
                   10206:     } else {
                   10207:         my %savedsettings = %curr_group; 
1.809     raeburn  10208:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  10209:         my $deloutcome;
                   10210:         if ($result eq 'ok') {
1.809     raeburn  10211:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  10212:         } else {
                   10213:             return ('write error',$result);
                   10214:         }
                   10215:         if ($deloutcome eq 'ok') {
                   10216:             return 'ok';
                   10217:         } else {
                   10218:             return ('delete error',$deloutcome);
                   10219:         }
                   10220:     }
                   10221: }
                   10222: 
1.679     raeburn  10223: sub modify_group_roles {
1.957     raeburn  10224:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  10225:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   10226:     my $role = 'gr/'.&escape($userprivs);
                   10227:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  10228:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  10229:     if ($result eq 'ok') {
                   10230:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   10231:     }
1.679     raeburn  10232:     return $result;
                   10233: }
                   10234: 
                   10235: sub modify_coursegroup_membership {
                   10236:     my ($cdom,$cnum,$membership) = @_;
                   10237:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   10238:     return $result;
                   10239: }
                   10240: 
1.682     raeburn  10241: sub get_active_groups {
                   10242:     my ($udom,$uname,$cdom,$cnum) = @_;
                   10243:     my $now = time;
                   10244:     my %groups = ();
                   10245:     foreach my $key (keys(%env)) {
1.811     albertel 10246:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  10247:             my ($start,$end) = split(/\./,$env{$key});
                   10248:             if (($end!=0) && ($end<$now)) { next; }
                   10249:             if (($start!=0) && ($start>$now)) { next; }
                   10250:             if ($1 eq $cdom && $2 eq $cnum) {
                   10251:                 $groups{$3} = $env{$key} ;
                   10252:             }
                   10253:         }
                   10254:     }
                   10255:     return %groups;
                   10256: }
                   10257: 
1.683     raeburn  10258: sub get_group_membership {
                   10259:     my ($cdom,$cnum,$group) = @_;
                   10260:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   10261: }
                   10262: 
                   10263: sub get_users_groups {
                   10264:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  10265:     my @usersgroups;
1.683     raeburn  10266:     my $cachetime=1800;
                   10267: 
                   10268:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  10269:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   10270:     if (defined($cached)) {
1.734     albertel 10271:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  10272:     } else {  
                   10273:         $grouplist = '';
1.816     raeburn  10274:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  10275:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  10276:         my $access_end = $env{'course.'.$courseid.
                   10277:                               '.default_enrollment_end_date'};
                   10278:         my $now = time;
                   10279:         foreach my $key (keys(%roleshash)) {
                   10280:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   10281:                 my $group = $1;
                   10282:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   10283:                     my $start = $2;
                   10284:                     my $end = $1;
                   10285:                     if ($start == -1) { next; } # deleted from group
                   10286:                     if (($start!=0) && ($start>$now)) { next; }
                   10287:                     if (($end!=0) && ($end<$now)) {
                   10288:                         if ($access_end && $access_end < $now) {
                   10289:                             if ($access_end - $end < 86400) {
                   10290:                                 push(@usersgroups,$group);
1.733     raeburn  10291:                             }
                   10292:                         }
1.817     raeburn  10293:                         next;
1.733     raeburn  10294:                     }
1.817     raeburn  10295:                     push(@usersgroups,$group);
1.683     raeburn  10296:                 }
                   10297:             }
                   10298:         }
1.817     raeburn  10299:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   10300:         $grouplist = join(':',@usersgroups);
                   10301:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  10302:     }
1.733     raeburn  10303:     return @usersgroups;
1.683     raeburn  10304: }
                   10305: 
                   10306: sub devalidate_getgroups_cache {
                   10307:     my ($udom,$uname,$cdom,$cnum)=@_;
                   10308:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 10309: 
1.683     raeburn  10310:     my $hashid="$udom:$uname:$courseid";
                   10311:     &devalidate_cache_new('getgroups',$hashid);
                   10312: }
                   10313: 
1.12      www      10314: # ------------------------------------------------------------------ Plain Text
                   10315: 
                   10316: sub plaintext {
1.988     raeburn  10317:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  10318:     if ($short =~ m{^cr/}) {
1.758     albertel 10319: 	return (split('/',$short))[-1];
                   10320:     }
1.742     raeburn  10321:     if (!defined($cid)) {
                   10322:         $cid = $env{'request.course.id'};
                   10323:     }
                   10324:     my %rolenames = (
1.1008    raeburn  10325:                       Course    => 'std',
                   10326:                       Community => 'alt1',
1.742     raeburn  10327:                     );
1.1037    raeburn  10328:     if ($cid ne '') {
                   10329:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   10330:             unless ($forcedefault) {
                   10331:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   10332:                 &Apache::lonlocal::mt_escape(\$roletext);
                   10333:                 return &Apache::lonlocal::mt($roletext);
                   10334:             }
                   10335:         }
                   10336:     }
                   10337:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   10338:         (defined($rolenames{$type})) && 
                   10339:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  10340:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  10341:     } elsif ($cid ne '') {
                   10342:         my $crstype = $env{'course.'.$cid.'.type'};
                   10343:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   10344:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   10345:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   10346:         }
1.742     raeburn  10347:     }
1.1037    raeburn  10348:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      10349: }
                   10350: 
                   10351: # ----------------------------------------------------------------- Assign Role
                   10352: 
                   10353: sub assignrole {
1.957     raeburn  10354:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   10355:         $context)=@_;
1.21      www      10356:     my $mrole;
                   10357:     if ($role =~ /^cr\//) {
1.393     www      10358:         my $cwosec=$url;
1.811     albertel 10359:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      10360: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  10361:            my $refused = 1;
                   10362:            if ($context eq 'requestcourses') {
                   10363:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   10364:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   10365:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   10366:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10367:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10368:                            if ($crsenv{'internal.courseowner'} eq
                   10369:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   10370:                                $refused = '';
                   10371:                            }
                   10372:                        }
                   10373:                    }
                   10374:                }
                   10375:            }
                   10376:            if ($refused) {
                   10377:                &logthis('Refused custom assignrole: '.
                   10378:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   10379:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   10380:                return 'refused';
                   10381:            }
1.104     www      10382:         }
1.21      www      10383:         $mrole='cr';
1.678     raeburn  10384:     } elsif ($role =~ /^gr\//) {
                   10385:         my $cwogrp=$url;
1.811     albertel 10386:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  10387:         unless (&allowed('mdg',$cwogrp)) {
                   10388:             &logthis('Refused group assignrole: '.
                   10389:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   10390:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   10391:             return 'refused';
                   10392:         }
                   10393:         $mrole='gr';
1.21      www      10394:     } else {
1.82      www      10395:         my $cwosec=$url;
1.811     albertel 10396:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  10397:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   10398:             my $refused;
                   10399:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   10400:                 if (!(&allowed('c'.$role,$url))) {
                   10401:                     $refused = 1;
                   10402:                 }
                   10403:             } else {
                   10404:                 $refused = 1;
                   10405:             }
1.947     raeburn  10406:             if ($refused) {
1.1045    raeburn  10407:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10408:                 if (!$selfenroll && $context eq 'course') {
                   10409:                     my %crsenv;
                   10410:                     if ($role eq 'cc' || $role eq 'co') {
                   10411:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10412:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   10413:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   10414:                                 if ($crsenv{'internal.courseowner'} eq 
                   10415:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10416:                                     $refused = '';
                   10417:                                 }
                   10418:                             }
                   10419:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   10420:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   10421:                                 if ($crsenv{'internal.courseowner'} eq 
                   10422:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10423:                                     $refused = '';
                   10424:                                 }
                   10425:                             }
                   10426:                         }
                   10427:                     }
1.1172.2.146.  .13(raeb 10428:-23):                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   10429:-23):                     if ($role eq 'st') {
                   10430:-23):                         $refused = '';
                   10431:-23):                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
                   10432:-23):                         $refused = '';
                   10433:-23):                     }
1.1017    raeburn  10434:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10435:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10436:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10437:                         my $wrongcc;
                   10438:                         if ($cnum =~ /^$match_community$/) {
                   10439:                             $wrongcc = 1 if ($role eq 'cc');
                   10440:                         } else {
                   10441:                             $wrongcc = 1 if ($role eq 'co');
                   10442:                         }
                   10443:                         unless ($wrongcc) {
                   10444:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10445:                             if ($crsenv{'internal.courseowner'} eq 
                   10446:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10447:                                 $refused = '';
                   10448:                             }
1.1017    raeburn  10449:                         }
                   10450:                     }
1.1172.2.9  raeburn  10451:                 } elsif ($context eq 'requestauthor') {
                   10452:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   10453:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10454:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10455:                             $refused = '';
                   10456:                         } else {
                   10457:                             my %domdefaults = &get_domain_defaults($udom);
                   10458:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10459:                                 my $checkbystatus;
                   10460:                                 if ($env{'user.adv'}) {
                   10461:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10462:                                     if ($disposition eq 'automatic') {
                   10463:                                         $refused = '';
                   10464:                                     } elsif ($disposition eq '') {
                   10465:                                         $checkbystatus = 1;
                   10466:                                     }
                   10467:                                 } else {
                   10468:                                     $checkbystatus = 1;
                   10469:                                 }
                   10470:                                 if ($checkbystatus) {
                   10471:                                     if ($env{'environment.inststatus'}) {
                   10472:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10473:                                         foreach my $type (@inststatuses) {
                   10474:                                             if (($type ne '') &&
                   10475:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10476:                                                 $refused = '';
                   10477:                                             }
                   10478:                                         }
                   10479:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10480:                                         $refused = '';
                   10481:                                     }
                   10482:                                 }
                   10483:                             }
                   10484:                         }
                   10485:                     }
1.1017    raeburn  10486:                 }
                   10487:                 if ($refused) {
1.947     raeburn  10488:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10489:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10490: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10491:                     return 'refused';
                   10492:                 }
1.932     raeburn  10493:             }
1.1131    raeburn  10494:         } elsif ($role eq 'au') {
                   10495:             if ($url ne '/'.$udom.'/') {
                   10496:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10497:                          ' to assign author role for '.$uname.':'.$udom.
                   10498:                          ' in domain: '.$url.' refused (wrong domain).');
                   10499:                 return 'refused';
                   10500:             }
1.104     www      10501:         }
1.21      www      10502:         $mrole=$role;
                   10503:     }
1.620     albertel 10504:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10505:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10506:     if ($end) { $command.='_'.$end; }
1.21      www      10507:     if ($start) {
                   10508: 	if ($end) { 
1.81      www      10509:            $command.='_'.$start; 
1.21      www      10510:         } else {
1.81      www      10511:            $command.='_0_'.$start;
1.21      www      10512:         }
                   10513:     }
1.739     raeburn  10514:     my $origstart = $start;
                   10515:     my $origend = $end;
1.957     raeburn  10516:     my $delflag;
1.357     www      10517: # actually delete
                   10518:     if ($deleteflag) {
1.373     www      10519: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10520: # modify command to delete the role
1.620     albertel 10521:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10522:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10523: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10524: # set start and finish to negative values for userrolelog
                   10525:            $start=-1;
                   10526:            $end=-1;
1.957     raeburn  10527:            $delflag = 1;
1.357     www      10528:         }
                   10529:     }
                   10530: # send command
1.349     www      10531:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      10532: # log new user role if status is ok
1.349     www      10533:     if ($answer eq 'ok') {
1.663     raeburn  10534: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  10535:         if (($role eq 'cc') || ($role eq 'in') ||
                   10536:             ($role eq 'ep') || ($role eq 'ad') ||
                   10537:             ($role eq 'ta') || ($role eq 'st') ||
                   10538:             ($role=~/^cr/) || ($role eq 'gr') ||
                   10539:             ($role eq 'co')) {
1.1172.2.13  raeburn  10540: # for course roles, perform group memberships changes triggered by role change.
                   10541:             unless ($role =~ /^gr/) {
                   10542:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10543:                                                  $origstart,$selfenroll,$context);
                   10544:             }
1.1172.2.9  raeburn  10545:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10546:                            $selfenroll,$context);
                   10547:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  10548:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10549:                  ($role eq 'da')) {
1.1172.2.9  raeburn  10550:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10551:                            $context);
                   10552:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10553:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10554:                              $context);
                   10555:         }
1.1053    raeburn  10556:         if ($role eq 'cc') {
                   10557:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10558:         }
1.349     www      10559:     }
                   10560:     return $answer;
1.169     harris41 10561: }
                   10562: 
1.1053    raeburn  10563: sub autoupdate_coowners {
                   10564:     my ($url,$end,$start,$uname,$udom) = @_;
                   10565:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10566:     if (($cdom ne '') && ($cnum ne '')) {
                   10567:         my $now = time;
                   10568:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10569:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10570:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10571:             my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141  raeburn  10572:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  10573:             if ($instcode ne '') {
1.1056    raeburn  10574:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10575:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10576:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10577:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141  raeburn  10578:                         unless ($result eq 'valid') {
                   10579:                             if ($xlists ne '') {
                   10580:                                 foreach my $xlist (split(',',$xlists)) {
                   10581:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   10582:                                     $result =
                   10583:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   10584:                                                                       $inst_crosslist,$uname.':'.$udom);
                   10585:                                     last if ($result eq 'valid');
                   10586:                                 }
                   10587:                             }
                   10588:                         }
1.1056    raeburn  10589:                         if ($result eq 'valid') {
                   10590:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10591:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10592:                                     push(@newcoowners,$coowner);
                   10593:                                 }
                   10594:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10595:                                     push(@newcoowners,$uname.':'.$udom);
                   10596:                                 }
                   10597:                                 @newcoowners = sort(@newcoowners);
                   10598:                             } else {
                   10599:                                 push(@newcoowners,$uname.':'.$udom);
                   10600:                             }
1.1172.2.141  raeburn  10601:                         } elsif ($coursehash{'internal.co-owners'}) {
                   10602:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10603:                                 unless ($coowner eq $uname.':'.$udom) {
                   10604:                                     push(@newcoowners,$coowner);
1.1053    raeburn  10605:                                 }
                   10606:                             }
1.1172.2.141  raeburn  10607:                             unless (@newcoowners > 0) {
                   10608:                                 $delcoowners = 1;
                   10609:                                 $coowners = '';
                   10610:                             }
1.1053    raeburn  10611:                         }
                   10612:                         if (@newcoowners || $delcoowners) {
                   10613:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10614:                                             $delcoowners,@newcoowners);
                   10615:                         }
                   10616:                     }
                   10617:                 }
                   10618:             }
                   10619:         }
                   10620:     }
                   10621: }
                   10622: 
                   10623: sub store_coowners {
                   10624:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10625:     my $cid = $cdom.'_'.$cnum;
                   10626:     my ($coowners,$delresult,$putresult);
                   10627:     if (@newcoowners) {
                   10628:         $coowners = join(',',@newcoowners);
                   10629:         my %coownershash = (
                   10630:                             'internal.co-owners' => $coowners,
                   10631:                            );
                   10632:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10633:         if ($putresult eq 'ok') {
                   10634:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10635:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10636:             }
                   10637:         }
                   10638:     }
                   10639:     if ($delcoowners) {
                   10640:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10641:         if ($delresult eq 'ok') {
                   10642:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10643:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10644:             }
                   10645:         }
                   10646:     }
                   10647:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10648:         my %crsinfo =
                   10649:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10650:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10651:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10652:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10653:         }
                   10654:     }
                   10655: }
                   10656: 
1.169     harris41 10657: # -------------------------------------------------- Modify user authentication
1.197     www      10658: # Overrides without validation
                   10659: 
1.169     harris41 10660: sub modifyuserauth {
                   10661:     my ($udom,$uname,$umode,$upass)=@_;
                   10662:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  10663:     my $allowed;
                   10664:     if (&allowed('mau',$udom)) {
                   10665:         $allowed = 1;
                   10666:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10667:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10668:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10669:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10670:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10671:         if (($cdom ne '') && ($cnum ne '')) {
                   10672:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10673:             if ($is_owner) {
                   10674:                 $allowed = 1;
                   10675:             }
                   10676:         }
                   10677:     }
                   10678:     unless ($allowed) { return 'refused'; }
1.197     www      10679:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10680:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10681:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10682:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10683: 		     &escape($upass),$uhome);
1.1172.2.134  raeburn  10684:     my $ip = &get_requestor_ip();
1.620     albertel 10685:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10686:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134  raeburn  10687:          '(Remote '.$ip.'): '.$reply);
1.197     www      10688:     &log($udom,,$uname,$uhome,
1.620     albertel 10689:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10690:                                      $env{'user.name'}.', '.$umode.
1.1172.2.134  raeburn  10691:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10692:     unless ($reply eq 'ok') {
1.197     www      10693:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10694: 	return 'error: '.$reply;
                   10695:     }   
1.170     harris41 10696:     return 'ok';
1.80      www      10697: }
                   10698: 
1.81      www      10699: # --------------------------------------------------------------- Modify a user
1.80      www      10700: 
1.81      www      10701: sub modifyuser {
1.206     matthew  10702:     my ($udom,    $uname, $uid,
                   10703:         $umode,   $upass, $first,
                   10704:         $middle,  $last,  $gene,
1.1058    raeburn  10705:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10706:     $udom= &LONCAPA::clean_domain($udom);
                   10707:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10708:     my $showcandelete = 'none';
                   10709:     if (ref($candelete) eq 'ARRAY') {
                   10710:         if (@{$candelete} > 0) {
                   10711:             $showcandelete = join(', ',@{$candelete});
                   10712:         }
                   10713:     }
1.81      www      10714:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10715:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10716: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10717:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10718:                                      ' desiredhome not specified'). 
1.620     albertel 10719:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10720:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10721:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10722:     my $newuser;
                   10723:     if ($uhome eq 'no_host') {
                   10724:         $newuser = 1;
1.1172.2.146.  .13(raeb 10725:-23):         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   10726:-23):                 ($umode eq 'lti')) {
                   10727:-23):             return 'error: more information needed to create new user';
                   10728:-23):         }
1.1075    raeburn  10729:     }
1.80      www      10730: # ----------------------------------------------------------------- Create User
1.406     albertel 10731:     if (($uhome eq 'no_host') && 
1.1172.2.146.  .13(raeb 10732:-23): 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      10733:         my $unhome='';
1.844     albertel 10734:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10735:             $unhome = $desiredhome;
1.620     albertel 10736: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10737: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10738:         } else { # load balancing routine for determining $unhome
1.81      www      10739:             my $loadm=10000000;
1.841     albertel 10740: 	    my %servers = &get_servers($udom,'library');
                   10741: 	    foreach my $tryserver (keys(%servers)) {
                   10742: 		my $answer=reply('load',$tryserver);
                   10743: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10744: 		    $loadm=$answer;
                   10745: 		    $unhome=$tryserver;
                   10746: 		}
1.80      www      10747: 	    }
                   10748:         }
                   10749:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10750: 	    return 'error: unable to find a home server for '.$uname.
                   10751:                    ' in domain '.$udom;
1.80      www      10752:         }
                   10753:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10754:                          &escape($upass),$unhome);
                   10755: 	unless ($reply eq 'ok') {
                   10756:             return 'error: '.$reply;
                   10757:         }   
1.230     stredwic 10758:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10759:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10760: 	    return 'error: unable verify users home machine.';
1.80      www      10761:         }
1.209     matthew  10762:     }   # End of creation of new user
1.80      www      10763: # ---------------------------------------------------------------------- Add ID
                   10764:     if ($uid) {
                   10765:        $uid=~tr/A-Z/a-z/;
                   10766:        my %uidhash=&idrget($udom,$uname);
1.196     www      10767:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10768:          && (!$forceid)) {
1.80      www      10769: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10770: 	      return 'error: user id "'.$uid.'" does not match '.
                   10771:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10772:           }
                   10773:        } else {
                   10774: 	  &idput($udom,($uname => $uid));
                   10775:        }
                   10776:     }
                   10777: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10778:     my @tmp=&get('environment',
1.899     raeburn  10779: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10780:                     'permanentemail','inststatus'],
1.134     albertel 10781: 		   $udom,$uname);
1.1075    raeburn  10782:     my (%names,%oldnames);
1.313     matthew  10783:     if ($tmp[0] =~ m/^error:.*/) { 
                   10784:         %names=(); 
                   10785:     } else {
                   10786:         %names = @tmp;
1.1075    raeburn  10787:         %oldnames = %names;
1.313     matthew  10788:     }
1.388     www      10789: #
1.1058    raeburn  10790: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10791: # of users did not contain them), do not overwrite existing values
                   10792: # unless field is in $candelete array ref.  
                   10793: #
                   10794: 
                   10795:     my @fields = ('firstname','middlename','lastname','generation',
                   10796:                   'permanentemail','id');
                   10797:     my %newvalues;
                   10798:     if (ref($candelete) eq 'ARRAY') {
                   10799:         foreach my $field (@fields) {
                   10800:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10801:                 if ($field eq 'firstname') {
                   10802:                     $names{$field} = $first;
                   10803:                 } elsif ($field eq 'middlename') {
                   10804:                     $names{$field} = $middle;
                   10805:                 } elsif ($field eq 'lastname') {
                   10806:                     $names{$field} = $last;
                   10807:                 } elsif ($field eq 'generation') { 
                   10808:                     $names{$field} = $gene;
                   10809:                 } elsif ($field eq 'permanentemail') {
                   10810:                     $names{$field} = $email;
                   10811:                 } elsif ($field eq 'id') {
                   10812:                     $names{$field}  = $uid;
                   10813:                 }
                   10814:             }
                   10815:         }
                   10816:     }
1.388     www      10817:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10818:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10819:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10820:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10821:     if ($email) {
                   10822:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10823:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10824:     }
1.899     raeburn  10825:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10826:     if (defined($inststatus)) {
                   10827:         $names{'inststatus'} = '';
                   10828:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10829:         if (ref($usertypes) eq 'HASH') {
                   10830:             my @okstatuses; 
                   10831:             foreach my $item (split(/:/,$inststatus)) {
                   10832:                 if (defined($usertypes->{$item})) {
                   10833:                     push(@okstatuses,$item);  
                   10834:                 }
                   10835:             }
                   10836:             if (@okstatuses) {
                   10837:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10838:             }
                   10839:         }
                   10840:     }
1.1075    raeburn  10841:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10842:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10843:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10844:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10845:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10846:     } else {
                   10847:         $logmsg .= ' during self creation';
                   10848:     }
1.1075    raeburn  10849:     my $changed;
                   10850:     if ($newuser) {
                   10851:         $changed = 1;
                   10852:     } else {
                   10853:         foreach my $field (@fields) {
                   10854:             if ($names{$field} ne $oldnames{$field}) {
                   10855:                 $changed = 1;
                   10856:                 last;
                   10857:             }
                   10858:         }
                   10859:     }
                   10860:     unless ($changed) {
                   10861:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10862:         &logthis($logmsg);
                   10863:         return 'ok';
                   10864:     }
                   10865:     my $reply = &put('environment', \%names, $udom,$uname);
                   10866:     if ($reply ne 'ok') { 
                   10867:         return 'error: '.$reply;
                   10868:     }
1.1087    raeburn  10869:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10870:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10871:     }
1.1075    raeburn  10872:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10873:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10874:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10875:     &logthis($logmsg);
1.134     albertel 10876:     return 'ok';
1.80      www      10877: }
                   10878: 
1.81      www      10879: # -------------------------------------------------------------- Modify student
1.80      www      10880: 
1.81      www      10881: sub modifystudent {
                   10882:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10883:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10884:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10885:     if (!$cid) {
1.620     albertel 10886: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10887: 	    return 'not_in_class';
                   10888: 	}
1.80      www      10889:     }
                   10890: # --------------------------------------------------------------- Make the user
1.81      www      10891:     my $reply=&modifyuser
1.209     matthew  10892: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10893:          $desiredhome,$email,$inststatus);
1.80      www      10894:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10895:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10896:     # student's environment
1.297     matthew  10897:     $uid = undef if (!$forceid);
1.455     albertel 10898:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10899: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10900:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10901:     return $reply;
                   10902: }
                   10903: 
                   10904: sub modify_student_enrollment {
1.1172.2.23  raeburn  10905:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10906:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10907:     my ($cdom,$cnum,$chome);
                   10908:     if (!$cid) {
1.620     albertel 10909: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10910: 	    return 'not_in_class';
                   10911: 	}
1.620     albertel 10912: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10913: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10914:     } else {
                   10915: 	($cdom,$cnum)=split(/_/,$cid);
                   10916:     }
1.620     albertel 10917:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10918:     if (!$chome) {
1.457     raeburn  10919: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10920:     }
1.455     albertel 10921:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10922:     # Make sure the user exists
1.81      www      10923:     my $uhome=&homeserver($uname,$udom);
                   10924:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10925: 	return 'error: no such user';
                   10926:     }
1.297     matthew  10927:     # Get student data if we were not given enough information
                   10928:     if (!defined($first)  || $first  eq '' || 
                   10929:         !defined($last)   || $last   eq '' || 
                   10930:         !defined($uid)    || $uid    eq '' || 
                   10931:         !defined($middle) || $middle eq '' || 
                   10932:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10933:         # They did not supply us with enough data to enroll the student, so
                   10934:         # we need to pick up more information.
1.297     matthew  10935:         my %tmp = &get('environment',
1.294     matthew  10936:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10937:                        ,$udom,$uname);
                   10938: 
1.800     albertel 10939:         #foreach my $key (keys(%tmp)) {
                   10940:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10941:         #}
1.294     matthew  10942:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10943:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10944:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10945:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10946:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10947:     }
1.556     albertel 10948:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10949:     my $user = "$uname:$udom";
                   10950:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10951:     my $reply=cput('classlist',
1.1148    raeburn  10952: 		   {$user => 
1.1172.2.76  raeburn  10953: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10954: 		   $cdom,$cnum);
1.1148    raeburn  10955:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10956:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10957:     } else { 
1.81      www      10958: 	return 'error: '.$reply;
                   10959:     }
1.297     matthew  10960:     # Add student role to user
1.83      www      10961:     my $uurl='/'.$cid;
1.81      www      10962:     $uurl=~s/\_/\//g;
                   10963:     if ($usec) {
                   10964: 	$uurl.='/'.$usec;
                   10965:     }
1.1148    raeburn  10966:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10967:                              $selfenroll,$context);
                   10968:     if ($result ne 'ok') {
                   10969:         if ($old_entry{$user} ne '') {
                   10970:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10971:         } else {
                   10972:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10973:         }
                   10974:     }
                   10975:     return $result; 
1.21      www      10976: }
                   10977: 
1.556     albertel 10978: sub format_name {
                   10979:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10980:     my $name;
                   10981:     if ($first ne 'lastname') {
                   10982: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10983:     } else {
                   10984: 	if ($lastname=~/\S/) {
                   10985: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10986: 	    $name=~s/\s+,/,/;
                   10987: 	} else {
                   10988: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10989: 	}
                   10990:     }
                   10991:     $name=~s/^\s+//;
                   10992:     $name=~s/\s+$//;
                   10993:     $name=~s/\s+/ /g;
                   10994:     return $name;
                   10995: }
                   10996: 
1.84      www      10997: # ------------------------------------------------- Write to course preferences
                   10998: 
                   10999: sub writecoursepref {
                   11000:     my ($courseid,%prefs)=@_;
                   11001:     $courseid=~s/^\///;
                   11002:     $courseid=~s/\_/\//g;
                   11003:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   11004:     my $chome=homeserver($cnum,$cdomain);
                   11005:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   11006: 	return 'error: no such course';
                   11007:     }
                   11008:     my $cstring='';
1.800     albertel 11009:     foreach my $pref (keys(%prefs)) {
                   11010: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 11011:     }
1.84      www      11012:     $cstring=~s/\&$//;
                   11013:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   11014: }
                   11015: 
                   11016: # ---------------------------------------------------------- Make/modify course
                   11017: 
                   11018: sub createcourse {
1.741     raeburn  11019:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.146.  .1(raebu 11020:22):         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      11021:     $url=&declutter($url);
                   11022:     my $cid='';
1.1028    raeburn  11023:     if ($context eq 'requestcourses') {
                   11024:         my $can_create = 0;
                   11025:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   11026:         if ($udom eq $ownerdom) {
1.1172.2.146.  .1(raebu 11027:22):             my $reload;
                   11028:22):             if (($callercontext eq 'auto') &&
                   11029:22):                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   11030:22):                 $reload = 'reload';
                   11031:22):             }
                   11032:22):             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  11033:                                   $context)) {
                   11034:                 $can_create = 1;
                   11035:             }
                   11036:         } else {
                   11037:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   11038:                                            $category);
                   11039:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   11040:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   11041:                 if (@curr > 0) {
                   11042:                     my @options = qw(approval validate autolimit);
                   11043:                     my $optregex = join('|',@options);
                   11044:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   11045:                         $can_create = 1;
                   11046:                     }
                   11047:                 }
                   11048:             }
                   11049:         }
                   11050:         if ($can_create) {
                   11051:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   11052:                 unless (&allowed('ccc',$udom)) {
                   11053:                     return 'refused'; 
                   11054:                 }
1.1017    raeburn  11055:             }
                   11056:         } else {
                   11057:             return 'refused';
                   11058:         }
1.1028    raeburn  11059:     } elsif (!&allowed('ccc',$udom)) {
                   11060:         return 'refused';
1.84      www      11061:     }
1.1011    raeburn  11062: # --------------------------------------------------------------- Get Unique ID
                   11063:     my $uname;
                   11064:     if ($cnum =~ /^$match_courseid$/) {
                   11065:         my $chome=&homeserver($cnum,$udom,'true');
                   11066:         if (($chome eq '') || ($chome eq 'no_host')) {
                   11067:             $uname = $cnum;
                   11068:         } else {
1.1038    raeburn  11069:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  11070:         }
                   11071:     } else {
1.1038    raeburn  11072:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  11073:     }
                   11074:     return $uname if ($uname =~ /^error/);
                   11075: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  11076:     if (!defined($course_server)) {
                   11077:         if (defined(&domain($udom,'primary'))) {
                   11078:             $course_server = &domain($udom,'primary');
                   11079:         } else {
                   11080:             $course_server = $env{'user.home'}; 
                   11081:         }
                   11082:     }
                   11083:     my %host_servers =
                   11084:         &Apache::lonnet::get_servers($udom,'library');
                   11085:     unless ($host_servers{$course_server}) {
                   11086:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  11087:     }
1.84      www      11088: # ------------------------------------------------------------- Make the course
                   11089:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  11090:                       $course_server);
1.84      www      11091:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  11092:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      11093:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   11094: 	return 'error: no such course';
                   11095:     }
1.271     www      11096: # ----------------------------------------------------------------- Course made
1.516     raeburn  11097: # log existence
1.1029    raeburn  11098:     my $now = time;
1.918     raeburn  11099:     my $newcourse = {
                   11100:                     $udom.'_'.$uname => {
1.921     raeburn  11101:                                      description => $description,
                   11102:                                      inst_code   => $inst_code,
                   11103:                                      owner       => $course_owner,
                   11104:                                      type        => $crstype,
1.1029    raeburn  11105:                                      creator     => $env{'user.name'}.':'.
                   11106:                                                     $env{'user.domain'},
                   11107:                                      created     => $now,
                   11108:                                      context     => $context,
1.918     raeburn  11109:                                                 },
                   11110:                     };
1.921     raeburn  11111:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      11112: # set toplevel url
1.271     www      11113:     my $topurl=$url;
                   11114:     unless ($nonstandard) {
                   11115: # ------------------------------------------ For standard courses, make top url
                   11116:         my $mapurl=&clutter($url);
1.278     www      11117:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 11118:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      11119: <map>
                   11120: <resource id="1" type="start"></resource>
                   11121: <resource id="2" src="$mapurl"></resource>
                   11122: <resource id="3" type="finish"></resource>
                   11123: <link index="1" from="1" to="2"></link>
                   11124: <link index="2" from="2" to="3"></link>
                   11125: </map>
                   11126: ENDINITMAP
                   11127:         $topurl=&declutter(
1.638     albertel 11128:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      11129:                           );
                   11130:     }
                   11131: # ----------------------------------------------------------- Write preferences
1.84      www      11132:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  11133:                      ('description'              => $description,
                   11134:                       'url'                      => $topurl,
                   11135:                       'internal.creator'         => $env{'user.name'}.':'.
                   11136:                                                     $env{'user.domain'},
                   11137:                       'internal.created'         => $now,
                   11138:                       'internal.creationcontext' => $context)
                   11139:                     );
1.84      www      11140:     return '/'.$udom.'/'.$uname;
                   11141: }
                   11142: 
1.1011    raeburn  11143: # ------------------------------------------------------------------- Create ID
                   11144: sub generate_coursenum {
1.1038    raeburn  11145:     my ($udom,$crstype) = @_;
1.1011    raeburn  11146:     my $domdesc = &domain($udom);
                   11147:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  11148:     my $first;
                   11149:     if ($crstype eq 'Community') {
                   11150:         $first = '0';
                   11151:     } else {
                   11152:         $first = int(1+rand(9)); 
                   11153:     } 
                   11154:     my $uname=$first.
1.1011    raeburn  11155:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11156:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11157:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11158: # ----------------------------------------------- Make sure that does not exist
                   11159:     my $uhome=&homeserver($uname,$udom,'true');
                   11160:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  11161:         if ($crstype eq 'Community') {
                   11162:             $first = '0';
                   11163:         } else {
                   11164:             $first = int(1+rand(9));
                   11165:         }
                   11166:         $uname=$first.
1.1011    raeburn  11167:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11168:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11169:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11170:         $uhome=&homeserver($uname,$udom,'true');
                   11171:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   11172:             return 'error: unable to generate unique course-ID';
                   11173:         }
                   11174:     }
                   11175:     return $uname;
                   11176: }
                   11177: 
1.813     albertel 11178: sub is_course {
1.1167    droeschl 11179:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   11180:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  11181:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   11182:     my $uhome=&homeserver($cnum,$cdom);
                   11183:     my $iscourse;
                   11184:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   11185:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   11186:     } else {
                   11187:         my $hashid = $cdom.':'.$cnum;
                   11188:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   11189:         unless (defined($cached)) {
                   11190:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   11191:                                         $cnum,undef,undef,'.');
                   11192:             $iscourse = 0;
                   11193:             if (exists($courses{$cdom.'_'.$cnum})) {
                   11194:                 $iscourse = 1;
                   11195:             }
                   11196:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   11197:         }
                   11198:     }
                   11199:     return unless($iscourse);
1.1167    droeschl 11200:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 11201: }
                   11202: 
1.1015    raeburn  11203: sub store_userdata {
                   11204:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  11205:     my $result;
1.1016    raeburn  11206:     if ($datakey ne '') {
1.1013    raeburn  11207:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  11208:             if ($udom eq '' || $uname eq '') {
                   11209:                 $udom = $env{'user.domain'};
                   11210:                 $uname = $env{'user.name'};
                   11211:             }
                   11212:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  11213:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   11214:                 $result = 'error: no_host';
                   11215:             } else {
1.1172.2.138  raeburn  11216:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  11217:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   11218: 
                   11219:                 my $namevalue='';
                   11220:                 foreach my $key (keys(%{$storehash})) {
                   11221:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   11222:                 }
                   11223:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  11224:                 unless ($namespace eq 'courserequests') {
                   11225:                     $datakey = &escape($datakey);
                   11226:                 }
1.1105    raeburn  11227:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   11228:                                   $namevalue,$uhome);
1.1013    raeburn  11229:             }
                   11230:         } else {
                   11231:             $result = 'error: data to store was not a hash reference'; 
                   11232:         }
                   11233:     } else {
                   11234:         $result= 'error: invalid requestkey'; 
                   11235:     }
                   11236:     return $result;
                   11237: }
                   11238: 
1.21      www      11239: # ---------------------------------------------------------- Assign Custom Role
                   11240: 
                   11241: sub assigncustomrole {
1.957     raeburn  11242:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11243:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  11244:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      11245: }
                   11246: 
                   11247: # ----------------------------------------------------------------- Revoke Role
                   11248: 
                   11249: sub revokerole {
1.957     raeburn  11250:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11251:     my $now=time;
1.965     raeburn  11252:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      11253: }
                   11254: 
                   11255: # ---------------------------------------------------------- Revoke Custom Role
                   11256: 
                   11257: sub revokecustomrole {
1.957     raeburn  11258:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11259:     my $now=time;
1.357     www      11260:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  11261:            $deleteflag,$selfenroll,$context);
1.17      www      11262: }
                   11263: 
1.533     banghart 11264: # ------------------------------------------------------------ Disk usage
1.535     albertel 11265: sub diskusage {
1.955     raeburn  11266:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   11267:     $directorypath =~ s/\/$//;
                   11268:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   11269:                        .&escape($getpropath).':'.&escape($uname).':'
                   11270:                        .&escape($udom),homeserver($uname,$udom));
                   11271:     if ($listing eq 'unknown_cmd') {
                   11272:         if ($getpropath) {
                   11273:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   11274:         }
                   11275:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   11276:     }
1.514     albertel 11277:     return $listing;
1.512     banghart 11278: }
                   11279: 
1.566     banghart 11280: sub is_locked {
1.1096    raeburn  11281:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 11282:     my @check;
                   11283:     my $is_locked;
1.1093    raeburn  11284:     push (@check,$file_name);
1.613     albertel 11285:     my %locked = &get('file_permissions',\@check,
1.620     albertel 11286: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 11287:     my ($tmp)=keys(%locked);
                   11288:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  11289:     
1.566     banghart 11290:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  11291:         $is_locked = 'false';
                   11292:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  11293:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  11294:                $is_locked = 'true';
1.1096    raeburn  11295:                if (ref($which) eq 'ARRAY') {
                   11296:                    push(@{$which},$entry);
                   11297:                } else {
                   11298:                    last;
                   11299:                }
1.745     raeburn  11300:            }
                   11301:        }
1.566     banghart 11302:     } else {
                   11303:         $is_locked = 'false';
                   11304:     }
1.1093    raeburn  11305:     return $is_locked;
1.566     banghart 11306: }
                   11307: 
1.759     albertel 11308: sub declutter_portfile {
                   11309:     my ($file) = @_;
1.833     albertel 11310:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 11311:     return $file;
                   11312: }
                   11313: 
1.559     banghart 11314: # ------------------------------------------------------------- Mark as Read Only
                   11315: 
                   11316: sub mark_as_readonly {
                   11317:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 11318:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11319:     my ($tmp)=keys(%current_permissions);
                   11320:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 11321:     foreach my $file (@{$files}) {
1.759     albertel 11322: 	$file = &declutter_portfile($file);
1.561     banghart 11323:         push(@{$current_permissions{$file}},$what);
1.559     banghart 11324:     }
1.613     albertel 11325:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11326:     return;
                   11327: }
                   11328: 
1.572     banghart 11329: # ------------------------------------------------------------Save Selected Files
                   11330: 
                   11331: sub save_selected_files {
                   11332:     my ($user, $path, @files) = @_;
                   11333:     my $filename = $user."savedfiles";
1.573     banghart 11334:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  11335:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 11336:     foreach my $file (@files) {
1.620     albertel 11337:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 11338:     }
                   11339:     foreach my $file (@other_files) {
1.574     banghart 11340:         print (OUT $file."\n");
1.572     banghart 11341:     }
1.574     banghart 11342:     close (OUT);
1.572     banghart 11343:     return 'ok';
                   11344: }
                   11345: 
1.574     banghart 11346: sub clear_selected_files {
                   11347:     my ($user) = @_;
                   11348:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  11349:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 11350:     print (OUT undef);
                   11351:     close (OUT);
                   11352:     return ("ok");    
                   11353: }
                   11354: 
1.572     banghart 11355: sub files_in_path {
                   11356:     my ($user, $path) = @_;
                   11357:     my $filename = $user."savedfiles";
                   11358:     my %return_files;
1.1172.2.96  raeburn  11359:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 11360:     while (my $line_in = <IN>) {
1.574     banghart 11361:         chomp ($line_in);
                   11362:         my @paths_and_file = split (m!/!, $line_in);
                   11363:         my $file_part = pop (@paths_and_file);
                   11364:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 11365:         $path_part.='/';
                   11366:         my $path_and_file = $path_part.$file_part;
                   11367:         if ($path_part eq $path) {
                   11368:             $return_files{$file_part}= 'selected';
                   11369:         }
                   11370:     }
1.574     banghart 11371:     close (IN);
                   11372:     return (\%return_files);
1.572     banghart 11373: }
                   11374: 
                   11375: # called in portfolio select mode, to show files selected NOT in current directory
                   11376: sub files_not_in_path {
                   11377:     my ($user, $path) = @_;
                   11378:     my $filename = $user."savedfiles";
                   11379:     my @return_files;
                   11380:     my $path_part;
1.1172.2.96  raeburn  11381:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 11382:     while (my $line = <IN>) {
1.572     banghart 11383:         #ok, I know it's clunky, but I want it to work
1.800     albertel 11384:         my @paths_and_file = split(m|/|, $line);
                   11385:         my $file_part = pop(@paths_and_file);
                   11386:         chomp($file_part);
                   11387:         my $path_part = join('/', @paths_and_file);
1.572     banghart 11388:         $path_part .= '/';
                   11389:         my $path_and_file = $path_part.$file_part;
                   11390:         if ($path_part ne $path) {
1.800     albertel 11391:             push(@return_files, ($path_and_file));
1.572     banghart 11392:         }
                   11393:     }
1.800     albertel 11394:     close(OUT);
1.574     banghart 11395:     return (@return_files);
1.572     banghart 11396: }
                   11397: 
1.745     raeburn  11398: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11399: 
1.745     raeburn  11400: sub get_portfile_permissions {
                   11401:     my ($domain,$user) = @_;
1.613     albertel 11402:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11403:     my ($tmp)=keys(%current_permissions);
                   11404:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11405:     return \%current_permissions;
                   11406: }
                   11407: 
                   11408: #---------------------------------------------Get portfolio file access controls
                   11409: 
1.749     raeburn  11410: sub get_access_controls {
1.745     raeburn  11411:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11412:     my %access;
                   11413:     my $real_file = $file;
                   11414:     $file =~ s/\.meta$//;
1.745     raeburn  11415:     if (defined($file)) {
1.749     raeburn  11416:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11417:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11418:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11419:             }
                   11420:         }
1.745     raeburn  11421:     } else {
1.749     raeburn  11422:         foreach my $key (keys(%{$current_permissions})) {
                   11423:             if ($key =~ /\0accesscontrol$/) {
                   11424:                 if (defined($group)) {
                   11425:                     if ($key !~ m-^\Q$group\E/-) {
                   11426:                         next;
                   11427:                     }
                   11428:                 }
                   11429:                 my ($fullpath) = split(/\0/,$key);
                   11430:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11431:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11432:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11433:                     }
                   11434:                 }
                   11435:             }
                   11436:         }
                   11437:     }
                   11438:     return %access;
                   11439: }
                   11440: 
                   11441: sub modify_access_controls {
                   11442:     my ($file_name,$changes,$domain,$user)=@_;
                   11443:     my ($outcome,$deloutcome);
                   11444:     my %store_permissions;
                   11445:     my %new_values;
                   11446:     my %new_control;
                   11447:     my %translation;
                   11448:     my @deletions = ();
                   11449:     my $now = time;
                   11450:     if (exists($$changes{'activate'})) {
                   11451:         if (ref($$changes{'activate'}) eq 'HASH') {
                   11452:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   11453:             my $numnew = scalar(@newitems);
                   11454:             for (my $i=0; $i<$numnew; $i++) {
                   11455:                 my $newkey = $newitems[$i];
                   11456:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  11457:                 if ($newkey =~ /^\d+:/) { 
                   11458:                     $newkey =~ s/^(\d+)/$newid/;
                   11459:                     $translation{$1} = $newid;
                   11460:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   11461:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   11462:                     $translation{$1} = $newid;
                   11463:                 }
1.749     raeburn  11464:                 $new_values{$file_name."\0".$newkey} = 
                   11465:                                           $$changes{'activate'}{$newitems[$i]};
                   11466:                 $new_control{$newkey} = $now;
                   11467:             }
                   11468:         }
                   11469:     }
                   11470:     my %todelete;
                   11471:     my %changed_items;
                   11472:     foreach my $action ('delete','update') {
                   11473:         if (exists($$changes{$action})) {
                   11474:             if (ref($$changes{$action}) eq 'HASH') {
                   11475:                 foreach my $key (keys(%{$$changes{$action}})) {
                   11476:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   11477:                     if ($action eq 'delete') { 
                   11478:                         $todelete{$itemnum} = 1;
                   11479:                     } else {
                   11480:                         $changed_items{$itemnum} = $key;
                   11481:                     }
                   11482:                 }
1.745     raeburn  11483:             }
                   11484:         }
1.749     raeburn  11485:     }
                   11486:     # get lock on access controls for file.
                   11487:     my $lockhash = {
                   11488:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   11489:                                                        ':'.$env{'user.domain'},
                   11490:                    }; 
                   11491:     my $tries = 0;
                   11492:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11493:    
1.1172.2.79  raeburn  11494:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  11495:         $tries ++;
1.1172.2.79  raeburn  11496:         sleep(0.1);
1.749     raeburn  11497:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11498:     }
                   11499:     if ($gotlock eq 'ok') {
                   11500:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   11501:         my ($tmp)=keys(%curr_permissions);
                   11502:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   11503:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   11504:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   11505:             if (ref($curr_controls) eq 'HASH') {
                   11506:                 foreach my $control_item (keys(%{$curr_controls})) {
                   11507:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   11508:                     if (defined($todelete{$itemnum})) {
                   11509:                         push(@deletions,$file_name."\0".$control_item);
                   11510:                     } else {
                   11511:                         if (defined($changed_items{$itemnum})) {
                   11512:                             $new_control{$changed_items{$itemnum}} = $now;
                   11513:                             push(@deletions,$file_name."\0".$control_item);
                   11514:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   11515:                         } else {
                   11516:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   11517:                         }
                   11518:                     }
1.745     raeburn  11519:                 }
                   11520:             }
                   11521:         }
1.970     raeburn  11522:         my ($group);
                   11523:         if (&is_course($domain,$user)) {
                   11524:             ($group,my $file) = split(/\//,$file_name,2);
                   11525:         }
1.749     raeburn  11526:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   11527:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   11528:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   11529:         #  remove lock
                   11530:         my @del_lock = ($file_name."\0".'locked_access_records');
                   11531:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  11532:         my $sqlresult =
1.970     raeburn  11533:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  11534:                                     $group);
1.749     raeburn  11535:     } else {
                   11536:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  11537:     }
1.749     raeburn  11538:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  11539: }
                   11540: 
1.827     raeburn  11541: sub make_public_indefinitely {
                   11542:     my ($requrl) = @_;
                   11543:     my $now = time;
                   11544:     my $action = 'activate';
                   11545:     my $aclnum = 0;
                   11546:     if (&is_portfolio_url($requrl)) {
                   11547:         my (undef,$udom,$unum,$file_name,$group) =
                   11548:             &parse_portfolio_url($requrl);
                   11549:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   11550:         my %access_controls = &get_access_controls($current_perms,
                   11551:                                                    $group,$file_name);
                   11552:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11553:             my ($num,$scope,$end,$start) = 
                   11554:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   11555:             if ($scope eq 'public') {
                   11556:                 if ($start <= $now && $end == 0) {
                   11557:                     $action = 'none';
                   11558:                 } else {
                   11559:                     $action = 'update';
                   11560:                     $aclnum = $num;
                   11561:                 }
                   11562:                 last;
                   11563:             }
                   11564:         }
                   11565:         if ($action eq 'none') {
                   11566:              return 'ok';
                   11567:         } else {
                   11568:             my %changes;
                   11569:             my $newend = 0;
                   11570:             my $newstart = $now;
                   11571:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   11572:             $changes{$action}{$newkey} = {
                   11573:                 type => 'public',
                   11574:                 time => {
                   11575:                     start => $newstart,
                   11576:                     end   => $newend,
                   11577:                 },
                   11578:             };
                   11579:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11580:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   11581:             return $outcome;
                   11582:         }
                   11583:     } else {
                   11584:         return 'invalid';
                   11585:     }
                   11586: }
                   11587: 
1.745     raeburn  11588: #------------------------------------------------------Get Marked as Read Only
                   11589: 
                   11590: sub get_marked_as_readonly {
                   11591:     my ($domain,$user,$what,$group) = @_;
                   11592:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11593:     my @readonly_files;
1.629     banghart 11594:     my $cmp1=$what;
                   11595:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11596:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11597:         if (defined($group)) {
                   11598:             if ($file_name !~ m-^\Q$group\E/-) {
                   11599:                 next;
                   11600:             }
                   11601:         }
1.561     banghart 11602:         if (ref($value) eq "ARRAY"){
                   11603:             foreach my $stored_what (@{$value}) {
1.629     banghart 11604:                 my $cmp2=$stored_what;
1.759     albertel 11605:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11606:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11607:                 }
1.629     banghart 11608:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11609:                     push(@readonly_files, $file_name);
1.745     raeburn  11610:                     last;
1.563     banghart 11611:                 } elsif (!defined($what)) {
                   11612:                     push(@readonly_files, $file_name);
1.745     raeburn  11613:                     last;
1.561     banghart 11614:                 }
                   11615:             }
1.745     raeburn  11616:         }
1.561     banghart 11617:     }
                   11618:     return @readonly_files;
                   11619: }
1.577     banghart 11620: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11621: 
1.577     banghart 11622: sub get_marked_as_readonly_hash {
1.745     raeburn  11623:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11624:     my %readonly_files;
1.745     raeburn  11625:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11626:         if (defined($group)) {
                   11627:             if ($file_name !~ m-^\Q$group\E/-) {
                   11628:                 next;
                   11629:             }
                   11630:         }
1.577     banghart 11631:         if (ref($value) eq "ARRAY"){
                   11632:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11633:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11634:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11635:                         if ($lock_descriptor eq 'graded') {
                   11636:                             $readonly_files{$file_name} = 'graded';
                   11637:                         } elsif ($lock_descriptor eq 'handback') {
                   11638:                             $readonly_files{$file_name} = 'handback';
                   11639:                         } else {
                   11640:                             if (!exists($readonly_files{$file_name})) {
                   11641:                                 $readonly_files{$file_name} = 'locked';
                   11642:                             }
                   11643:                         }
1.745     raeburn  11644:                     }
1.750     banghart 11645:                 } 
1.577     banghart 11646:             }
                   11647:         } 
                   11648:     }
                   11649:     return %readonly_files;
                   11650: }
1.559     banghart 11651: # ------------------------------------------------------------ Unmark as Read Only
                   11652: 
                   11653: sub unmark_as_readonly {
1.629     banghart 11654:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11655:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11656:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11657:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11658:     my $symb_crs = $what;
                   11659:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11660:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11661:     my ($tmp)=keys(%current_permissions);
                   11662:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11663:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11664:     foreach my $file (@readonly_files) {
1.759     albertel 11665: 	my $clean_file = &declutter_portfile($file);
                   11666: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11667: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11668:         my @new_locks;
                   11669:         my @del_keys;
                   11670:         if (ref($current_locks) eq "ARRAY"){
                   11671:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11672:                 my $compare=$locker;
1.749     raeburn  11673:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11674:                     $compare=join('',@{$locker});
1.746     raeburn  11675:                     if ($compare ne $symb_crs) {
                   11676:                         push(@new_locks, $locker);
                   11677:                     }
1.563     banghart 11678:                 }
                   11679:             }
1.650     albertel 11680:             if (scalar(@new_locks) > 0) {
1.563     banghart 11681:                 $current_permissions{$file} = \@new_locks;
                   11682:             } else {
                   11683:                 push(@del_keys, $file);
1.613     albertel 11684:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11685:                 delete($current_permissions{$file});
1.563     banghart 11686:             }
                   11687:         }
1.561     banghart 11688:     }
1.613     albertel 11689:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11690:     return;
                   11691: }
1.512     banghart 11692: 
1.17      www      11693: # ------------------------------------------------------------ Directory lister
                   11694: 
                   11695: sub dirlist {
1.955     raeburn  11696:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11697:     $uri=~s/^\///;
                   11698:     $uri=~s/\/$//;
1.253     stredwic 11699:     my ($udom, $uname);
1.955     raeburn  11700:     if ($getuserdir) {
1.253     stredwic 11701:         $udom = $userdomain;
                   11702:         $uname = $username;
1.955     raeburn  11703:     } else {
                   11704:         (undef,$udom,$uname)=split(/\//,$uri);
                   11705:         if(defined($userdomain)) {
                   11706:             $udom = $userdomain;
                   11707:         }
                   11708:         if(defined($username)) {
                   11709:             $uname = $username;
                   11710:         }
1.253     stredwic 11711:     }
1.955     raeburn  11712:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11713: 
1.955     raeburn  11714:     $dirRoot = $perlvar{'lonDocRoot'};
                   11715:     if (defined($getpropath)) {
                   11716:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11717:         $dirRoot =~ s/\/$//;
1.955     raeburn  11718:     } elsif (defined($getuserdir)) {
                   11719:         my $subdir=$uname.'__';
                   11720:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11721:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11722:                    ."/$udom/$subdir/$uname";
                   11723:     } elsif (defined($alternateRoot)) {
                   11724:         $dirRoot = $alternateRoot;
1.751     banghart 11725:     }
1.253     stredwic 11726: 
                   11727:     if($udom) {
                   11728:         if($uname) {
1.1135    raeburn  11729:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11730:             if ($uhome eq 'no_host') {
                   11731:                 return ([],'no_host');
                   11732:             }
1.955     raeburn  11733:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11734:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11735:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11736:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11737:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11738:             } else {
                   11739:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11740:             }
1.605     matthew  11741:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11742:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11743:                 @listing_results = split(/:/,$listing);
                   11744:             } else {
                   11745:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11746:             }
1.1135    raeburn  11747:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11748:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11749:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11750:                 return ([],$listing);
                   11751:             } else {
                   11752:                 return (\@listing_results);
1.1135    raeburn  11753:             }
1.955     raeburn  11754:         } elsif(!$alternateRoot) {
1.1136    raeburn  11755:             my (%allusers,%listerror);
1.841     albertel 11756: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11757:  	    foreach my $tryserver (keys(%servers)) {
                   11758:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11759:                                   &escape($udom),$tryserver);
                   11760:                 if ($listing eq 'unknown_cmd') {
                   11761: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11762: 				      $udom, $tryserver);
                   11763:                 } else {
                   11764:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11765:                 }
1.841     albertel 11766: 		if ($listing eq 'unknown_cmd') {
                   11767: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11768: 				      $udom, $tryserver);
                   11769: 		    @listing_results = split(/:/,$listing);
                   11770: 		} else {
                   11771: 		    @listing_results =
                   11772: 			map { &unescape($_); } split(/:/,$listing);
                   11773: 		}
1.1136    raeburn  11774:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11775:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11776:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11777:                     $listerror{$tryserver} = $listing;
                   11778:                 } else {
1.841     albertel 11779: 		    foreach my $line (@listing_results) {
                   11780: 			my ($entry) = split(/&/,$line,2);
                   11781: 			$allusers{$entry} = 1;
                   11782: 		    }
                   11783: 		}
1.253     stredwic 11784:             }
1.1136    raeburn  11785:             my @alluserslist=();
1.800     albertel 11786:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11787:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11788:             }
1.1172.2.80  raeburn  11789:             if (!%listerror) {
                   11790:                 # no errors
                   11791:                 return (\@alluserslist);
                   11792:             } elsif (scalar(keys(%servers)) == 1) {
                   11793:                 # one library server, one error
                   11794:                 my ($key) = keys(%listerror);
                   11795:                 return (\@alluserslist, $listerror{$key});
                   11796:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11797:                 # con_lost indicates that we might miss data from at least one
                   11798:                 # library server
                   11799:                 return (\@alluserslist, 'con_lost');
                   11800:             } else {
                   11801:                 # multiple library servers and no con_lost -> data should be
                   11802:                 # complete.
                   11803:                 return (\@alluserslist);
                   11804:             }
                   11805: 
1.253     stredwic 11806:         } else {
1.1136    raeburn  11807:             return ([],'missing username');
1.253     stredwic 11808:         }
1.955     raeburn  11809:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11810:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11811:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11812:         return (\@all_domains);
1.955     raeburn  11813:     } else {
1.1136    raeburn  11814:         return ([],'missing domain');
1.275     stredwic 11815:     }
                   11816: }
                   11817: 
                   11818: # --------------------------------------------- GetFileTimestamp
                   11819: # This function utilizes dirlist and returns the date stamp for
                   11820: # when it was last modified.  It will also return an error of -1
                   11821: # if an error occurs
                   11822: 
                   11823: sub GetFileTimestamp {
1.955     raeburn  11824:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11825:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11826:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11827:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11828:                                     undef,$getuserdir);
                   11829:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11830:         return -1;
                   11831:     }
                   11832:     if (ref($fileref) eq 'ARRAY') {
                   11833:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11834:         # @stats contains first the filename, then the stat output
                   11835:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11836:     } else {
                   11837:         return -1;
1.253     stredwic 11838:     }
1.26      www      11839: }
                   11840: 
1.712     albertel 11841: sub stat_file {
                   11842:     my ($uri) = @_;
1.787     albertel 11843:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11844: 
1.955     raeburn  11845:     my ($udom,$uname,$file);
1.712     albertel 11846:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11847: 	($udom,$uname,$file) =
1.811     albertel 11848: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11849: 	$file = 'userfiles/'.$file;
                   11850:     }
                   11851:     if ($uri =~ m-^/res/-) {
                   11852: 	($udom,$uname) = 
1.807     albertel 11853: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11854: 	$file = $uri;
                   11855:     }
                   11856: 
                   11857:     if (!$udom || !$uname || !$file) {
                   11858: 	# unable to handle the uri
                   11859: 	return ();
                   11860:     }
1.956     raeburn  11861:     my $getpropath;
                   11862:     if ($file =~ /^userfiles\//) {
                   11863:         $getpropath = 1;
                   11864:     }
1.1136    raeburn  11865:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11866:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11867:         return ();
                   11868:     } else {
                   11869:         if (ref($listref) eq 'ARRAY') {
                   11870:             my @stats = split('&',$listref->[0]);
                   11871: 	    shift(@stats); #filename is first
                   11872: 	    return @stats;
                   11873:         }
1.712     albertel 11874:     }
                   11875:     return ();
                   11876: }
                   11877: 
1.26      www      11878: # -------------------------------------------------------- Value of a Condition
                   11879: 
1.713     albertel 11880: # gets the value of a specific preevaluated condition
                   11881: #    stored in the string  $env{user.state.<cid>}
                   11882: # or looks up a condition reference in the bighash and if if hasn't
                   11883: # already been evaluated recurses into docondval to get the value of
                   11884: # the condition, then memoizing it to 
                   11885: #   $env{user.state.<cid>.<condition>}
1.40      www      11886: sub directcondval {
                   11887:     my $number=shift;
1.620     albertel 11888:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11889: 	&Apache::lonuserstate::evalstate();
                   11890:     }
1.713     albertel 11891:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11892: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11893:     } elsif ($number =~ /^_/) {
                   11894: 	my $sub_condition;
                   11895: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11896: 		&GDBM_READER(),0640)) {
                   11897: 	    $sub_condition=$bighash{'conditions'.$number};
                   11898: 	    untie(%bighash);
                   11899: 	}
                   11900: 	my $value = &docondval($sub_condition);
1.949     raeburn  11901: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11902: 	return $value;
                   11903:     }
1.620     albertel 11904:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11905:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11906:     } else {
                   11907:        return 2;
                   11908:     }
                   11909: }
                   11910: 
1.713     albertel 11911: # get the collection of conditions for this resource
1.26      www      11912: sub condval {
                   11913:     my $condidx=shift;
1.54      www      11914:     my $allpathcond='';
1.713     albertel 11915:     foreach my $cond (split(/\|/,$condidx)) {
                   11916: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11917: 	    $allpathcond.=
                   11918: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11919: 	}
1.191     harris41 11920:     }
1.54      www      11921:     $allpathcond=~s/\|$//;
1.713     albertel 11922:     return &docondval($allpathcond);
                   11923: }
                   11924: 
                   11925: #evaluates an expression of conditions
                   11926: sub docondval {
                   11927:     my ($allpathcond) = @_;
                   11928:     my $result=0;
                   11929:     if ($env{'request.course.id'}
                   11930: 	&& defined($allpathcond)) {
                   11931: 	my $operand='|';
                   11932: 	my @stack;
                   11933: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11934: 	    if ($chunk eq '(') {
                   11935: 		push @stack,($operand,$result);
                   11936: 	    } elsif ($chunk eq ')') {
                   11937: 		my $before=pop @stack;
                   11938: 		if (pop @stack eq '&') {
                   11939: 		    $result=$result>$before?$before:$result;
                   11940: 		} else {
                   11941: 		    $result=$result>$before?$result:$before;
                   11942: 		}
                   11943: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11944: 		$operand=$chunk;
                   11945: 	    } else {
                   11946: 		my $new=directcondval($chunk);
                   11947: 		if ($operand eq '&') {
                   11948: 		    $result=$result>$new?$new:$result;
                   11949: 		} else {
                   11950: 		    $result=$result>$new?$result:$new;
                   11951: 		}
                   11952: 	    }
                   11953: 	}
1.26      www      11954:     }
                   11955:     return $result;
1.421     albertel 11956: }
                   11957: 
                   11958: # ---------------------------------------------------- Devalidate courseresdata
                   11959: 
                   11960: sub devalidatecourseresdata {
                   11961:     my ($coursenum,$coursedomain)=@_;
                   11962:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11963:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11964: }
                   11965: 
1.763     www      11966: 
1.200     www      11967: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11968: #
                   11969: #  Parameters:
                   11970: #      $coursenum    - Number of the course.
                   11971: #      $coursedomain - Domain at which the course was created.
                   11972: #  Returns:
                   11973: #     A hash of the course parameters along (I think) with timestamps
                   11974: #     and version info.
1.877     foxr     11975: 
1.624     albertel 11976: sub get_courseresdata {
                   11977:     my ($coursenum,$coursedomain)=@_;
1.200     www      11978:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11979:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11980:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11981:     my %dumpreply;
1.417     albertel 11982:     unless (defined($cached)) {
1.624     albertel 11983: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11984: 	$result=\%dumpreply;
1.251     albertel 11985: 	my ($tmp) = keys(%dumpreply);
                   11986: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11987: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11988: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11989: 	    return $tmp;
1.416     albertel 11990: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11991: 	    $result=undef;
1.599     albertel 11992: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11993: 	}
                   11994:     }
1.624     albertel 11995:     return $result;
                   11996: }
                   11997: 
1.633     albertel 11998: sub devalidateuserresdata {
                   11999:     my ($uname,$udom)=@_;
                   12000:     my $hashid="$udom:$uname";
                   12001:     &devalidate_cache_new('userres',$hashid);
                   12002: }
                   12003: 
1.624     albertel 12004: sub get_userresdata {
                   12005:     my ($uname,$udom)=@_;
                   12006:     #most student don\'t have any data set, check if there is some data
                   12007:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   12008: 
                   12009:     my $hashid="$udom:$uname";
                   12010:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   12011:     if (!defined($cached)) {
                   12012: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   12013: 	$result=\%resourcedata;
                   12014: 	&do_cache_new('userres',$hashid,$result,600);
                   12015:     }
                   12016:     my ($tmp)=keys(%$result);
                   12017:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   12018: 	return $result;
                   12019:     }
                   12020:     #error 2 occurs when the .db doesn't exist
                   12021:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  12022:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   12023: 	    &logthis("<font color=\"blue\">WARNING:".
                   12024: 		     " Trying to get resource data for ".
                   12025: 		     $uname." at ".$udom.": ".
                   12026: 		     $tmp."</font>");
                   12027:         }
1.624     albertel 12028:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 12029: 	#&EXT_cache_set($udom,$uname);
                   12030: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 12031: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 12032:     }
                   12033:     return $tmp;
                   12034: }
1.879     foxr     12035: #----------------------------------------------- resdata - return resource data
                   12036: #  Purpose:
                   12037: #    Return resource data for either users or for a course.
                   12038: #  Parameters:
                   12039: #     $name      - Course/user name.
                   12040: #     $domain    - Name of the domain the user/course is registered on.
                   12041: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   12042: #     @which     - Array of names of resources desired.
                   12043: #  Returns:
                   12044: #     The value of the first reasource in @which that is found in the
                   12045: #     resource hash.
                   12046: #  Exceptional Conditions:
                   12047: #     If the $type passed in is not valid (not the string 'course' or 
                   12048: #     'user', an undefined  reference is returned.
                   12049: #     If none of the resources are found, an undef is returned
1.624     albertel 12050: sub resdata {
                   12051:     my ($name,$domain,$type,@which)=@_;
                   12052:     my $result;
                   12053:     if ($type eq 'course') {
                   12054: 	$result=&get_courseresdata($name,$domain);
                   12055:     } elsif ($type eq 'user') {
                   12056: 	$result=&get_userresdata($name,$domain);
                   12057:     }
                   12058:     if (!ref($result)) { return $result; }    
1.251     albertel 12059:     foreach my $item (@which) {
1.927     albertel 12060: 	if (defined($result->{$item->[0]})) {
                   12061: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 12062: 	}
1.250     albertel 12063:     }
1.291     albertel 12064:     return undef;
1.200     www      12065: }
                   12066: 
1.1172.2.146.  .1(raebu 12067:22): sub get_domain_lti {
                   12068:22):     my ($cdom,$context) = @_;
          .4(raebu 12069:22):     my ($name,$cachename,%lti);
          .1(raebu 12070:22):     if ($context eq 'consumer') {
                   12071:22):         $name = 'ltitools';
                   12072:22):     } elsif ($context eq 'provider') {
                   12073:22):         $name = 'lti';
          .4(raebu 12074:22):     } elsif ($context eq 'linkprot') {
                   12075:22):         $name = 'ltisec';
          .1(raebu 12076:22):     } else {
                   12077:22):         return %lti;
                   12078:22):     }
          .4(raebu 12079:22):     if ($context eq 'linkprot') {
                   12080:22):         $cachename = $context;
                   12081:22):     } else {
                   12082:22):         $cachename = $name;
                   12083:22):     }
                   12084:22):     my ($result,$cached)=&is_cached_new($cachename,$cdom);
          .1(raebu 12085:22):     if (defined($cached)) {
                   12086:22):         if (ref($result) eq 'HASH') {
                   12087:22):             %lti = %{$result};
                   12088:22):         }
                   12089:22):     } else {
                   12090:22):         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   12091:22):         if (ref($domconfig{$name}) eq 'HASH') {
          .4(raebu 12092:22):             if ($context eq 'linkprot') {
                   12093:22):                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
                   12094:22):                     %lti = %{$domconfig{$name}{'linkprot'}};
                   12095:22):                 }
                   12096:22):             } else {
                   12097:22):                 %lti = %{$domconfig{$name}};
                   12098:22):             }
          .1(raebu 12099:22):         }
                   12100:22):         my $cachetime = 24*60*60;
          .4(raebu 12101:22):         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
          .1(raebu 12102:22):     }
                   12103:22):     return %lti;
                   12104:22): }
                   12105:22): 
                   12106:22): sub get_course_lti {
          .13(raeb 12107:-23):     my ($cnum,$cdom,$context) = @_;
                   12108:-23):     my ($name,$cachename,%lti);
                   12109:-23):     if ($context eq 'consumer') {
                   12110:-23):         $name = 'ltitools';
                   12111:-23):         $cachename = 'courseltitools';
                   12112:-23):     } elsif ($context eq 'provider') {
                   12113:-23):         $name = 'lti';
                   12114:-23):         $cachename = 'courselti';
                   12115:-23):     } else {
                   12116:-23):         return %lti;
                   12117:-23):     }
          .1(raebu 12118:22):     my $hashid=$cdom.'_'.$cnum;
          .13(raeb 12119:-23):     my ($result,$cached)=&is_cached_new($cachename,$hashid);
          .1(raebu 12120:22):     if (defined($cached)) {
                   12121:22):         if (ref($result) eq 'HASH') {
          .13(raeb 12122:-23):             %lti = %{$result};
          .1(raebu 12123:22):         }
                   12124:22):     } else {
          .13(raeb 12125:-23):         %lti = &dump($name,$cdom,$cnum,undef,undef,undef,1);
          .1(raebu 12126:22):         my $cachetime = 24*60*60;
          .13(raeb 12127:-23):         &do_cache_new($cachename,$hashid,\%lti,$cachetime);
          .1(raebu 12128:22):     }
          .13(raeb 12129:-23):     return %lti;
          .1(raebu 12130:22): }
                   12131:22): 
          .3(raebu 12132:22): sub courselti_itemid {
                   12133:22):     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
                   12134:22):     my ($chome,$itemid);
                   12135:22):     $chome = &homeserver($cnum,$cdom);
                   12136:22):     return if ($chome eq 'no_host');
                   12137:22):     if (ref($params) eq 'HASH') {
                   12138:22):         my $rep;
                   12139:22):         if (grep { $_ eq $chome } current_machine_ids()) {
                   12140:22):             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
                   12141:22):         } else {
                   12142:22):             my $escurl = &escape($url);
                   12143:22):             my $escmethod = &escape($method);
                   12144:22):             my $items = &freeze_escape($params);
                   12145:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
                   12146:22):         }
                   12147:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   12148:22):                 ($rep eq 'unknown_cmd')) {
                   12149:22):             $itemid = $rep;
                   12150:22):         }
                   12151:22):     }
                   12152:22):     return $itemid;
                   12153:22): }
                   12154:22): 
                   12155:22): sub domainlti_itemid {
                   12156:22):     my ($cdom,$url,$method,$params,$context) = @_;
                   12157:22):     my ($primary_id,$itemid);
                   12158:22):     $primary_id = &domain($cdom,'primary');
                   12159:22):     return if ($primary_id eq '');
                   12160:22):     if (ref($params) eq 'HASH') {
                   12161:22):         my $rep;
                   12162:22):         if (grep { $_ eq $primary_id } current_machine_ids()) {
                   12163:22):             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
                   12164:22):         } else {
                   12165:22):             my $cnum = '';
                   12166:22):             my $escurl = &escape($url);
                   12167:22):             my $escmethod = &escape($method);
                   12168:22):             my $items = &freeze_escape($params);
                   12169:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
                   12170:22):         }
                   12171:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   12172:22):                 ($rep eq 'unknown_cmd')) {
                   12173:22):             $itemid = $rep;
                   12174:22):         }
                   12175:22):     }
                   12176:22):     return $itemid;
                   12177:22): }
                   12178:22): 
          .15(raeb 12179:-23): sub get_ltitools_id {
                   12180:-23):     my ($context,$cdom,$cnum,$title) = @_;
                   12181:-23):     my ($lockhash,$tries,$gotlock,$id,$error);
                   12182:-23): 
                   12183:-23):     # get lock on ltitools db
                   12184:-23):     $lockhash = {
                   12185:-23):                    lock => $env{'user.name'}.
                   12186:-23):                            ':'.$env{'user.domain'},
                   12187:-23):                 };
                   12188:-23):     $tries = 0;
                   12189:-23):     if ($context eq 'domain') {
                   12190:-23):         $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
                   12191:-23):     } else {
                   12192:-23):         $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
                   12193:-23):     }
                   12194:-23):     while (($gotlock ne 'ok') && ($tries<10)) {
                   12195:-23):         $tries ++;
                   12196:-23):         sleep (0.1);
                   12197:-23):         if ($context eq 'domain') {
                   12198:-23):             $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
                   12199:-23):         } else {
                   12200:-23):             $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
                   12201:-23):         }
                   12202:-23):     }
                   12203:-23):     if ($gotlock eq 'ok') {
                   12204:-23):         my %currids;
                   12205:-23):         if ($context eq 'domain') {
                   12206:-23):             %currids = &dump_dom('ltitools',$cdom);
                   12207:-23):         } else {
                   12208:-23):             %currids = &dump('ltitools',$cdom,$cnum);
                   12209:-23):         }
                   12210:-23):         if ($currids{'lock'}) {
                   12211:-23):             delete($currids{'lock'});
                   12212:-23):             if (keys(%currids)) {
                   12213:-23):                 my @curr = sort { $a <=> $b } keys(%currids);
                   12214:-23):                 if ($curr[-1] =~ /^\d+$/) {
                   12215:-23):                     $id = 1 + $curr[-1];
                   12216:-23):                 }
                   12217:-23):             } else {
                   12218:-23):                 $id = 1;
                   12219:-23):             }
                   12220:-23):             if ($id) {
                   12221:-23):                 if ($context eq 'domain') {
                   12222:-23):                     unless (&newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
                   12223:-23):                         $error = 'nostore';
                   12224:-23):                     }
                   12225:-23):                 } else {
                   12226:-23):                     unless (&newput('ltitools',{ $id => $title },$cdom,$cnum) eq 'ok') {
                   12227:-23):                         $error = 'nostore';
                   12228:-23):                     }
                   12229:-23):                 }
                   12230:-23):             } else {
                   12231:-23):                 $error = 'nonumber';
                   12232:-23):             }
                   12233:-23):         }
                   12234:-23):         my $dellockoutcome;
                   12235:-23):         if ($context eq 'domain') {
                   12236:-23):             $dellockoutcome = &del_dom('ltitools',['lock'],$cdom);
                   12237:-23):         } else {
                   12238:-23):             $dellockoutcome = &del('ltitools',['lock'],$cdom,$cnum);
                   12239:-23):         }
                   12240:-23):     } else {
                   12241:-23):         $error = 'nolock';
                   12242:-23):     }
                   12243:-23):     return ($id,$error);
                   12244:-23): }
                   12245:-23): 
          .9(raebu 12246:23): sub count_supptools {
                   12247:23):     my ($cnum,$cdom,$ignorecache,$reload)=@_;
1.1172.2.31  raeburn  12248:     my $hashid=$cnum.':'.$cdom;
1.1172.2.146.  .9(raebu 12249:23):     my ($numexttools,$cached);
1.1172.2.31  raeburn  12250:     unless ($ignorecache) {
1.1172.2.146.  .9(raebu 12251:23):         ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
1.1172.2.31  raeburn  12252:     }
                   12253:     unless (defined($cached)) {
                   12254:         my $chome=&homeserver($cnum,$cdom);
1.1172.2.146.  .9(raebu 12255:23):         $numexttools = 0;
1.1172.2.31  raeburn  12256:         unless ($chome eq 'no_host') {
1.1172.2.146.  .9(raebu 12257:23):             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
                   12258:23):             if (ref($supplemental) eq 'HASH') {
                   12259:23):                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   12260:23):                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
                   12261:23):                         if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   12262:23):                             $numexttools ++;
                   12263:23):                         }
                   12264:23):                     }
                   12265:23):                 }
                   12266:23):             }
1.1172.2.31  raeburn  12267:         }
1.1172.2.146.  .9(raebu 12268:23):         &do_cache_new('supptools',$hashid,$numexttools,600);
1.1172.2.31  raeburn  12269:     }
1.1172.2.146.  .9(raebu 12270:23):     return $numexttools;
                   12271:23): }
                   12272:23): 
                   12273:23): sub has_unhidden_suppfiles {
                   12274:23):     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   12275:23):     my $hashid=$cnum.':'.$cdom;
                   12276:23):     my ($showsupp,$cached);
                   12277:23):     unless ($ignorecache) {
                   12278:23):         ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
                   12279:23):     }
                   12280:23):     unless (defined($cached)) {
                   12281:23):         my $chome=&homeserver($cnum,$cdom);
                   12282:23):         unless ($chome eq 'no_host') {
                   12283:23):             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
                   12284:23):             if (ref($supplemental) eq 'HASH') {
                   12285:23):                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   12286:23):                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
                   12287:23):                         next if ($key =~ /\.sequence$/);
                   12288:23):                         if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
                   12289:23):                             foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
                   12290:23):                                 unless ($supplemental->{'hidden'}->{$id}) {
                   12291:23):                                     $showsupp = 1;
                   12292:23):                                     last;
                   12293:23):                                 }
                   12294:23):                             }
                   12295:23):                         }
                   12296:23):                         last if ($showsupp);
                   12297:23):                     }
                   12298:23):                 }
                   12299:23):             }
                   12300:23):         }
                   12301:23):         &do_cache_new('showsupp',$hashid,$showsupp,600);
                   12302:23):     }
                   12303:23):     return $showsupp;
1.1172.2.31  raeburn  12304: }
                   12305: 
1.379     matthew  12306: #
                   12307: # EXT resource caching routines
                   12308: #
                   12309: 
1.1172.2.146.  .1(raebu 12310:22): {
                   12311:22): # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   12312:22): #
                   12313:22): # The course for which we cache
                   12314:22): my $cachedmapkey='';
                   12315:22): # The cached recursive maps for this course
                   12316:22): my %cachedmaps=();
                   12317:22): # When this was last done
                   12318:22): my $cachedmaptime='';
                   12319:22): 
1.379     matthew  12320: sub clear_EXT_cache_status {
1.383     albertel 12321:     &delenv('cache.EXT.');
1.379     matthew  12322: }
                   12323: 
                   12324: sub EXT_cache_status {
                   12325:     my ($target_domain,$target_user) = @_;
1.383     albertel 12326:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 12327:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  12328:         # We know already the user has no data
                   12329:         return 1;
                   12330:     } else {
                   12331:         return 0;
                   12332:     }
                   12333: }
                   12334: 
                   12335: sub EXT_cache_set {
                   12336:     my ($target_domain,$target_user) = @_;
1.383     albertel 12337:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  12338:     #&appenv({$cachename => time});
1.379     matthew  12339: }
                   12340: 
1.28      www      12341: # --------------------------------------------------------- Value of a Variable
1.58      www      12342: sub EXT {
1.715     albertel 12343: 
1.1172.2.28  raeburn  12344:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      12345:     unless ($varname) { return ''; }
1.218     albertel 12346:     #get real user name/domain, courseid and symb
                   12347:     my $courseid;
1.359     albertel 12348:     my $publicuser;
1.427     www      12349:     if ($symbparm) {
                   12350: 	$symbparm=&get_symb_from_alias($symbparm);
                   12351:     }
1.218     albertel 12352:     if (!($uname && $udom)) {
1.790     albertel 12353:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 12354:       if (!$symbparm) {	$symbparm=$cursymb; }
                   12355:     } else {
1.620     albertel 12356: 	$courseid=$env{'request.course.id'};
1.218     albertel 12357:     }
1.48      www      12358:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   12359:     my $rest;
1.320     albertel 12360:     if (defined($therest[0])) {
1.48      www      12361:        $rest=join('.',@therest);
                   12362:     } else {
                   12363:        $rest='';
                   12364:     }
1.320     albertel 12365: 
1.57      www      12366:     my $qualifierrest=$qualifier;
                   12367:     if ($rest) { $qualifierrest.='.'.$rest; }
                   12368:     my $spacequalifierrest=$space;
                   12369:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      12370:     if ($realm eq 'user') {
1.48      www      12371: # --------------------------------------------------------------- user.resource
                   12372: 	if ($space eq 'resource') {
1.651     albertel 12373: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   12374: 		  || defined($Apache::lonhomework::parsing_a_task))
                   12375: 		 &&
1.1172.2.142  raeburn  12376: 		 ($symbparm eq &symbread()) ) {
1.744     albertel 12377: 		# if we are in the middle of processing the resource the
                   12378: 		# get the value we are planning on committing
                   12379:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   12380:                     return $Apache::lonhomework::results{$qualifierrest};
                   12381:                 } else {
                   12382:                     return $Apache::lonhomework::history{$qualifierrest};
                   12383:                 }
1.335     albertel 12384: 	    } else {
1.359     albertel 12385: 		my %restored;
1.620     albertel 12386: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 12387: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   12388: 		} else {
                   12389: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   12390: 		}
1.335     albertel 12391: 		return $restored{$qualifierrest};
                   12392: 	    }
1.48      www      12393: # ----------------------------------------------------------------- user.access
                   12394:         } elsif ($space eq 'access') {
1.218     albertel 12395: 	    # FIXME - not supporting calls for a specific user
1.48      www      12396:             return &allowed($qualifier,$rest);
                   12397: # ------------------------------------------ user.preferences, user.environment
                   12398:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 12399: 	    if (($uname eq $env{'user.name'}) &&
                   12400: 		($udom eq $env{'user.domain'})) {
                   12401: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 12402: 	    } else {
1.359     albertel 12403: 		my %returnhash;
                   12404: 		if (!$publicuser) {
                   12405: 		    %returnhash=&userenvironment($udom,$uname,
                   12406: 						 $qualifierrest);
                   12407: 		}
1.218     albertel 12408: 		return $returnhash{$qualifierrest};
                   12409: 	    }
1.48      www      12410: # ----------------------------------------------------------------- user.course
                   12411:         } elsif ($space eq 'course') {
1.218     albertel 12412: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12413:             return $env{join('.',('request.course',$qualifier))};
1.48      www      12414: # ------------------------------------------------------------------- user.role
                   12415:         } elsif ($space eq 'role') {
1.218     albertel 12416: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12417:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      12418:             if ($qualifier eq 'value') {
                   12419: 		return $role;
                   12420:             } elsif ($qualifier eq 'extent') {
                   12421:                 return $where;
                   12422:             }
                   12423: # ----------------------------------------------------------------- user.domain
                   12424:         } elsif ($space eq 'domain') {
1.218     albertel 12425:             return $udom;
1.48      www      12426: # ------------------------------------------------------------------- user.name
                   12427:         } elsif ($space eq 'name') {
1.218     albertel 12428:             return $uname;
1.48      www      12429: # ---------------------------------------------------- Any other user namespace
1.29      www      12430:         } else {
1.359     albertel 12431: 	    my %reply;
                   12432: 	    if (!$publicuser) {
                   12433: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   12434: 	    }
                   12435: 	    return $reply{$qualifierrest};
1.48      www      12436:         }
1.236     www      12437:     } elsif ($realm eq 'query') {
                   12438: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 12439:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   12440: 						[$spacequalifierrest]);
1.620     albertel 12441: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      12442:    } elsif ($realm eq 'request') {
1.48      www      12443: # ------------------------------------------------------------- request.browser
                   12444:         if ($space eq 'browser') {
1.1145    bisitz   12445:             return $env{'browser.'.$qualifier};
1.57      www      12446: # ------------------------------------------------------------ request.filename
                   12447:         } else {
1.620     albertel 12448:             return $env{'request.'.$spacequalifierrest};
1.29      www      12449:         }
1.28      www      12450:     } elsif ($realm eq 'course') {
1.48      www      12451: # ---------------------------------------------------------- course.description
1.620     albertel 12452:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      12453:     } elsif ($realm eq 'resource') {
1.165     www      12454: 
1.620     albertel 12455: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 12456: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   12457: 	}
1.693     albertel 12458: 
1.1172.2.30  raeburn  12459:         if ($qualifier eq '') {
                   12460: 	    if ($space eq 'title') {
                   12461: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   12462: 	        return &gettitle($symbparm);
                   12463: 	    }
1.693     albertel 12464: 	
1.1172.2.30  raeburn  12465: 	    if ($space eq 'map') {
                   12466: 	        my ($map) = &decode_symb($symbparm);
                   12467: 	        return &symbread($map);
                   12468: 	    }
                   12469:             if ($space eq 'maptitle') {
                   12470:                 my ($map) = &decode_symb($symbparm);
                   12471:                 return &gettitle($map);
                   12472:             }
                   12473: 	    if ($space eq 'filename') {
                   12474: 	        if ($symbparm) {
                   12475: 		    return &clutter((&decode_symb($symbparm))[2]);
                   12476: 	        }
                   12477: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 12478: 	    }
1.1172.2.30  raeburn  12479: 
                   12480:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   12481:                 if ($space eq 'visibleparts') {
                   12482:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   12483:                     my $item;
                   12484:                     if (ref($navmap)) {
                   12485:                         my $res = $navmap->getBySymb($symbparm);
                   12486:                         my $parts = $res->parts();
                   12487:                         if (ref($parts) eq 'ARRAY') {
                   12488:                             $item = join(',',@{$parts});
                   12489:                         }
                   12490:                         undef($navmap);
                   12491:                     }
                   12492:                     return $item;
                   12493:                 }
                   12494:             }
                   12495:         }
1.693     albertel 12496: 
                   12497: 	my ($section, $group, @groups);
1.593     albertel 12498: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  12499:         if (($courseid eq '') && ($cid)) {
                   12500:             $courseid = $cid;
                   12501:         }
                   12502: 	if (($symbparm && $courseid) && 
                   12503: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      12504: 
1.218     albertel 12505: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      12506: 
1.60      www      12507: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 12508: 	    my $symbp=$symbparm;
1.735     albertel 12509: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 12510: 
                   12511: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   12512: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   12513: 
1.620     albertel 12514: 	    if (($env{'user.name'} eq $uname) &&
                   12515: 		($env{'user.domain'} eq $udom)) {
                   12516: 		$section=$env{'request.course.sec'};
1.733     raeburn  12517:                 @groups = split(/:/,$env{'request.course.groups'});  
                   12518:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 12519: 	    } else {
1.539     albertel 12520: 		if (! defined($usection)) {
1.551     albertel 12521: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 12522: 		} else {
                   12523: 		    $section = $usection;
                   12524: 		}
1.733     raeburn  12525:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12526: 	    }
                   12527: 
                   12528: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12529: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   12530: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12531: 
1.593     albertel 12532: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12533: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 12534: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12535: 
1.60      www      12536: # ----------------------------------------------------------- first, check user
1.624     albertel 12537: 
                   12538: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 12539: 				       ([$courselevelr,'resource'],
                   12540: 					[$courselevelm,'map'     ],
                   12541: 					[$courselevel, 'course'  ]));
1.931     albertel 12542: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12543: 
1.594     albertel 12544: # ------------------------------------------------ second, check some of course
1.684     raeburn  12545:             my $coursereply;
1.691     raeburn  12546:             if (@groups > 0) {
                   12547:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   12548:                                        $mapparm,$spacequalifierrest);
1.927     albertel 12549:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  12550:             }
1.96      www      12551: 
1.684     raeburn  12552: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12553: 				  $env{'course.'.$courseid.'.domain'},
                   12554: 				  'course',
                   12555: 				  ([$seclevelr,   'resource'],
                   12556: 				   [$seclevelm,   'map'     ],
                   12557: 				   [$seclevel,    'course'  ],
                   12558: 				   [$courselevelr,'resource']));
                   12559: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12560: 
1.60      www      12561: # ------------------------------------------------------ third, check map parms
1.218     albertel 12562: 	    my %parmhash=();
                   12563: 	    my $thisparm='';
                   12564: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12565: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12566: 		    &GDBM_READER(),0640)) {
1.218     albertel 12567: 		$thisparm=$parmhash{$symbparm};
                   12568: 		untie(%parmhash);
                   12569: 	    }
1.927     albertel 12570: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12571: 	}
1.594     albertel 12572: # ------------------------------------------ fourth, look in resource metadata
1.71      www      12573: 
1.1172.2.146.  .13(raeb 12574:-23):         my $what = $spacequalifierrest;
                   12575:-23):         $what=~s/\./\_/;
                   12576:-23):         my $filename;
1.282     albertel 12577: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12578: 	if ($symbparm) {
1.409     www      12579: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12580: 	} else {
1.620     albertel 12581: 	    $filename=$env{'request.filename'};
1.282     albertel 12582: 	}
1.1172.2.146.  .13(raeb 12583:-23):         my $toolsymb;
                   12584:-23):         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   12585:-23):             $toolsymb = $symbparm;
                   12586:-23):         }
                   12587:-23): 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 12588: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1172.2.146.  .13(raeb 12589:-23): 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 12590: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12591: 
1.1172.2.146.  .13(raeb 12592:-23): # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 12593: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12594: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12595: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12596: 				     $env{'course.'.$courseid.'.domain'},
                   12597: 				     'course',
1.927     albertel 12598: 				     ([$courselevelm,'map'   ],
                   12599: 				      [$courselevel, 'course']));
                   12600: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12601: 	}
1.145     www      12602: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12603: 	unless ($space eq '0') {
1.336     albertel 12604: 	    my @parts=split(/_/,$space);
                   12605: 	    my $id=pop(@parts);
                   12606: 	    my $part=join('_',@parts);
                   12607: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12608: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12609: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12610: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12611: 	}
1.395     albertel 12612: 	if ($recurse) { return undef; }
1.1172.2.146.  .13(raeb 12613:-23): 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 12614: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12615: # ---------------------------------------------------- Any other user namespace
                   12616:     } elsif ($realm eq 'environment') {
                   12617: # ----------------------------------------------------------------- environment
1.620     albertel 12618: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12619: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12620: 	} else {
1.770     albertel 12621: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12622: 		return '';
                   12623: 	    }
1.219     albertel 12624: 	    my %returnhash=&userenvironment($udom,$uname,
                   12625: 					    $spacequalifierrest);
                   12626: 	    return $returnhash{$spacequalifierrest};
                   12627: 	}
1.28      www      12628:     } elsif ($realm eq 'system') {
1.48      www      12629: # ----------------------------------------------------------------- system.time
                   12630: 	if ($space eq 'time') {
                   12631: 	    return time;
                   12632:         }
1.696     albertel 12633:     } elsif ($realm eq 'server') {
                   12634: # ----------------------------------------------------------------- system.time
                   12635: 	if ($space eq 'name') {
                   12636: 	    return $ENV{'SERVER_NAME'};
                   12637:         }
1.1172.2.146.  .1(raebu 12638:22):     } elsif ($realm eq 'client') {
                   12639:22):         if ($space eq 'remote_addr') {
                   12640:22):             return &get_requestor_ip();
                   12641:22):         }
1.28      www      12642:     }
1.48      www      12643:     return '';
1.61      www      12644: }
                   12645: 
1.927     albertel 12646: sub get_reply {
                   12647:     my ($reply_value) = @_;
1.940     raeburn  12648:     if (ref($reply_value) eq 'ARRAY') {
                   12649:         if (wantarray) {
                   12650: 	    return @$reply_value;
                   12651:         }
                   12652:         return $reply_value->[0];
                   12653:     } else {
                   12654:         return $reply_value;
1.927     albertel 12655:     }
                   12656: }
                   12657: 
1.691     raeburn  12658: sub check_group_parms {
                   12659:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   12660:     my @groupitems = ();
                   12661:     my $resultitem;
1.927     albertel 12662:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  12663:     foreach my $group (@{$groups}) {
                   12664:         foreach my $level (@levels) {
1.927     albertel 12665:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12666:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12667:         }
                   12668:     }
                   12669:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12670:                             $env{'course.'.$courseid.'.domain'},
                   12671:                                      'course',@groupitems);
                   12672:     return $coursereply;
                   12673: }
                   12674: 
1.1172.2.146.  .1(raebu 12675:22): sub get_map_hierarchy {
                   12676:22):     my ($mapname,$courseid) = @_;
                   12677:22):     my @recurseup = ();
                   12678:22):     if ($mapname) {
                   12679:22):         if (($cachedmapkey eq $courseid) &&
                   12680:22):             (abs($cachedmaptime-time)<5)) {
                   12681:22):             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12682:22):                 return @{$cachedmaps{$mapname}};
                   12683:22):             }
                   12684:22):         }
                   12685:22):         my $navmap = Apache::lonnavmaps::navmap->new();
                   12686:22):         if (ref($navmap)) {
                   12687:22):             @recurseup = $navmap->recurseup_maps($mapname);
                   12688:22):             undef($navmap);
                   12689:22):             $cachedmaps{$mapname} = \@recurseup;
                   12690:22):             $cachedmaptime=time;
                   12691:22):             $cachedmapkey=$courseid;
                   12692:22):         }
                   12693:22):     }
                   12694:22):     return @recurseup;
                   12695:22): }
                   12696:22): 
          .2(raebu 12697:22): }
          .1(raebu 12698:22): 
1.691     raeburn  12699: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12700:     my ($courseid,@groups) = @_;
                   12701:     @groups = sort(@groups);
1.691     raeburn  12702:     return @groups;
                   12703: }
                   12704: 
1.395     albertel 12705: sub packages_tab_default {
1.1172.2.146.  .13(raeb 12706:-23):     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 12707:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12708: 
                   12709:     my (@extension,@specifics,$do_default);
1.1172.2.146.  .13(raeb 12710:-23):     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 12711: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12712: 	if ($pack_type eq 'default') {
                   12713: 	    $do_default=1;
                   12714: 	} elsif ($pack_type eq 'extension') {
                   12715: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12716: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12717: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12718: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12719: 	}
                   12720:     }
                   12721:     # first look for a package that matches the requested part id
                   12722:     foreach my $package (@specifics) {
                   12723: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12724: 	next if ($pack_part ne $part);
                   12725: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12726: 	    return $packagetab{"$pack_type&$name&default"};
                   12727: 	}
                   12728:     }
                   12729:     # look for any possible matching non extension_ package
                   12730:     foreach my $package (@specifics) {
                   12731: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12732: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12733: 	    return $packagetab{"$pack_type&$name&default"};
                   12734: 	}
1.585     albertel 12735: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12736: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12737: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12738: 	}
                   12739:     }
1.738     albertel 12740:     # look for any posible extension_ match
                   12741:     foreach my $package (@extension) {
                   12742: 	my ($package,$pack_type)=@{$package};
                   12743: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12744: 	    return $packagetab{"$pack_type&$name&default"};
                   12745: 	}
                   12746: 	if (defined($packagetab{$package."&$name&default"})) {
                   12747: 	    return $packagetab{$package."&$name&default"};
                   12748: 	}
                   12749:     }
                   12750:     # look for a global default setting
                   12751:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12752: 	return $packagetab{"default&$name&default"};
                   12753:     }
1.395     albertel 12754:     return undef;
                   12755: }
                   12756: 
1.334     albertel 12757: sub add_prefix_and_part {
                   12758:     my ($prefix,$part)=@_;
                   12759:     my $keyroot;
                   12760:     if (defined($prefix) && $prefix !~ /^__/) {
                   12761: 	# prefix that has a part already
                   12762: 	$keyroot=$prefix;
                   12763:     } elsif (defined($prefix)) {
                   12764: 	# prefix that is missing a part
                   12765: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12766:     } else {
                   12767: 	# no prefix at all
                   12768: 	if (defined($part)) { $keyroot='_'.$part; }
                   12769:     }
                   12770:     return $keyroot;
                   12771: }
                   12772: 
1.71      www      12773: # ---------------------------------------------------------------- Get metadata
                   12774: 
1.599     albertel 12775: my %metaentry;
1.1070    www      12776: my %importedpartids;
1.1172.2.99  raeburn  12777: my %importedrespids;
1.71      www      12778: sub metadata {
1.1172.2.146.  .13(raeb 12779:-23):     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      12780:     $uri=&declutter($uri);
1.288     albertel 12781:     # if it is a non metadata possible uri return quickly
1.529     albertel 12782:     if (($uri eq '') || 
                   12783: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.146.  .1(raebu 12784:22): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12785:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12786: 	return undef;
                   12787:     }
1.1172.2.49  raeburn  12788:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12789: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12790: 	return undef;
1.288     albertel 12791:     }
1.73      www      12792:     my $filename=$uri;
                   12793:     $uri=~s/\.meta$//;
1.172     www      12794: #
                   12795: # Is the metadata already cached?
1.177     www      12796: # Look at timestamp of caching
1.172     www      12797: # Everything is cached by the main uri, libraries are never directly cached
                   12798: #
1.428     albertel 12799:     if (!defined($liburi)) {
1.599     albertel 12800: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12801: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12802:     }
1.1172.2.146.  .13(raeb 12803:-23): 
                   12804:-23): #
                   12805:-23): # If the uri is for an external tool the file from
                   12806:-23): # which metadata should be retrieved depends on whether
                   12807:-23): # the tool had been configured to be gradable (set in the Course
                   12808:-23): # Editor or Resource Editor).
                   12809:-23): #
                   12810:-23): # If a valid symb has been included as the third arg in the call
                   12811:-23): # to &metadata() that can be used to retrieve the value of
                   12812:-23): # parameter_0_gradable set for the resource, and included in the
                   12813:-23): # uploaded map containing the tool. The value is retrieved via
                   12814:-23): # &EXT(), if a valid symb is available.  Otherwise the value of
                   12815:-23): # gradable in the exttool_$marker.db file for the tool instance
                   12816:-23): # is retrieved via &get().
                   12817:-23): #
                   12818:-23): # When lonuserstate::traceroute() calls lonnet::EXT() for
                   12819:-23): # hiddenresource and encrypturl (during course initialization)
                   12820:-23): # the map-level parameter for resource.0.gradable included in the
                   12821:-23): # uploaded map containing the tool will not yet have been stored
                   12822:-23): # in the user_course_parms.db file for the user's session, so in
                   12823:-23): # this case fall back to retrieving gradable status from the
                   12824:-23): # exttool_$marker.db file.
                   12825:-23): #
                   12826:-23): # In order to avoid an infinite loop, &metadata() will return
                   12827:-23): # before a call to &EXT(), if the uri is for an external tool
                   12828:-23): # and the $what for which metadata is being requested is
                   12829:-23): # parameter_0_gradable or 0_gradable.
                   12830:-23): #
                   12831:-23): 
                   12832:-23):     if ($uri =~ /ext\.tool$/) {
                   12833:-23):         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   12834:-23):             return;
                   12835:-23):         } else {
                   12836:-23):             my ($checked,$use_passback);
                   12837:-23):             if ($toolsymb ne '') {
                   12838:-23):                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
                   12839:-23):                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
                   12840:-23):                     $checked = 1;
                   12841:-23):                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   12842:-23):                         $use_passback = 1;
                   12843:-23):                     }
                   12844:-23):                 }
                   12845:-23):             }
                   12846:-23):             unless ($checked) {
                   12847:-23):                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   12848:-23):                 $marker=~s/\D//g;
                   12849:-23):                 if ($marker) {
                   12850:-23):                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   12851:-23):                     $use_passback = $toolsettings{'gradable'};
                   12852:-23):                 }
                   12853:-23):             }
                   12854:-23):             if ($use_passback) {
                   12855:-23):                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   12856:-23):             } else {
                   12857:-23):                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   12858:-23):             }
                   12859:-23):         }
                   12860:-23):     }
                   12861:-23): 
1.428     albertel 12862:     {
1.1069    www      12863: # Imported parts would go here
1.1172.2.99  raeburn  12864:         my @origfiletagids=();
1.1069    www      12865:         my $importedparts=0;
1.1172.2.99  raeburn  12866: 
                   12867: # Imported responseids would go here
                   12868:         my $importedresponses=0;
1.172     www      12869: #
                   12870: # Is this a recursive call for a library?
                   12871: #
1.599     albertel 12872: #	if (! exists($metacache{$uri})) {
                   12873: #	    $metacache{$uri}={};
                   12874: #	}
1.924     albertel 12875: 	my $cachetime = 60*60;
1.171     www      12876:         if ($liburi) {
                   12877: 	    $liburi=&declutter($liburi);
                   12878:             $filename=$liburi;
1.401     bowersj2 12879:         } else {
1.599     albertel 12880: 	    &devalidate_cache_new('meta',$uri);
                   12881: 	    undef(%metaentry);
1.401     bowersj2 12882: 	}
1.140     www      12883:         my %metathesekeys=();
1.73      www      12884:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12885: 	my $metastring;
1.1140    www      12886: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12887: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12888: 	    $metastring = 
1.929     albertel 12889: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12890: 					  ('grade_target' => 'meta'));
                   12891: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12892: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12893:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12894: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12895: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12896: 	    $metastring=&getfile($file);
1.489     albertel 12897: 	}
1.208     albertel 12898:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12899:         my $token;
1.140     www      12900:         undef %metathesekeys;
1.71      www      12901:         while ($token=$parser->get_token) {
1.339     albertel 12902: 	    if ($token->[0] eq 'S') {
                   12903: 		if (defined($token->[2]->{'package'})) {
1.172     www      12904: #
                   12905: # This is a package - get package info
                   12906: #
1.339     albertel 12907: 		    my $package=$token->[2]->{'package'};
                   12908: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12909: 		    if (defined($token->[2]->{'id'})) { 
                   12910: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12911: 		    }
1.599     albertel 12912: 		    if ($metaentry{':packages'}) {
                   12913: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12914: 		    } else {
1.599     albertel 12915: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12916: 		    }
1.736     albertel 12917: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12918: 			my $part=$keyroot;
                   12919: 			$part=~s/^\_//;
1.736     albertel 12920: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12921: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12922: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12923: 			    # ignore package.tab specified default values
                   12924:                             # here &package_tab_default() will fetch those
                   12925: 			    if ($subp eq 'default') { next; }
1.736     albertel 12926: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12927: 			    my $unikey;
                   12928: 			    if ($pack =~ /_0$/) {
                   12929: 				$unikey='parameter_0_'.$name;
                   12930: 				$part=0;
                   12931: 			    } else {
                   12932: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12933: 			    }
1.339     albertel 12934: 			    if ($subp eq 'display') {
                   12935: 				$value.=' [Part: '.$part.']';
                   12936: 			    }
1.599     albertel 12937: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12938: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12939: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12940: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12941: 			    }
1.599     albertel 12942: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12943: 				$metaentry{':'.$unikey}=
                   12944: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12945: 			    }
1.339     albertel 12946: 			}
                   12947: 		    }
                   12948: 		} else {
1.172     www      12949: #
                   12950: # This is not a package - some other kind of start tag
1.339     albertel 12951: #
                   12952: 		    my $entry=$token->[1];
1.1068    www      12953: 		    my $unikey='';
1.175     www      12954: 
1.339     albertel 12955: 		    if ($entry eq 'import') {
1.175     www      12956: #
                   12957: # Importing a library here
1.339     albertel 12958: #
1.1067    www      12959:                         my $location=$parser->get_text('/import');
                   12960:                         my $dir=$filename;
                   12961:                         $dir=~s|[^/]*$||;
                   12962:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  12963: 
                   12964:                         my $importid=$token->[2]->{'id'};
1.1068    www      12965:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  12966: #
                   12967: # Check metadata for imported file to
                   12968: # see if it contained response items
                   12969: #
                   12970:                         my %currmetaentry = %metaentry;
                   12971:                         my $libresponseorder = &metadata($location,'responseorder');
                   12972:                         my $origfile;
                   12973:                         if ($libresponseorder ne '') {
                   12974:                             if ($#origfiletagids<0) {
                   12975:                                 undef(%importedrespids);
                   12976:                                 undef(%importedpartids);
                   12977:                             }
                   12978:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   12979:                             if (@{$importedrespids{$importid}} > 0) {
                   12980:                                 $importedresponses = 1;
                   12981: # We need to get the original file and the imported file to get the response order correct
                   12982: # Load and inspect original file
                   12983:                                 if ($#origfiletagids<0) {
                   12984:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12985:                                     $origfile=&getfile($origfilelocation);
                   12986:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12987:                                 }
                   12988:                             }
                   12989:                         }
                   12990: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12991: # hash populated for imported library file
                   12992:                         %metaentry = %currmetaentry;
                   12993:                         undef(%currmetaentry);
1.1068    www      12994:                         if ($importmode eq 'problem') {
1.1069    www      12995: # Import as problem/response
1.1068    www      12996:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12997:                         } elsif ($importmode eq 'part') {
                   12998: # Import as part(s)
1.1069    www      12999:                            $importedparts=1;
                   13000: # We need to get the original file and the imported file to get the part order correct
                   13001: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  13002: # Load and inspect original file if we didn't do that already
                   13003:                            if ($#origfiletagids<0) {
                   13004:                                undef(%importedrespids);
                   13005:                                undef(%importedpartids);
                   13006:                                if ($origfile eq '') {
                   13007:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   13008:                                    $origfile=&getfile($origfilelocation);
                   13009:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13010:                                }
1.1070    www      13011:                            }
                   13012: 
1.1069    www      13013: # Load and inspect imported file
                   13014:                            my $impfile=&getfile($location);
                   13015:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13016:                            if ($#impfilepartids>=0) {
                   13017: # This problem had parts
1.1070    www      13018:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      13019:                            } else {
                   13020: # Importing by turning a single problem into a problem part
                   13021: # It gets the import-tags ID as part-ID
                   13022:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      13023:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      13024:                            }
1.1068    www      13025:                         } else {
                   13026: # Normal import
                   13027:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13028:                            if (defined($token->[2]->{'id'})) {
                   13029:                               $unikey.='_'.$token->[2]->{'id'};
                   13030:                            }
1.1067    www      13031:                         }
                   13032: 
1.339     albertel 13033: 			if ($depthcount<20) {
1.736     albertel 13034: 			    my $metadata = 
1.1172.2.146.  .13(raeb 13035:-23): 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 13036: 					  $depthcount+1);
                   13037: 			    foreach my $meta (split(',',$metadata)) {
                   13038: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   13039: 				$metathesekeys{$meta}=1;
1.339     albertel 13040: 			    }
1.1068    www      13041: 			
                   13042:                         }
1.1067    www      13043: 		    } else {
                   13044: #
                   13045: # Not importing, some other kind of non-package, non-library start tag
                   13046: # 
                   13047:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13048:                         if (defined($token->[2]->{'id'})) {
                   13049:                             $unikey.='_'.$token->[2]->{'id'};
                   13050:                         }
1.339     albertel 13051: 			if (defined($token->[2]->{'name'})) { 
                   13052: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   13053: 			}
                   13054: 			$metathesekeys{$unikey}=1;
1.736     albertel 13055: 			foreach my $param (@{$token->[3]}) {
                   13056: 			    $metaentry{':'.$unikey.'.'.$param} =
                   13057: 				$token->[2]->{$param};
1.339     albertel 13058: 			}
                   13059: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 13060: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 13061: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   13062: 		 # only ws inside the tag, and not in default, so use default
                   13063: 		 # as value
1.599     albertel 13064: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 13065: 			} elsif ( $internaltext =~ /\S/ ) {
                   13066: 		  # something interesting inside the tag
                   13067: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 13068: 			} else {
1.908     albertel 13069: 		  # no interesting values, don't set a default
1.339     albertel 13070: 			}
1.172     www      13071: # end of not-a-package not-a-library import
1.339     albertel 13072: 		    }
1.172     www      13073: # end of not-a-package start tag
1.339     albertel 13074: 		}
1.172     www      13075: # the next is the end of "start tag"
1.339     albertel 13076: 	    }
                   13077: 	}
1.483     albertel 13078: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 13079: 	$extension = lc($extension);
                   13080: 	if ($extension eq 'htm') { $extension='html'; }
                   13081: 
1.737     albertel 13082: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 13083: 	    #no specific packages #how's our extension
                   13084: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 13085: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 13086: 					 \%metathesekeys);
                   13087: 	}
1.883     albertel 13088: 
                   13089: 	if (!exists($metaentry{':packages'})
                   13090: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 13091: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 13092: 		#no specific packages well let's get default then
                   13093: 		if ($key!~/^default&/) { next; }
1.488     albertel 13094: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 13095: 					     \%metathesekeys);
                   13096: 	    }
                   13097: 	}
1.338     www      13098: # are there custom rights to evaluate
1.599     albertel 13099: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 13100: 
1.338     www      13101:     #
                   13102:     # Importing a rights file here
1.339     albertel 13103:     #
                   13104: 	    unless ($depthcount) {
1.599     albertel 13105: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 13106: 		my $dir=$filename;
                   13107: 		$dir=~s|[^/]*$||;
                   13108: 		$location=&filelocation($dir,$location);
1.736     albertel 13109: 		my $rights_metadata =
1.1172.2.146.  .13(raeb 13110:-23): 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 13111: 			      $depthcount+1);
                   13112: 		foreach my $rights (split(',',$rights_metadata)) {
                   13113: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   13114: 		    $metathesekeys{$rights}=1;
1.339     albertel 13115: 		}
                   13116: 	    }
                   13117: 	}
1.737     albertel 13118: 	# uniqifiy package listing
                   13119: 	my %seen;
                   13120: 	my @uniq_packages =
                   13121: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   13122: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   13123: 
1.1172.2.99  raeburn  13124:         if (($importedresponses) || ($importedparts)) {
                   13125:             if ($importedparts) {
1.1070    www      13126: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  13127:                 $metaentry{':partorder'}='';
                   13128:                 $metathesekeys{'partorder'}=1;
                   13129:             }
                   13130:             if ($importedresponses) {
                   13131: # We had imported responses and need to rebuild responseorder
                   13132:                 $metaentry{':responseorder'}='';
                   13133:                 $metathesekeys{'responseorder'}=1;
                   13134:             }
                   13135:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   13136:                 my $origid = $origfiletagids[$index+1];
                   13137:                 if ($origfiletagids[$index] eq 'part') {
                   13138: # Original part, part of the problem
                   13139:                     if ($importedparts) {
                   13140:                         $metaentry{':partorder'}.=','.$origid;
                   13141:                     }
                   13142:                 } elsif ($origfiletagids[$index] eq 'import') {
                   13143:                     if ($importedparts) {
                   13144: # We have imported parts at this position
                   13145:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   13146:                     }
                   13147:                     if ($importedresponses) {
                   13148: # We have imported responses at this position
                   13149:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   13150:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   13151:                         }
                   13152:                     }
                   13153:                 } else {
                   13154: # Original response item, part of the problem
                   13155:                     if ($importedresponses) {
                   13156:                         $metaentry{':responseorder'}.=','.$origid;
                   13157:                     }
                   13158:                 }
                   13159:             }
                   13160:             if ($importedparts) {
                   13161:                 $metaentry{':partorder'}=~s/^\,//;
                   13162:             }
                   13163:             if ($importedresponses) {
                   13164:                 $metaentry{':responseorder'}=~s/^\,//;
                   13165:             }
1.1070    www      13166:         }
                   13167: 
1.737     albertel 13168: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 13169: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  13170: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 13171: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      13172: # this is the end of "was not already recently cached
1.71      www      13173:     }
1.599     albertel 13174:     return $metaentry{':'.$what};
1.261     albertel 13175: }
                   13176: 
1.488     albertel 13177: sub metadata_create_package_def {
1.483     albertel 13178:     my ($uri,$key,$package,$metathesekeys)=@_;
                   13179:     my ($pack,$name,$subp)=split(/\&/,$key);
                   13180:     if ($subp eq 'default') { next; }
                   13181:     
1.599     albertel 13182:     if (defined($metaentry{':packages'})) {
                   13183: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 13184:     } else {
1.599     albertel 13185: 	$metaentry{':packages'}=$package;
1.483     albertel 13186:     }
                   13187:     my $value=$packagetab{$key};
                   13188:     my $unikey;
                   13189:     $unikey='parameter_0_'.$name;
1.599     albertel 13190:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 13191:     $$metathesekeys{$unikey}=1;
1.599     albertel 13192:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   13193: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 13194:     }
1.599     albertel 13195:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   13196: 	$metaentry{':'.$unikey}=
                   13197: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 13198:     }
                   13199: }
                   13200: 
1.261     albertel 13201: sub metadata_generate_part0 {
                   13202:     my ($metadata,$metacache,$uri) = @_;
                   13203:     my %allnames;
1.737     albertel 13204:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 13205: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 13206: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   13207: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 13208: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 13209: 	    $allnames{$name}=$part;
                   13210: 	  }
                   13211: 	}
                   13212:     }
                   13213:     foreach my $name (keys(%allnames)) {
                   13214:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 13215:       my $key=":parameter_0_$name";
1.261     albertel 13216:       $$metacache{"$key.part"}='0';
                   13217:       $$metacache{"$key.name"}=$name;
1.428     albertel 13218:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 13219: 					   $allnames{$name}.'_'.$name.
                   13220: 					   '.type'};
1.428     albertel 13221:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 13222: 			     '.display'};
1.644     www      13223:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 13224:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 13225:       $$metacache{"$key.display"}=$olddis;
                   13226:     }
1.71      www      13227: }
                   13228: 
1.764     albertel 13229: # ------------------------------------------------------ Devalidate title cache
                   13230: 
                   13231: sub devalidate_title_cache {
                   13232:     my ($url)=@_;
                   13233:     if (!$env{'request.course.id'}) { return; }
                   13234:     my $symb=&symbread($url);
                   13235:     if (!$symb) { return; }
                   13236:     my $key=$env{'request.course.id'}."\0".$symb;
                   13237:     &devalidate_cache_new('title',$key);
                   13238: }
                   13239: 
1.1014    droeschl 13240: # ------------------------------------------------- Get the title of a course
                   13241: 
                   13242: sub current_course_title {
                   13243:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   13244: }
1.301     www      13245: # ------------------------------------------------- Get the title of a resource
                   13246: 
                   13247: sub gettitle {
                   13248:     my $urlsymb=shift;
                   13249:     my $symb=&symbread($urlsymb);
1.534     albertel 13250:     if ($symb) {
1.620     albertel 13251: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 13252: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 13253: 	if (defined($cached)) { 
                   13254: 	    return $result;
                   13255: 	}
1.534     albertel 13256: 	my ($map,$resid,$url)=&decode_symb($symb);
                   13257: 	my $title='';
1.907     albertel 13258: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   13259: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   13260: 	} else {
                   13261: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   13262: 		    &GDBM_READER(),0640)) {
                   13263: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   13264: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   13265: 		untie(%bighash);
                   13266: 	    }
1.534     albertel 13267: 	}
                   13268: 	$title=~s/\&colon\;/\:/gs;
                   13269: 	if ($title) {
1.1159    www      13270: # Remember both $symb and $title for dynamic metadata
                   13271:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      13272:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      13273: # Cache this title and then return it
1.599     albertel 13274: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 13275: 	}
                   13276: 	$urlsymb=$url;
                   13277:     }
                   13278:     my $title=&metadata($urlsymb,'title');
                   13279:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   13280:     return $title;
1.301     www      13281: }
1.613     albertel 13282: 
1.614     albertel 13283: sub get_slot {
                   13284:     my ($which,$cnum,$cdom)=@_;
                   13285:     if (!$cnum || !$cdom) {
1.790     albertel 13286: 	(undef,my $courseid)=&whichuser();
1.620     albertel 13287: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   13288: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 13289:     }
1.703     albertel 13290:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   13291:     my %slotinfo;
                   13292:     if (exists($remembered{$key})) {
                   13293: 	$slotinfo{$which} = $remembered{$key};
                   13294:     } else {
                   13295: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   13296: 	&Apache::lonhomework::showhash(%slotinfo);
                   13297: 	my ($tmp)=keys(%slotinfo);
                   13298: 	if ($tmp=~/^error:/) { return (); }
                   13299: 	$remembered{$key} = $slotinfo{$which};
                   13300:     }
1.616     albertel 13301:     if (ref($slotinfo{$which}) eq 'HASH') {
                   13302: 	return %{$slotinfo{$which}};
                   13303:     }
                   13304:     return $slotinfo{$which};
1.614     albertel 13305: }
1.1150    raeburn  13306: 
                   13307: sub get_reservable_slots {
                   13308:     my ($cnum,$cdom,$uname,$udom) = @_;
                   13309:     my $now = time;
                   13310:     my $reservable_info;
                   13311:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   13312:     if (exists($remembered{$key})) {
                   13313:         $reservable_info = $remembered{$key};
                   13314:     } else {
                   13315:         my %resv;
                   13316:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   13317:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   13318:         $reservable_info = \%resv;
                   13319:         $remembered{$key} = $reservable_info;
                   13320:     }
                   13321:     return $reservable_info;
                   13322: }
                   13323: 
                   13324: sub get_course_slots {
                   13325:     my ($cnum,$cdom) = @_;
                   13326:     my $hashid=$cnum.':'.$cdom;
                   13327:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   13328:     if (defined($cached)) {
                   13329:         if (ref($result) eq 'HASH') {
                   13330:             return %{$result};
                   13331:         }
                   13332:     } else {
                   13333:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   13334:         my ($tmp) = keys(%slots);
                   13335:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  13336:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  13337:             return %slots;
                   13338:         }
                   13339:     }
                   13340:     return;
                   13341: }
                   13342: 
                   13343: sub devalidate_slots_cache {
                   13344:     my ($cnum,$cdom)=@_;
                   13345:     my $hashid=$cnum.':'.$cdom;
                   13346:     &devalidate_cache_new('allslots',$hashid);
                   13347: }
                   13348: 
1.1172.2.8  raeburn  13349: sub get_coursechange {
                   13350:     my ($cdom,$cnum) = @_;
                   13351:     if ($cdom eq '' || $cnum eq '') {
                   13352:         return unless ($env{'request.course.id'});
                   13353:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   13354:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   13355:     }
                   13356:     my $hashid=$cdom.'_'.$cnum;
                   13357:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   13358:     if ((defined($cached)) && ($change ne '')) {
                   13359:         return $change;
                   13360:     } else {
                   13361:         my %crshash;
                   13362:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   13363:         if ($crshash{'internal.contentchange'} eq '') {
                   13364:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13365:             if ($change eq '') {
                   13366:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13367:                 $change = $crshash{'internal.created'};
                   13368:             }
                   13369:         } else {
                   13370:             $change = $crshash{'internal.contentchange'};
                   13371:         }
                   13372:         my $cachetime = 600;
                   13373:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   13374:     }
                   13375:     return $change;
                   13376: }
                   13377: 
                   13378: sub devalidate_coursechange_cache {
1.1172.2.146.  .9(raebu 13379:23):     my ($cdom,$cnum)=@_;
                   13380:23):     my $hashid=$cdom.'_'.$cnum;
1.1172.2.8  raeburn  13381:     &devalidate_cache_new('crschange',$hashid);
                   13382: }
                   13383: 
1.1172.2.146.  .9(raebu 13384:23): sub get_suppchange {
                   13385:23):     my ($cdom,$cnum) = @_;
                   13386:23):     if ($cdom eq '' || $cnum eq '') {
                   13387:23):         return unless ($env{'request.course.id'});
                   13388:23):         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   13389:23):         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   13390:23):     }
                   13391:23):     my $hashid=$cdom.'_'.$cnum;
                   13392:23):     my ($change,$cached)=&is_cached_new('suppchange',$hashid);
                   13393:23):     if ((defined($cached)) && ($change ne '')) {
                   13394:23):         return $change;
                   13395:23):     } else {
                   13396:23):         my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
                   13397:23):         if ($crshash{'internal.supplementalchange'} eq '') {
                   13398:23):             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13399:23):             if ($change eq '') {
                   13400:23):                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13401:23):                 $change = $crshash{'internal.created'};
                   13402:23):             }
                   13403:23):         } else {
                   13404:23):             $change = $crshash{'internal.supplementalchange'};
                   13405:23):         }
                   13406:23):         my $cachetime = 600;
                   13407:23):         &do_cache_new('suppchange',$hashid,$change,$cachetime);
                   13408:23):     }
                   13409:23):     return $change;
                   13410:23): }
                   13411:23): 
                   13412:23): sub devalidate_suppchange_cache {
                   13413:23):     my ($cdom,$cnum)=@_;
                   13414:23):     my $hashid=$cdom.'_'.$cnum;
                   13415:23):     &devalidate_cache_new('suppchange',$hashid);
                   13416:23): }
                   13417:23): 
                   13418:23): sub update_supp_caches {
                   13419:23):     my ($cdom,$cnum) = @_;
                   13420:23):     my %servers = &internet_dom_servers($cdom);
                   13421:23):     my @ids=&current_machine_ids();
                   13422:23):     foreach my $server (keys(%servers)) {
                   13423:23):         next if (grep(/^\Q$server\E$/,@ids));
                   13424:23):         my $hashid=$cnum.':'.$cdom;
                   13425:23):         my $cachekey = &escape('showsupp').':'.&escape($hashid);
                   13426:23):         &remote_devalidate_cache($server,[$cachekey]);
                   13427:23):     }
                   13428:23):     &has_unhidden_suppfiles($cnum,$cdom,1,1);
                   13429:23):     &count_supptools($cnum,$cdom,1);
                   13430:23):     my $now = time;
                   13431:23):     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   13432:23):         &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
                   13433:23):     }
                   13434:23):     &put('environment',{'internal.supplementalchange' => $now},
                   13435:23):          $cdom,$cnum);
                   13436:23):     &Apache::lonnet::appenv(
                   13437:23):         {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
                   13438:23):     &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
                   13439:23): }
                   13440:23): 
1.31      www      13441: # ------------------------------------------------- Update symbolic store links
                   13442: 
                   13443: sub symblist {
                   13444:     my ($mapname,%newhash)=@_;
1.438     www      13445:     $mapname=&deversion(&declutter($mapname));
1.31      www      13446:     my %hash;
1.620     albertel 13447:     if (($env{'request.course.fn'}) && (%newhash)) {
                   13448:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 13449:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  13450: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 13451: 		next if ($url eq 'last_known'
                   13452: 			 && $env{'form.no_update_last_known'});
                   13453: 		$hash{declutter($url)}=&encode_symb($mapname,
                   13454: 						    $newhash{$url}->[1],
                   13455: 						    $newhash{$url}->[0]);
1.191     harris41 13456:             }
1.31      www      13457:             if (untie(%hash)) {
                   13458: 		return 'ok';
                   13459:             }
                   13460:         }
                   13461:     }
                   13462:     return 'error';
1.212     www      13463: }
                   13464: 
                   13465: # --------------------------------------------------------------- Verify a symb
                   13466: 
                   13467: sub symbverify {
1.1172.2.11  raeburn  13468:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      13469:     my $thisfn=$thisurl;
1.439     www      13470:     $thisfn=&declutter($thisfn);
1.215     www      13471: # direct jump to resource in page or to a sequence - will construct own symbs
                   13472:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   13473: # check URL part
1.409     www      13474:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      13475: 
1.431     www      13476:     unless ($url eq $thisfn) { return 0; }
1.213     www      13477: 
1.216     www      13478:     $symb=&symbclean($symb);
1.510     www      13479:     $thisurl=&deversion($thisurl);
1.439     www      13480:     $thisfn=&deversion($thisfn);
1.213     www      13481: 
                   13482:     my %bighash;
                   13483:     my $okay=0;
1.431     www      13484: 
1.620     albertel 13485:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13486:                             &GDBM_READER(),0640)) {
1.1032    raeburn  13487:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   13488:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  13489:             if ($map =~ m{^uploaded/.+\.page$}) {
                   13490:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   13491:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   13492:             }
                   13493:         }
                   13494:         my $ids;
1.1172.2.122  raeburn  13495:         if ($map =~ m{^uploaded/.+\.page$}) {
                   13496:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  13497:         } else {
                   13498:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  13499:         }
1.1102    raeburn  13500:         unless ($ids) {
1.1172.2.13  raeburn  13501:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  13502:             $ids=$bighash{$idkey};
1.216     www      13503:         }
                   13504:         if ($ids) {
                   13505: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  13506:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   13507:                 $symb =~ s/\?.+$//;
                   13508:             }
1.800     albertel 13509: 	    foreach my $id (split(/\,/,$ids)) {
                   13510: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      13511:                if (
                   13512:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  13513:    eq $symb) {
1.1172.2.11  raeburn  13514:                    if (ref($encstate)) {
                   13515:                        $$encstate = $bighash{'encrypted_'.$id};
                   13516:                    }
1.1172.2.13  raeburn  13517:                    if (($env{'request.role.adv'}) ||
                   13518:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  13519:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  13520:                        $okay=1;
                   13521:                        last;
                   13522:                    }
                   13523:                }
                   13524:            }
1.216     www      13525:         }
1.213     www      13526: 	untie(%bighash);
                   13527:     }
                   13528:     return $okay;
1.31      www      13529: }
                   13530: 
1.210     www      13531: # --------------------------------------------------------------- Clean-up symb
                   13532: 
                   13533: sub symbclean {
                   13534:     my $symb=shift;
1.568     albertel 13535:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      13536: # remove version from map
                   13537:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      13538: 
1.210     www      13539: # remove version from URL
                   13540:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      13541: 
1.507     www      13542: # remove wrapper
                   13543: 
1.510     www      13544:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 13545:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      13546:     return $symb;
1.409     www      13547: }
                   13548: 
                   13549: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 13550: 
                   13551: sub encode_symb {
                   13552:     my ($map,$resid,$url)=@_;
                   13553:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   13554: }
1.409     www      13555: 
                   13556: sub decode_symb {
1.568     albertel 13557:     my $symb=shift;
                   13558:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   13559:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      13560:     return (&fixversion($map),$resid,&fixversion($url));
                   13561: }
                   13562: 
                   13563: sub fixversion {
                   13564:     my $fn=shift;
1.609     banghart 13565:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      13566:     my %bighash;
                   13567:     my $uri=&clutter($fn);
1.620     albertel 13568:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      13569: # is this cached?
1.599     albertel 13570:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      13571:     if (defined($cached)) { return $result; }
                   13572: # unfortunately not cached, or expired
1.620     albertel 13573:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      13574: 	    &GDBM_READER(),0640)) {
                   13575:  	if ($bighash{'version_'.$uri}) {
                   13576:  	    my $version=$bighash{'version_'.$uri};
1.444     www      13577:  	    unless (($version eq 'mostrecent') || 
                   13578: 		    ($version==&getversion($uri))) {
1.440     www      13579:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   13580:  	    }
                   13581:  	}
                   13582:  	untie %bighash;
1.413     www      13583:     }
1.599     albertel 13584:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      13585: }
                   13586: 
                   13587: sub deversion {
                   13588:     my $url=shift;
                   13589:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   13590:     return $url;
1.210     www      13591: }
                   13592: 
1.31      www      13593: # ------------------------------------------------------ Return symb list entry
                   13594: 
                   13595: sub symbread {
1.1172.2.126  raeburn  13596:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128  raeburn  13597:         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  13598:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128  raeburn  13599:     if (defined($env{$cache_str})) {
1.1172.2.126  raeburn  13600:         unless (ref($possibles) eq 'HASH') {
                   13601:             if ($ignorecachednull) {
                   13602:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   13603:             } else {
                   13604:                 return $env{$cache_str};
                   13605:             }
1.1172.2.66  raeburn  13606:         }
                   13607:     }
1.242     www      13608: # no filename provided? try from environment
1.1172.2.54  raeburn  13609:     unless ($thisfn) {
1.620     albertel 13610:         if ($env{'request.symb'}) {
1.1172.2.128  raeburn  13611:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  13612:         }
                   13613:         $thisfn=$env{'request.filename'};
1.44      www      13614:     }
1.569     albertel 13615:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13616: # is that filename actually a symb? Verify, clean, and return
                   13617:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13618: 	if (&symbverify($thisfn,$1)) {
1.1172.2.128  raeburn  13619: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13620: 	}
1.242     www      13621:     }
1.44      www      13622:     $thisfn=declutter($thisfn);
1.31      www      13623:     my %hash;
1.37      www      13624:     my %bighash;
                   13625:     my $syval='';
1.620     albertel 13626:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.1172.2.128  raeburn  13627:         unless ($ignoresymbdb) {
1.1172.2.126  raeburn  13628:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   13629:                           &GDBM_READER(),0640)) {
1.1172.2.146.  .7(raebu 13630:22): 	        $syval=$hash{$thisfn};
1.1172.2.126  raeburn  13631:                 untie(%hash);
                   13632:             }
1.1172.2.128  raeburn  13633:             if ($syval && $checkforblock) {
                   13634:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126  raeburn  13635:                 if (@blockers) {
                   13636:                     $syval='';
                   13637:                 }
                   13638:             }
1.37      www      13639:         }
                   13640: # ---------------------------------------------------------- There was an entry
                   13641:         if ($syval) {
1.601     albertel 13642: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13643: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13644: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13645: 		    #return $env{$cache_str}='';
1.601     albertel 13646: 		#}    
                   13647: 		#$syval.=$1;
                   13648: 	    #}
1.37      www      13649:         } else {
                   13650: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13651:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13652:                             &GDBM_READER(),0640)) {
1.37      www      13653: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13654:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13655:               unless ($ids) { 
                   13656:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13657:               }
                   13658:               unless ($ids) {
                   13659: # alias?
                   13660: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13661:               }
1.37      www      13662:               if ($ids) {
                   13663: # ------------------------------------------------------------------- Has ID(s)
                   13664:                  my @possibilities=split(/\,/,$ids);
1.39      www      13665:                  if ($#possibilities==0) {
                   13666: # ----------------------------------------------- There is only one possibility
1.37      www      13667: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13668: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13669: 						    $resid,$thisfn);
1.1172.2.66  raeburn  13670:                      if (ref($possibles) eq 'HASH') {
1.1172.2.126  raeburn  13671:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   13672:                              $possibles->{$syval} = 1;
                   13673:                          }
1.1172.2.66  raeburn  13674:                      }
                   13675:                      if ($checkforblock) {
1.1172.2.126  raeburn  13676:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127  raeburn  13677:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126  raeburn  13678:                              if (@blockers) {
                   13679:                                  $syval = '';
                   13680:                                  untie(%bighash);
                   13681:                                  return $env{$cache_str}='';
                   13682:                              }
1.1172.2.66  raeburn  13683:                          }
                   13684:                      }
                   13685:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      13686: # ------------------------------------------ There is more than one possibility
                   13687:                      my $realpossible=0;
1.800     albertel 13688:                      foreach my $id (@possibilities) {
                   13689: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  13690:                          my $canaccess;
                   13691:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13692:                              $canaccess = 1;
                   13693:                          } else {
                   13694:                              $canaccess = &allowed('bre',$file);
                   13695:                          }
                   13696:                          if ($canaccess) {
                   13697:          		     my ($mapid,$resid)=split(/\./,$id);
                   13698:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13699:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13700:                                                              $resid,$thisfn);
1.1172.2.126  raeburn  13701:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127  raeburn  13702:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  13703:                                  if ($checkforblock) {
1.1172.2.127  raeburn  13704:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126  raeburn  13705:                                      if (@blockers > 0) {
                   13706:                                          $syval = '';
                   13707:                                      } else {
1.1172.2.66  raeburn  13708:                                          $syval = $poss_syval;
                   13709:                                          $realpossible++;
                   13710:                                      }
                   13711:                                  } else {
                   13712:                                      $syval = $poss_syval;
                   13713:                                      $realpossible++;
                   13714:                                  }
1.1172.2.126  raeburn  13715:                                  if ($syval) {
                   13716:                                      if (ref($possibles) eq 'HASH') {
                   13717:                                          $possibles->{$syval} = 1;
                   13718:                                      }
                   13719:                                  }
1.1172.2.66  raeburn  13720:                              }
1.39      www      13721: 			 }
1.191     harris41 13722:                      }
1.39      www      13723: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13724:                  } else {
                   13725:                      $syval='';
1.37      www      13726:                  }
                   13727: 	      }
1.1172.2.66  raeburn  13728:               untie(%bighash);
1.481     raeburn  13729:            }
1.31      www      13730:         }
1.62      www      13731:         if ($syval) {
1.1172.2.128  raeburn  13732: 	    return $env{$cache_str}=$syval;
1.62      www      13733:         }
1.31      www      13734:     }
1.949     raeburn  13735:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13736:     return $env{$cache_str}='';
1.31      www      13737: }
                   13738: 
                   13739: # ---------------------------------------------------------- Return random seed
                   13740: 
1.32      www      13741: sub numval {
                   13742:     my $txt=shift;
                   13743:     $txt=~tr/A-J/0-9/;
                   13744:     $txt=~tr/a-j/0-9/;
                   13745:     $txt=~tr/K-T/0-9/;
                   13746:     $txt=~tr/k-t/0-9/;
                   13747:     $txt=~tr/U-Z/0-5/;
                   13748:     $txt=~tr/u-z/0-5/;
                   13749:     $txt=~s/\D//g;
1.564     albertel 13750:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13751:     return int($txt);
1.368     albertel 13752: }
                   13753: 
1.484     albertel 13754: sub numval2 {
                   13755:     my $txt=shift;
                   13756:     $txt=~tr/A-J/0-9/;
                   13757:     $txt=~tr/a-j/0-9/;
                   13758:     $txt=~tr/K-T/0-9/;
                   13759:     $txt=~tr/k-t/0-9/;
                   13760:     $txt=~tr/U-Z/0-5/;
                   13761:     $txt=~tr/u-z/0-5/;
                   13762:     $txt=~s/\D//g;
                   13763:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13764:     my $total;
                   13765:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13766:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13767:     return int($total);
                   13768: }
                   13769: 
1.575     albertel 13770: sub numval3 {
                   13771:     use integer;
                   13772:     my $txt=shift;
                   13773:     $txt=~tr/A-J/0-9/;
                   13774:     $txt=~tr/a-j/0-9/;
                   13775:     $txt=~tr/K-T/0-9/;
                   13776:     $txt=~tr/k-t/0-9/;
                   13777:     $txt=~tr/U-Z/0-5/;
                   13778:     $txt=~tr/u-z/0-5/;
                   13779:     $txt=~s/\D//g;
                   13780:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13781:     my $total;
                   13782:     foreach my $val (@txts) { $total+=$val; }
                   13783:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13784:     return $total;
                   13785: }
                   13786: 
1.675     albertel 13787: sub digest {
                   13788:     my ($data)=@_;
                   13789:     my $digest=&Digest::MD5::md5($data);
                   13790:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13791:     my ($e,$f);
                   13792:     {
                   13793:         use integer;
                   13794:         $e=($a+$b);
                   13795:         $f=($c+$d);
                   13796:         if ($_64bit) {
                   13797:             $e=(($e<<32)>>32);
                   13798:             $f=(($f<<32)>>32);
                   13799:         }
                   13800:     }
                   13801:     if (wantarray) {
                   13802: 	return ($e,$f);
                   13803:     } else {
                   13804: 	my $g;
                   13805: 	{
                   13806: 	    use integer;
                   13807: 	    $g=($e+$f);
                   13808: 	    if ($_64bit) {
                   13809: 		$g=(($g<<32)>>32);
                   13810: 	    }
                   13811: 	}
                   13812: 	return $g;
                   13813:     }
                   13814: }
                   13815: 
1.368     albertel 13816: sub latest_rnd_algorithm_id {
1.675     albertel 13817:     return '64bit5';
1.366     albertel 13818: }
1.32      www      13819: 
1.503     albertel 13820: sub get_rand_alg {
                   13821:     my ($courseid)=@_;
1.790     albertel 13822:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13823:     if ($courseid) {
1.620     albertel 13824: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13825:     }
                   13826:     return &latest_rnd_algorithm_id();
                   13827: }
                   13828: 
1.562     albertel 13829: sub validCODE {
                   13830:     my ($CODE)=@_;
                   13831:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13832:     return 0;
                   13833: }
                   13834: 
1.491     albertel 13835: sub getCODE {
1.620     albertel 13836:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13837:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13838: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13839: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13840: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13841:     }
                   13842:     return undef;
                   13843: }
1.1133    foxr     13844: #
                   13845: #  Determines the random seed for a specific context:
                   13846: #
                   13847: # parameters:
                   13848: #   symb      - in course context the symb for the seed.
                   13849: #   course_id - The course id of the form domain_coursenum.
                   13850: #   domain    - Domain for the user.
                   13851: #   course    - Course for the user.
                   13852: #   cenv      - environment of the course.
                   13853: #
                   13854: # NOTE:
                   13855: #   All parameters are picked out of the environment if missing
                   13856: #   or not defined.
                   13857: #   If a symb cannot be determined the current time is used instead.
                   13858: #
                   13859: #  For a given well defined symb, courside, domain, username,
                   13860: #  and course environment, the seed is reproducible.
                   13861: #
1.31      www      13862: sub rndseed {
1.1133    foxr     13863:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13864:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13865:     if (!defined($symb)) {
1.366     albertel 13866: 	unless ($symb=$wsymb) { return time; }
                   13867:     }
1.1146    foxr     13868:     if (!defined $courseid) { 
                   13869: 	$courseid=$wcourseid; 
                   13870:     }
                   13871:     if (!defined $domain) { $domain=$wdomain; }
                   13872:     if (!defined $username) { $username=$wusername }
1.1133    foxr     13873: 
                   13874:     my $which;
                   13875:     if (defined($cenv->{'rndseed'})) {
                   13876: 	$which = $cenv->{'rndseed'};
                   13877:     } else {
                   13878: 	$which =&get_rand_alg($courseid);
                   13879:     }
1.491     albertel 13880:     if (defined(&getCODE())) {
1.675     albertel 13881: 	if ($which eq '64bit5') {
                   13882: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   13883: 	} elsif ($which eq '64bit4') {
1.575     albertel 13884: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   13885: 	} else {
                   13886: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   13887: 	}
1.675     albertel 13888:     } elsif ($which eq '64bit5') {
                   13889: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 13890:     } elsif ($which eq '64bit4') {
                   13891: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 13892:     } elsif ($which eq '64bit3') {
                   13893: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 13894:     } elsif ($which eq '64bit2') {
                   13895: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13896:     } elsif ($which eq '64bit') {
                   13897: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13898:     }
                   13899:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13900: }
                   13901: 
                   13902: sub rndseed_32bit {
                   13903:     my ($symb,$courseid,$domain,$username)=@_;
                   13904:     {
                   13905: 	use integer;
                   13906: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13907: 	my $symbseed=numval($symb) << 22;
                   13908: 	my $namechck=unpack("%32C*",$username) << 17;
                   13909: 	my $nameseed=numval($username) << 12;
                   13910: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13911: 	my $courseseed=unpack("%32C*",$courseid);
                   13912: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13913: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13914: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13915: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13916: 	return $num;
                   13917:     }
                   13918: }
                   13919: 
                   13920: sub rndseed_64bit {
                   13921:     my ($symb,$courseid,$domain,$username)=@_;
                   13922:     {
                   13923: 	use integer;
                   13924: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13925: 	my $symbseed=numval($symb) << 10;
                   13926: 	my $namechck=unpack("%32S*",$username);
                   13927: 	
                   13928: 	my $nameseed=numval($username) << 21;
                   13929: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13930: 	my $courseseed=unpack("%32S*",$courseid);
                   13931: 	
                   13932: 	my $num1=$symbchck+$symbseed+$namechck;
                   13933: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13934: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13935: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13936: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13937: 	return "$num1,$num2";
1.155     albertel 13938:     }
1.366     albertel 13939: }
                   13940: 
1.443     albertel 13941: sub rndseed_64bit2 {
                   13942:     my ($symb,$courseid,$domain,$username)=@_;
                   13943:     {
                   13944: 	use integer;
                   13945: 	# strings need to be an even # of cahracters long, it it is odd the
                   13946:         # last characters gets thrown away
                   13947: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13948: 	my $symbseed=numval($symb) << 10;
                   13949: 	my $namechck=unpack("%32S*",$username.' ');
                   13950: 	
                   13951: 	my $nameseed=numval($username) << 21;
1.501     albertel 13952: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13953: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13954: 	
                   13955: 	my $num1=$symbchck+$symbseed+$namechck;
                   13956: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13957: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13958: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13959: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13960: 	return "$num1,$num2";
                   13961:     }
                   13962: }
                   13963: 
                   13964: sub rndseed_64bit3 {
                   13965:     my ($symb,$courseid,$domain,$username)=@_;
                   13966:     {
                   13967: 	use integer;
                   13968: 	# strings need to be an even # of cahracters long, it it is odd the
                   13969:         # last characters gets thrown away
                   13970: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13971: 	my $symbseed=numval2($symb) << 10;
                   13972: 	my $namechck=unpack("%32S*",$username.' ');
                   13973: 	
                   13974: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13975: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13976: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13977: 	
                   13978: 	my $num1=$symbchck+$symbseed+$namechck;
                   13979: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13980: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13981: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13982: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13983: 	
1.503     albertel 13984: 	return "$num1:$num2";
1.443     albertel 13985:     }
                   13986: }
                   13987: 
1.575     albertel 13988: sub rndseed_64bit4 {
                   13989:     my ($symb,$courseid,$domain,$username)=@_;
                   13990:     {
                   13991: 	use integer;
                   13992: 	# strings need to be an even # of cahracters long, it it is odd the
                   13993:         # last characters gets thrown away
                   13994: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13995: 	my $symbseed=numval3($symb) << 10;
                   13996: 	my $namechck=unpack("%32S*",$username.' ');
                   13997: 	
                   13998: 	my $nameseed=numval3($username) << 21;
                   13999: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   14000: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14001: 	
                   14002: 	my $num1=$symbchck+$symbseed+$namechck;
                   14003: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 14004: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14005: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 14006: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      14007: 	
1.575     albertel 14008: 	return "$num1:$num2";
                   14009:     }
                   14010: }
                   14011: 
1.675     albertel 14012: sub rndseed_64bit5 {
                   14013:     my ($symb,$courseid,$domain,$username)=@_;
                   14014:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   14015:     return "$num1:$num2";
                   14016: }
                   14017: 
1.366     albertel 14018: sub rndseed_CODE_64bit {
                   14019:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 14020:     {
1.366     albertel 14021: 	use integer;
1.443     albertel 14022: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 14023: 	my $symbseed=numval2($symb);
1.491     albertel 14024: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   14025: 	my $CODEseed=numval(&getCODE());
1.443     albertel 14026: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 14027: 	my $num1=$symbseed+$CODEchck;
                   14028: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 14029: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   14030: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 14031: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   14032: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 14033: 	return "$num1:$num2";
1.366     albertel 14034:     }
                   14035: }
                   14036: 
1.575     albertel 14037: sub rndseed_CODE_64bit4 {
                   14038:     my ($symb,$courseid,$domain,$username)=@_;
                   14039:     {
                   14040: 	use integer;
                   14041: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   14042: 	my $symbseed=numval3($symb);
                   14043: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   14044: 	my $CODEseed=numval3(&getCODE());
                   14045: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14046: 	my $num1=$symbseed+$CODEchck;
                   14047: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 14048: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   14049: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 14050: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   14051: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   14052: 	return "$num1:$num2";
                   14053:     }
                   14054: }
                   14055: 
1.675     albertel 14056: sub rndseed_CODE_64bit5 {
                   14057:     my ($symb,$courseid,$domain,$username)=@_;
                   14058:     my $code = &getCODE();
                   14059:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   14060:     return "$num1:$num2";
                   14061: }
                   14062: 
1.366     albertel 14063: sub setup_random_from_rndseed {
                   14064:     my ($rndseed)=@_;
1.503     albertel 14065:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  14066: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   14067:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   14068:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   14069:         } else {
                   14070:             &Math::Random::random_set_seed($num1,$num2);
                   14071:         }
1.366     albertel 14072:     } else {
                   14073: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 14074:     }
1.36      albertel 14075: }
                   14076: 
1.474     albertel 14077: sub latest_receipt_algorithm_id {
1.835     albertel 14078:     return 'receipt3';
1.474     albertel 14079: }
                   14080: 
1.480     www      14081: sub recunique {
                   14082:     my $fucourseid=shift;
                   14083:     my $unique;
1.835     albertel 14084:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   14085: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 14086: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      14087:     } else {
                   14088: 	$unique=$perlvar{'lonReceipt'};
                   14089:     }
                   14090:     return unpack("%32C*",$unique);
                   14091: }
                   14092: 
                   14093: sub recprefix {
                   14094:     my $fucourseid=shift;
                   14095:     my $prefix;
1.835     albertel 14096:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   14097: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 14098: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      14099:     } else {
                   14100: 	$prefix=$perlvar{'lonHostID'};
                   14101:     }
                   14102:     return unpack("%32C*",$prefix);
                   14103: }
                   14104: 
1.76      www      14105: sub ireceipt {
1.474     albertel 14106:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 14107: 
                   14108:     my $return =&recprefix($fucourseid).'-';
                   14109: 
                   14110:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   14111: 	$env{'request.state'} eq 'construct') {
                   14112: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   14113: 	return $return;
                   14114:     }
                   14115: 
1.76      www      14116:     my $cuname=unpack("%32C*",$funame);
                   14117:     my $cudom=unpack("%32C*",$fudom);
                   14118:     my $cucourseid=unpack("%32C*",$fucourseid);
                   14119:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      14120:     my $cunique=&recunique($fucourseid);
1.474     albertel 14121:     my $cpart=unpack("%32S*",$part);
1.835     albertel 14122:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   14123: 
1.790     albertel 14124: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 14125: 			       
                   14126: 	$return.= ($cunique%$cuname+
                   14127: 		   $cunique%$cudom+
                   14128: 		   $cusymb%$cuname+
                   14129: 		   $cusymb%$cudom+
                   14130: 		   $cucourseid%$cuname+
                   14131: 		   $cucourseid%$cudom+
                   14132: 		   $cpart%$cuname+
                   14133: 		   $cpart%$cudom);
                   14134:     } else {
                   14135: 	$return.= ($cunique%$cuname+
                   14136: 		   $cunique%$cudom+
                   14137: 		   $cusymb%$cuname+
                   14138: 		   $cusymb%$cudom+
                   14139: 		   $cucourseid%$cuname+
                   14140: 		   $cucourseid%$cudom);
                   14141:     }
                   14142:     return $return;
1.76      www      14143: }
                   14144: 
                   14145: sub receipt {
1.474     albertel 14146:     my ($part)=@_;
1.790     albertel 14147:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 14148:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      14149: }
1.260     ng       14150: 
1.790     albertel 14151: sub whichuser {
                   14152:     my ($passedsymb)=@_;
                   14153:     my ($symb,$courseid,$domain,$name,$publicuser);
                   14154:     if (defined($env{'form.grade_symb'})) {
                   14155: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   14156: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   14157: 	if (!$allowed &&
                   14158: 	    exists($env{'request.course.sec'}) &&
                   14159: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   14160: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   14161: 			      '/'.$env{'request.course.sec'});
                   14162: 	}
                   14163: 	if ($allowed) {
                   14164: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   14165: 	    $courseid=$tmp_courseid;
                   14166: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   14167: 	    ($name)=&get_env_multiple('form.grade_username');
                   14168: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   14169: 	}
                   14170:     }
                   14171:     if (!$passedsymb) {
                   14172: 	$symb=&symbread();
                   14173:     } else {
                   14174: 	$symb=$passedsymb;
                   14175:     }
                   14176:     $courseid=$env{'request.course.id'};
                   14177:     $domain=$env{'user.domain'};
                   14178:     $name=$env{'user.name'};
                   14179:     if ($name eq 'public' && $domain eq 'public') {
                   14180: 	if (!defined($env{'form.username'})) {
                   14181: 	    $env{'form.username'}.=time.rand(10000000);
                   14182: 	}
                   14183: 	$name.=$env{'form.username'};
                   14184:     }
                   14185:     return ($symb,$courseid,$domain,$name,$publicuser);
                   14186: 
                   14187: }
                   14188: 
1.36      albertel 14189: # ------------------------------------------------------------ Serves up a file
1.472     albertel 14190: # returns either the contents of the file or 
                   14191: # -1 if the file doesn't exist
1.481     raeburn  14192: #
                   14193: # if the target is a file that was uploaded via DOCS, 
                   14194: # a check will be made to see if a current copy exists on the local server,
                   14195: # if it does this will be served, otherwise a copy will be retrieved from
                   14196: # the home server for the course and stored in /home/httpd/html/userfiles on
                   14197: # the local server.   
1.472     albertel 14198: 
1.36      albertel 14199: sub getfile {
1.538     albertel 14200:     my ($file) = @_;
1.609     banghart 14201:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 14202:     &repcopy($file);
                   14203:     return &readfile($file);
                   14204: }
                   14205: 
                   14206: sub repcopy_userfile {
                   14207:     my ($file)=@_;
1.1142    raeburn  14208:     my $londocroot = $perlvar{'lonDocRoot'};
                   14209:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  14210:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 14211:     my ($cdom,$cnum,$filename) = 
1.811     albertel 14212: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 14213:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   14214:     if (-e "$file") {
1.828     www      14215: # we already have a local copy, check it out
1.538     albertel 14216: 	my @fileinfo = stat($file);
1.828     www      14217: 	my $rtncode;
                   14218: 	my $info;
1.538     albertel 14219: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 14220: 	if ($lwpresp ne 'ok') {
1.828     www      14221: # there is no such file anymore, even though we had a local copy
1.482     albertel 14222: 	    if ($rtncode eq '404') {
1.538     albertel 14223: 		unlink($file);
1.482     albertel 14224: 	    }
                   14225: 	    return -1;
                   14226: 	}
                   14227: 	if ($info < $fileinfo[9]) {
1.828     www      14228: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  14229: 	    return 'ok';
1.828     www      14230: 	} else {
                   14231: # the file is outdated, get rid of it
                   14232: 	    unlink($file);
1.482     albertel 14233: 	}
1.828     www      14234:     }
                   14235: # one way or the other, at this point, we don't have the file
                   14236: # construct the correct path for the file
                   14237:     my @parts = ($cdom,$cnum); 
                   14238:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   14239: 	push @parts, split(/\//,$1);
                   14240:     }
                   14241:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   14242:     foreach my $part (@parts) {
                   14243: 	$path .= '/'.$part;
                   14244: 	if (!-e $path) {
                   14245: 	    mkdir($path,0770);
1.482     albertel 14246: 	}
                   14247:     }
1.828     www      14248: # now the path exists for sure
                   14249: # get a user agent
                   14250:     my $ua=new LWP::UserAgent;
                   14251:     my $transferfile=$file.'.in.transfer';
                   14252: # FIXME: this should flock
                   14253:     if (-e $transferfile) { return 'ok'; }
                   14254:     my $request;
                   14255:     $uri=~s/^\///;
1.980     raeburn  14256:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  14257:     my $hostname = &hostname($homeserver);
1.980     raeburn  14258:     my $protocol = $protocol{$homeserver};
                   14259:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  14260:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      14261:     my $response=$ua->request($request,$transferfile);
                   14262: # did it work?
                   14263:     if ($response->is_error()) {
                   14264: 	unlink($transferfile);
                   14265: 	&logthis("Userfile repcopy failed for $uri");
                   14266: 	return -1;
                   14267:     }
                   14268: # worked, rename the transfer file
                   14269:     rename($transferfile,$file);
1.607     raeburn  14270:     return 'ok';
1.481     raeburn  14271: }
                   14272: 
1.517     albertel 14273: sub tokenwrapper {
                   14274:     my $uri=shift;
1.980     raeburn  14275:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 14276:     $uri=~s|^/||;
1.620     albertel 14277:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 14278:     my $token=$1;
1.552     albertel 14279:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   14280:     if ($udom && $uname && $file) {
                   14281: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  14282:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  14283:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.120  raeburn  14284:         my $hostname = &hostname($homeserver);
1.980     raeburn  14285:         my $protocol = $protocol{$homeserver};
                   14286:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  14287:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 14288:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   14289:                                '&tokenissued='.$perlvar{'lonHostID'};
                   14290:     } else {
                   14291:         return '/adm/notfound.html';
                   14292:     }
                   14293: }
                   14294: 
1.828     www      14295: # call with reqtype HEAD: get last modification time
                   14296: # call with reqtype GET: get the file contents
                   14297: # Do not call this with reqtype GET for large files! It loads everything into memory
                   14298: #
1.481     raeburn  14299: sub getuploaded {
                   14300:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   14301:     $uri=~s/^\///;
1.980     raeburn  14302:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  14303:     my $hostname = &hostname($homeserver);
1.980     raeburn  14304:     my $protocol = $protocol{$homeserver};
                   14305:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  14306:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  14307:     my $ua=new LWP::UserAgent;
                   14308:     my $request=new HTTP::Request($reqtype,$uri);
                   14309:     my $response=$ua->request($request);
                   14310:     $$rtncode = $response->code;
1.482     albertel 14311:     if (! $response->is_success()) {
                   14312: 	return 'failed';
                   14313:     }      
                   14314:     if ($reqtype eq 'HEAD') {
1.486     www      14315: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 14316:     } elsif ($reqtype eq 'GET') {
                   14317: 	$$info = $response->content;
1.472     albertel 14318:     }
1.482     albertel 14319:     return 'ok';
1.36      albertel 14320: }
                   14321: 
1.481     raeburn  14322: sub readfile {
                   14323:     my $file = shift;
                   14324:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   14325:     my $fh;
1.1172.2.96  raeburn  14326:     open($fh,"<",$file);
1.481     raeburn  14327:     my $a='';
1.800     albertel 14328:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  14329:     return $a;
                   14330: }
                   14331: 
1.36      albertel 14332: sub filelocation {
1.590     banghart 14333:     my ($dir,$file) = @_;
                   14334:     my $location;
                   14335:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 14336: 
                   14337:     if ($file =~ m-^/adm/-) {
                   14338: 	$file=~s-^/adm/wrapper/-/-;
                   14339: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   14340:     }
1.882     albertel 14341: 
1.1139    www      14342:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  14343:         $location = $file;
1.609     banghart 14344:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 14345:         my ($udom,$uname,$filename)=
1.811     albertel 14346:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 14347:         my $home=&homeserver($uname,$udom);
                   14348:         my $is_me=0;
                   14349:         my @ids=&current_machine_ids();
                   14350:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   14351:         if ($is_me) {
1.1117    foxr     14352:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 14353:         } else {
                   14354:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   14355:   	      $udom.'/'.$uname.'/'.$filename;
                   14356:         }
1.882     albertel 14357:     } elsif ($file =~ m-^/adm/-) {
                   14358: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 14359:     } else {
                   14360:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      14361:         $file=~s:^/(res|priv)/:/:;
                   14362:         my $space=$1;
1.590     banghart 14363:         if ( !( $file =~ m:^/:) ) {
                   14364:             $location = $dir. '/'.$file;
                   14365:         } else {
1.1142    raeburn  14366:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 14367:         }
1.59      albertel 14368:     }
1.590     banghart 14369:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 14370:     while ($location=~m{/\.\./}) {
                   14371: 	if ($location =~ m{/[^/]+/\.\./}) {
                   14372: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   14373: 	} else {
                   14374: 	    $location=~ s{/\.\./}{/}g;
                   14375: 	}
                   14376:     } #remove dir/..
1.590     banghart 14377:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   14378:     return $location;
1.46      www      14379: }
1.36      albertel 14380: 
1.46      www      14381: sub hreflocation {
                   14382:     my ($dir,$file)=@_;
1.980     raeburn  14383:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 14384: 	$file=filelocation($dir,$file);
1.700     albertel 14385:     } elsif ($file=~m-^/adm/-) {
                   14386: 	$file=~s-^/adm/wrapper/-/-;
                   14387: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 14388:     }
                   14389:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   14390: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   14391:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  14392: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   14393: 	        {/uploaded/$1/$2/}x;
1.46      www      14394:     }
1.913     albertel 14395:     if ($file=~ m{^/userfiles/}) {
                   14396: 	$file =~ s{^/userfiles/}{/uploaded/};
                   14397:     }
1.462     albertel 14398:     return $file;
1.465     albertel 14399: }
                   14400: 
1.1139    www      14401: 
                   14402: 
                   14403: 
                   14404: 
1.465     albertel 14405: sub current_machine_domains {
1.853     albertel 14406:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   14407: }
                   14408: 
                   14409: sub machine_domains {
                   14410:     my ($hostname) = @_;
1.465     albertel 14411:     my @domains;
1.838     albertel 14412:     my %hostname = &all_hostnames();
1.465     albertel 14413:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  14414: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 14415: 	if ($hostname eq $name) {
1.844     albertel 14416: 	    push(@domains,&host_domain($id));
1.465     albertel 14417: 	}
                   14418:     }
                   14419:     return @domains;
                   14420: }
                   14421: 
                   14422: sub current_machine_ids {
1.853     albertel 14423:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   14424: }
                   14425: 
                   14426: sub machine_ids {
                   14427:     my ($hostname) = @_;
                   14428:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 14429:     my @ids;
1.888     albertel 14430:     my %name_to_host = &all_names();
1.889     albertel 14431:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   14432: 	return @{ $name_to_host{$hostname} };
                   14433:     }
                   14434:     return;
1.31      www      14435: }
                   14436: 
1.824     raeburn  14437: sub additional_machine_domains {
                   14438:     my @domains;
1.1172.2.142  raeburn  14439:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
                   14440:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
                   14441:             while( my $line = <$fh>) {
                   14442:                 chomp($line);
                   14443:                 $line =~ s/\s//g;
                   14444:                 push(@domains,$line);
                   14445:             }
                   14446:             close($fh);
                   14447:         }
1.824     raeburn  14448:     }
                   14449:     return @domains;
                   14450: }
                   14451: 
                   14452: sub default_login_domain {
                   14453:     my $domain = $perlvar{'lonDefDomain'};
                   14454:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   14455:     foreach my $posdom (&current_machine_domains(),
                   14456:                         &additional_machine_domains()) {
                   14457:         if (lc($posdom) eq lc($testdomain)) {
                   14458:             $domain=$posdom;
                   14459:             last;
                   14460:         }
                   14461:     }
                   14462:     return $domain;
                   14463: }
                   14464: 
1.1172.2.106  raeburn  14465: sub shared_institution {
1.1172.2.136  raeburn  14466:     my ($dom,$lonhost) = @_;
                   14467:     if ($lonhost eq '') {
                   14468:         $lonhost = $perlvar{'lonHostID'};
                   14469:     }
1.1172.2.106  raeburn  14470:     my $same_intdom;
1.1172.2.136  raeburn  14471:     my $hostintdom = &internet_dom($lonhost);
1.1172.2.106  raeburn  14472:     if ($hostintdom ne '') {
                   14473:         my %iphost = &get_iphost();
                   14474:         my $primary_id = &domain($dom,'primary');
                   14475:         my $primary_ip = &get_host_ip($primary_id);
                   14476:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   14477:             foreach my $id (@{$iphost{$primary_ip}}) {
                   14478:                 my $intdom = &internet_dom($id);
                   14479:                 if ($intdom eq $hostintdom) {
                   14480:                     $same_intdom = 1;
                   14481:                     last;
                   14482:                 }
                   14483:             }
                   14484:         }
                   14485:     }
                   14486:     return $same_intdom;
                   14487: }
                   14488: 
1.1172.2.120  raeburn  14489: sub uses_sts {
                   14490:     my ($ignore_cache) = @_;
                   14491:     my $lonhost = $perlvar{'lonHostID'};
                   14492:     my $hostname = &hostname($lonhost);
                   14493:     my $sts_on;
                   14494:     if ($protocol{$lonhost} eq 'https') {
                   14495:         my $cachetime = 12*3600;
                   14496:         if (!$ignore_cache) {
                   14497:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   14498:             if (defined($cached)) {
                   14499:                 return $sts_on;
                   14500:             }
                   14501:         }
1.1172.2.121  raeburn  14502:         my $ua=new LWP::UserAgent;
1.1172.2.120  raeburn  14503:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   14504:         my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121  raeburn  14505:         my $response=$ua->request($request);
1.1172.2.120  raeburn  14506:         if ($response->is_success) {
                   14507:             my $has_sts = $response->header('Strict-Transport-Security');
                   14508:             if ($has_sts eq '') {
                   14509:                 $sts_on = 0;
                   14510:             } else {
                   14511:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   14512:                     my $maxage = $1;
                   14513:                     if ($maxage) {
                   14514:                         $sts_on = 1;
                   14515:                     } else {
                   14516:                         $sts_on = 0;
                   14517:                     }
                   14518:                 } else {
                   14519:                     $sts_on = 0;
                   14520:                 }
                   14521:             }
                   14522:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   14523:         }
                   14524:     }
                   14525:     return;
                   14526: }
                   14527: 
1.1172.2.142  raeburn  14528: sub waf_allssl {
                   14529:     my ($host_name) = @_;
                   14530:     my $alias = &get_proxy_alias();
                   14531:     if ($host_name eq '') {
                   14532:         $host_name = $ENV{'SERVER_NAME'};
                   14533:     }
                   14534:     if (($host_name ne '') && ($alias eq $host_name)) {
                   14535:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   14536:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   14537:         if ($defdomdefaults{'waf_sslopt'}) {
                   14538:             return $defdomdefaults{'waf_sslopt'};
                   14539:         }
                   14540:     }
                   14541:     return;
                   14542: }
                   14543: 
1.1172.2.134  raeburn  14544: sub get_requestor_ip {
                   14545:     my ($r,$nolookup,$noproxy) = @_;
                   14546:     my $from_ip;
                   14547:     if (ref($r)) {
1.1172.2.142  raeburn  14548:         if ($r->can('useragent_ip')) {
                   14549:             if ($noproxy && $r->can('client_ip')) {
                   14550:                 $from_ip = $r->client_ip();
                   14551:             } else {
                   14552:                 $from_ip = $r->useragent_ip();
                   14553:             }
                   14554:         } elsif ($r->connection->can('remote_ip')) {
                   14555:             $from_ip = $r->connection->remote_ip();
                   14556:         } else {
                   14557:             $from_ip = $r->get_remote_host($nolookup);
                   14558:         }
1.1172.2.134  raeburn  14559:     } else {
                   14560:         $from_ip = $ENV{'REMOTE_ADDR'};
                   14561:     }
1.1172.2.142  raeburn  14562:     return $from_ip if ($noproxy);
                   14563:    # Who controls proxy settings for server
                   14564:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14565:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   14566:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
                   14567:         if ($proxyinfo->{'vpnint'}) {
                   14568:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
                   14569:                 return $from_ip;
                   14570:             }
                   14571:         }
                   14572:         if ($proxyinfo->{'trusted'}) {
                   14573:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   14574:                 my $ipheader = $proxyinfo->{'ipheader'};
                   14575:                 my ($ip,$xfor);
                   14576:                 if (ref($r)) {
                   14577:                     if ($ipheader) {
                   14578:                         $ip = $r->headers_in->{$ipheader};
                   14579:                     }
                   14580:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   14581:                 } else {
                   14582:                     if ($ipheader) {
                   14583:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   14584:                     }
                   14585:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   14586:                 }
                   14587:                 if (($ip eq '') && ($xfor ne '')) {
                   14588:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   14589:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   14590:                             $ip = $poss_ip;
                   14591:                             last;
                   14592:                         }
                   14593:                     }
                   14594:                 }
                   14595:                 if ($ip ne '') {
                   14596:                     return $ip;
                   14597:                 }
                   14598:             }
                   14599:         }
                   14600:     }
1.1172.2.134  raeburn  14601:     return $from_ip;
                   14602: }
                   14603: 
1.1172.2.142  raeburn  14604: sub get_proxy_settings {
                   14605:     my ($dom_in_use) = @_;
                   14606:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   14607:     my $proxyinfo = {
                   14608:                        ipheader => $domdefaults{'waf_ipheader'},
                   14609:                        trusted  => $domdefaults{'waf_trusted'},
                   14610:                        vpnint   => $domdefaults{'waf_vpnint'},
                   14611:                        vpnext   => $domdefaults{'waf_vpnext'},
                   14612:                        sslopt   => $domdefaults{'waf_sslopt'},
                   14613:                     };
                   14614:     return $proxyinfo;
                   14615: }
                   14616: 
                   14617: sub ip_match {
                   14618:     my ($ip,$pattern_str) = @_;
                   14619:     $ip=Net::CIDR::cidrvalidate($ip);
                   14620:     if ($ip) {
                   14621:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   14622:     }
                   14623:     return;
                   14624: }
                   14625: 
                   14626: sub get_proxy_alias {
                   14627:     my ($lonid) = @_;
                   14628:     if ($lonid eq '') {
                   14629:         $lonid = $perlvar{'lonHostID'};
                   14630:     }
                   14631:     if (!defined(&hostname($lonid))) {
                   14632:         return;
                   14633:     }
                   14634:     if ($lonid ne '') {
                   14635:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
                   14636:         if ($cached) {
                   14637:             return $alias;
                   14638:         }
                   14639:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14640:         if ($dom ne '') {
                   14641:             my $cachetime = 60*60*24;
                   14642:             my %domconfig =
                   14643:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14644:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14645:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
                   14646:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   14647:                 }
                   14648:             }
                   14649:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   14650:         }
                   14651:     }
                   14652:     return;
                   14653: }
                   14654: 
                   14655: sub use_proxy_alias {
                   14656:     my ($r,$lonid) = @_;
                   14657:     my $alias = &get_proxy_alias($lonid);
                   14658:     if ($alias) {
                   14659:         my $dom = &host_domain($lonid);
                   14660:         if ($dom ne '') {
                   14661:             my $proxyinfo = &get_proxy_settings($dom);
                   14662:             my ($vpnint,$remote_ip);
                   14663:             if (ref($proxyinfo) eq 'HASH') {
                   14664:                 $vpnint = $proxyinfo->{'vpnint'};
                   14665:                 if ($vpnint) {
                   14666:                     $remote_ip = &get_requestor_ip($r,1,1);
                   14667:                 }
                   14668:             }
                   14669:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   14670:                 return $alias;
                   14671:             }
                   14672:         }
                   14673:     }
                   14674:     return;
                   14675: }
                   14676: 
                   14677: sub alias_sso {
                   14678:     my ($lonid) = @_;
                   14679:     if ($lonid eq '') {
                   14680:         $lonid = $perlvar{'lonHostID'};
                   14681:     }
                   14682:     if (!defined(&hostname($lonid))) {
                   14683:         return;
                   14684:     }
                   14685:     if ($lonid ne '') {
                   14686:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
                   14687:         if ($cached) {
                   14688:             return $use_alias;
                   14689:         }
                   14690:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14691:         if ($dom ne '') {
                   14692:             my $cachetime = 60*60*24;
                   14693:             my %domconfig =
                   14694:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14695:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14696:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
                   14697:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
                   14698:                 }
                   14699:             }
                   14700:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
                   14701:         }
                   14702:     }
                   14703:     return;
                   14704: }
                   14705: 
                   14706: sub get_saml_landing {
                   14707:     my ($lonid) = @_;
                   14708:     if ($lonid eq '') {
                   14709:         my $defdom = &default_login_domain();
                   14710:         my @hosts = &current_machine_ids();
                   14711:         if (@hosts > 1) {
                   14712:             foreach my $hostid (@hosts) {
                   14713:                 if (&host_domain($hostid) eq $defdom) {
                   14714:                     $lonid = $hostid;
                   14715:                     last;
                   14716:                 }
                   14717:             }
                   14718:         } else {
                   14719:             $lonid = $perlvar{'lonHostID'};
                   14720:         }
                   14721:         if ($lonid) {
                   14722:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
                   14723:                 return;
                   14724:             }
                   14725:         } else {
                   14726:             return;
                   14727:         }
                   14728:     } elsif (!defined(&hostname($lonid))) {
                   14729:         return;
                   14730:     }
                   14731:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   14732:     if ($cached) {
                   14733:         return $landing;
                   14734:     }
                   14735:     my $dom = &Apache::lonnet::host_domain($lonid);
                   14736:     if ($dom ne '') {
                   14737:         my $cachetime = 60*60*24;
                   14738:         my %domconfig =
                   14739:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
                   14740:         if (ref($domconfig{'login'}) eq 'HASH') {
                   14741:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   14742:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   14743:                     $landing = 1;
                   14744:                 }
                   14745:             }
                   14746:         }
                   14747:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   14748:     }
                   14749:     return;
                   14750: }
                   14751: 
1.31      www      14752: # ------------------------------------------------------------- Declutters URLs
                   14753: 
                   14754: sub declutter {
                   14755:     my $thisfn=shift;
1.569     albertel 14756:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  14757:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   14758:         $thisfn=~s{^/home/httpd/html}{};
                   14759:     }
1.31      www      14760:     $thisfn=~s/^\///;
1.697     albertel 14761:     $thisfn=~s|^adm/wrapper/||;
                   14762:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      14763:     $thisfn=~s/^res\///;
1.1172    bisitz   14764:     $thisfn=~s/^priv\///;
1.1032    raeburn  14765:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   14766:         $thisfn=~s/\?.+$//;
                   14767:     }
1.268     www      14768:     return $thisfn;
                   14769: }
                   14770: 
                   14771: # ------------------------------------------------------------- Clutter up URLs
                   14772: 
                   14773: sub clutter {
                   14774:     my $thisfn='/'.&declutter(shift);
1.887     albertel 14775:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 14776: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      14777:        $thisfn='/res'.$thisfn; 
                   14778:     }
1.1031    raeburn  14779:     if ($thisfn !~m|^/adm|) {
                   14780: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 14781: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 14782: 	} else {
                   14783: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   14784: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 14785: 	    if ($embstyle eq 'ssi'
                   14786: 		|| ($embstyle eq 'hdn')
                   14787: 		|| ($embstyle eq 'rat')
                   14788: 		|| ($embstyle eq 'prv')
                   14789: 		|| ($embstyle eq 'ign')) {
                   14790: 		#do nothing with these
                   14791: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 14792: 		|| ($embstyle eq 'emb')
                   14793: 		|| ($embstyle eq 'wrp')) {
                   14794: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 14795: 	    } elsif ($embstyle eq 'unk'
                   14796: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 14797: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 14798: 	    } else {
1.718     www      14799: #		&logthis("Got a blank emb style");
1.695     albertel 14800: 	    }
1.694     albertel 14801: 	}
1.1172.2.146.  .1(raebu 14802:22):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   14803:22):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 14804:     }
1.31      www      14805:     return $thisfn;
1.12      www      14806: }
                   14807: 
1.787     albertel 14808: sub clutter_with_no_wrapper {
                   14809:     my $uri = &clutter(shift);
                   14810:     if ($uri =~ m-^/adm/-) {
                   14811: 	$uri =~ s-^/adm/wrapper/-/-;
                   14812: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14813:     }
                   14814:     return $uri;
                   14815: }
                   14816: 
1.557     albertel 14817: sub freeze_escape {
                   14818:     my ($value)=@_;
                   14819:     if (ref($value)) {
                   14820: 	$value=&nfreeze($value);
                   14821: 	return '__FROZEN__'.&escape($value);
                   14822:     }
                   14823:     return &escape($value);
                   14824: }
                   14825: 
1.11      www      14826: 
1.557     albertel 14827: sub thaw_unescape {
                   14828:     my ($value)=@_;
                   14829:     if ($value =~ /^__FROZEN__/) {
                   14830: 	substr($value,0,10,undef);
                   14831: 	$value=&unescape($value);
                   14832: 	return &thaw($value);
                   14833:     }
                   14834:     return &unescape($value);
                   14835: }
                   14836: 
1.436     albertel 14837: sub correct_line_ends {
                   14838:     my ($result)=@_;
                   14839:     $$result =~s/\r\n/\n/mg;
                   14840:     $$result =~s/\r/\n/mg;
1.415     albertel 14841: }
1.1       albertel 14842: # ================================================================ Main Program
                   14843: 
1.184     www      14844: sub goodbye {
1.204     albertel 14845:    &logthis("Starting Shut down");
1.443     albertel 14846: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14847:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14848: #converted
1.599     albertel 14849: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14850:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14851: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   14852: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 14853: #1.1 only
1.870     albertel 14854: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   14855: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   14856: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   14857: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   14858:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 14859:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   14860:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      14861:    &flushcourselogs();
                   14862:    &logthis("Shutting down");
                   14863: }
                   14864: 
1.852     albertel 14865: sub get_dns {
1.1172.2.17  raeburn  14866:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 14867:     if (!$ignore_cache) {
                   14868: 	my ($content,$cached)=
                   14869: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   14870: 	if ($cached) {
1.1172.2.17  raeburn  14871: 	    &$func($content,$hashref);
1.869     albertel 14872: 	    return;
                   14873: 	}
                   14874:     }
                   14875: 
                   14876:     my %alldns;
1.1172.2.96  raeburn  14877:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   14878:         foreach my $dns (<$config>) {
                   14879: 	    next if ($dns !~ /^\^(\S*)/x);
                   14880:             my $line = $1;
                   14881:             my ($host,$protocol) = split(/:/,$line);
                   14882:             if ($protocol ne 'https') {
                   14883:                 $protocol = 'http';
                   14884:             }
                   14885: 	    $alldns{$host} = $protocol;
1.979     raeburn  14886:         }
1.1172.2.96  raeburn  14887:         close($config);
1.869     albertel 14888:     }
                   14889:     while (%alldns) {
1.1172.2.52  raeburn  14890: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142  raeburn  14891:         my @content;
                   14892:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   14893:             my $command = (split('/',$url))[3];
                   14894:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   14895:             delete($alldns{$dns});
                   14896:             next if (($dir eq '') || ($file eq ''));
                   14897:             if (open(my $config,'<',"$dir/$file")) {
                   14898:                 @content = <$config>;
                   14899:                 close($config);
                   14900:             }
                   14901:         } else {
                   14902: 	    my $ua=new LWP::UserAgent;
                   14903:             $ua->timeout(30);
                   14904: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   14905: 	    my $response=$ua->request($request);
                   14906:             delete($alldns{$dns});
                   14907: 	    next if ($response->is_error());
                   14908: 	    @content = split("\n",$response->content);
                   14909:         }
1.1172.2.17  raeburn  14910:         unless ($nocache) {
1.1172.2.23  raeburn  14911: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  14912:         }
                   14913: 	&$func(\@content,$hashref);
1.869     albertel 14914: 	return;
1.852     albertel 14915:     }
1.871     albertel 14916:     my $which = (split('/',$url))[3];
                   14917:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  14918:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   14919:         my @content = <$config>;
                   14920:         &$func(\@content,$hashref);
                   14921:     }
1.1172.2.17  raeburn  14922:     return;
                   14923: }
                   14924: 
                   14925: # ------------------------------------------------------Get DNS checksums file
                   14926: sub parse_dns_checksums_tab {
                   14927:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  14928:     my $lonhost = $perlvar{'lonHostID'};
                   14929:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  14930:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  14931:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14932:     my $webconfdir = '/etc/httpd/conf';
                   14933:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14934:         $webconfdir = '/etc/apache2';
                   14935:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14936:         if ($1 >= 10) {
                   14937:             $webconfdir = '/etc/apache2';
                   14938:         }
                   14939:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14940:         if ($1 >= 10.0) {
                   14941:             $webconfdir = '/etc/apache2';
                   14942:         }
                   14943:     }
1.1172.2.17  raeburn  14944:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14945:     my (%chksum,%revnum);
                   14946:     if (ref($lines) eq 'ARRAY') {
                   14947:         chomp(@{$lines});
1.1172.2.34  raeburn  14948:         my $version = shift(@{$lines});
                   14949:         if ($version eq $release) {
1.1172.2.17  raeburn  14950:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  14951:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  14952:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14953:                     if ($webconfdir eq '/etc/apache2') {
                   14954:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14955:                     }
                   14956:                 }
1.1172.2.34  raeburn  14957:                 $chksum{$file} = $shasum;
                   14958:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  14959:             }
                   14960:             if (ref($hashref) eq 'HASH') {
                   14961:                 %{$hashref} = (
                   14962:                                 sums     => \%chksum,
                   14963:                                 versions => \%revnum,
                   14964:                               );
                   14965:             }
                   14966:         }
                   14967:     }
1.869     albertel 14968:     return;
1.852     albertel 14969: }
1.1172.2.17  raeburn  14970: 
                   14971: sub fetch_dns_checksums {
                   14972:     my %checksums;
1.1172.2.34  raeburn  14973:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  14974:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  14975:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14976:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  14977:              \%checksums);
                   14978:     return \%checksums;
                   14979: }
                   14980: 
1.1172.2.142  raeburn  14981: sub parse_getdns_url {
                   14982:     my ($command,$url) = @_;
                   14983:     my $dir = $perlvar{'lonTabDir'};
                   14984:     my $file;
                   14985:     if ($command eq 'hosts') {
                   14986:         $file = 'dns_hosts.tab';
                   14987:     } elsif ($command eq 'domain') {
                   14988:         $file = 'dns_domain.tab';
                   14989:     } elsif ($command eq 'checksums') {
                   14990:         my $version = (split('/',$url))[4];
                   14991:         $file = "dns_checksums/$version.tab",
                   14992:     }
                   14993:     return ($dir,$file);
                   14994: }
                   14995: 
1.327     albertel 14996: # ------------------------------------------------------------ Read domain file
                   14997: {
1.852     albertel 14998:     my $loaded;
1.846     albertel 14999:     my %domain;
                   15000: 
1.852     albertel 15001:     sub parse_domain_tab {
                   15002: 	my ($lines) = @_;
                   15003: 	foreach my $line (@$lines) {
                   15004: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      15005: 
1.846     albertel 15006: 	    chomp($line);
1.852     albertel 15007: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 15008: 	    my %this_domain;
                   15009: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   15010: 			       'lang_def', 'city', 'longi', 'lati',
                   15011: 			       'primary') {
                   15012: 		$this_domain{$field} = shift(@elements);
                   15013: 	    }
                   15014: 	    $domain{$name} = \%this_domain;
1.852     albertel 15015: 	}
                   15016:     }
1.864     albertel 15017: 
                   15018:     sub reset_domain_info {
                   15019: 	undef($loaded);
                   15020: 	undef(%domain);
                   15021:     }
                   15022: 
1.852     albertel 15023:     sub load_domain_tab {
1.1172.2.70  raeburn  15024: 	my ($ignore_cache,$nocache) = @_;
                   15025: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 15026: 	my $fh;
1.1172.2.96  raeburn  15027: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 15028: 	    my @lines = <$fh>;
                   15029: 	    &parse_domain_tab(\@lines);
1.448     albertel 15030: 	}
1.852     albertel 15031: 	close($fh);
                   15032: 	$loaded = 1;
1.327     albertel 15033:     }
1.846     albertel 15034: 
                   15035:     sub domain {
1.852     albertel 15036: 	&load_domain_tab() if (!$loaded);
                   15037: 
1.846     albertel 15038: 	my ($name,$what) = @_;
                   15039: 	return if ( !exists($domain{$name}) );
                   15040: 
                   15041: 	if (!$what) {
                   15042: 	    return $domain{$name}{'description'};
                   15043: 	}
                   15044: 	return $domain{$name}{$what};
                   15045:     }
1.974     raeburn  15046: 
                   15047:     sub domain_info {
                   15048:         &load_domain_tab() if (!$loaded);
                   15049:         return %domain;
                   15050:     }
                   15051: 
1.327     albertel 15052: }
                   15053: 
                   15054: 
1.1       albertel 15055: # ------------------------------------------------------------- Read hosts file
                   15056: {
1.838     albertel 15057:     my %hostname;
1.844     albertel 15058:     my %hostdom;
1.845     albertel 15059:     my %libserv;
1.852     albertel 15060:     my $loaded;
1.888     albertel 15061:     my %name_to_host;
1.1074    raeburn  15062:     my %internetdom;
1.1107    raeburn  15063:     my %LC_dns_serv;
1.852     albertel 15064: 
                   15065:     sub parse_hosts_tab {
                   15066: 	my ($file) = @_;
                   15067: 	foreach my $configline (@$file) {
                   15068: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  15069:             chomp($configline);
                   15070: 	    if ($configline =~ /^\^/) {
                   15071:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   15072:                     $LC_dns_serv{$1} = 1;
                   15073:                 }
                   15074:                 next;
                   15075:             }
1.1074    raeburn  15076: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 15077: 	    $name=~s/\s//g;
                   15078: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  15079:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   15080:                     my $curr = $hostname{$id};
                   15081:                     my $skip;
                   15082:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   15083:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   15084:                             $skip = 1;
                   15085:                         } else {
                   15086:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   15087:                         }
                   15088:                     }
                   15089:                     unless ($skip) {
                   15090:                         push(@{$name_to_host{$name}},$id);
                   15091:                     }
                   15092:                 } else {
                   15093:                     push(@{$name_to_host{$name}},$id);
                   15094:                 }
1.852     albertel 15095: 		$hostname{$id}=$name;
                   15096: 		$hostdom{$id}=$domain;
                   15097: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  15098:                 if (defined($protocol)) {
                   15099:                     if ($protocol eq 'https') {
                   15100:                         $protocol{$id} = $protocol;
                   15101:                     } else {
                   15102:                         $protocol{$id} = 'http'; 
                   15103:                     }
1.968     raeburn  15104:                 } else {
1.969     raeburn  15105:                     $protocol{$id} = 'http';
1.968     raeburn  15106:                 }
1.1074    raeburn  15107:                 if (defined($intdom)) {
                   15108:                     $internetdom{$id} = $intdom;
                   15109:                 }
1.852     albertel 15110: 	    }
                   15111: 	}
                   15112:     }
1.864     albertel 15113:     
                   15114:     sub reset_hosts_info {
1.897     albertel 15115: 	&purge_remembered();
1.864     albertel 15116: 	&reset_domain_info();
                   15117: 	&reset_hosts_ip_info();
1.892     albertel 15118: 	undef(%name_to_host);
1.864     albertel 15119: 	undef(%hostname);
                   15120: 	undef(%hostdom);
                   15121: 	undef(%libserv);
                   15122: 	undef($loaded);
                   15123:     }
1.1       albertel 15124: 
1.852     albertel 15125:     sub load_hosts_tab {
1.1172.2.70  raeburn  15126: 	my ($ignore_cache,$nocache) = @_;
                   15127: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  15128: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 15129: 	my @config = <$config>;
                   15130: 	&parse_hosts_tab(\@config);
                   15131: 	close($config);
                   15132: 	$loaded=1;
1.1       albertel 15133:     }
1.852     albertel 15134: 
1.838     albertel 15135:     sub hostname {
1.852     albertel 15136: 	&load_hosts_tab() if (!$loaded);
                   15137: 
1.838     albertel 15138: 	my ($lonid) = @_;
                   15139: 	return $hostname{$lonid};
                   15140:     }
1.845     albertel 15141: 
1.838     albertel 15142:     sub all_hostnames {
1.852     albertel 15143: 	&load_hosts_tab() if (!$loaded);
                   15144: 
1.838     albertel 15145: 	return %hostname;
                   15146:     }
1.845     albertel 15147: 
1.888     albertel 15148:     sub all_names {
1.1172.2.70  raeburn  15149:         my ($ignore_cache,$nocache) = @_;
                   15150: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 15151: 
                   15152: 	return %name_to_host;
                   15153:     }
                   15154: 
1.974     raeburn  15155:     sub all_host_domain {
                   15156:         &load_hosts_tab() if (!$loaded);
                   15157:         return %hostdom;
                   15158:     }
                   15159: 
1.845     albertel 15160:     sub is_library {
1.852     albertel 15161: 	&load_hosts_tab() if (!$loaded);
                   15162: 
1.845     albertel 15163: 	return exists($libserv{$_[0]});
                   15164:     }
                   15165: 
                   15166:     sub all_library {
1.852     albertel 15167: 	&load_hosts_tab() if (!$loaded);
                   15168: 
1.845     albertel 15169: 	return %libserv;
                   15170:     }
                   15171: 
1.1062    droeschl 15172:     sub unique_library {
                   15173: 	#2x reverse removes all hostnames that appear more than once
                   15174:         my %unique = reverse &all_library();
                   15175:         return reverse %unique;
                   15176:     }
                   15177: 
1.841     albertel 15178:     sub get_servers {
1.852     albertel 15179: 	&load_hosts_tab() if (!$loaded);
                   15180: 
1.841     albertel 15181: 	my ($domain,$type) = @_;
                   15182: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   15183: 	                                          : %hostname;
                   15184: 	my %result;
1.842     albertel 15185: 	if (ref($domain) eq 'ARRAY') {
                   15186: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 15187: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 15188: 		    $result{$host} = $hostname;
                   15189: 		}
                   15190: 	    }
                   15191: 	} else {
                   15192: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   15193: 		if ($hostdom{$host} eq $domain) {
                   15194: 		    $result{$host} = $hostname;
                   15195: 		}
1.841     albertel 15196: 	    }
                   15197: 	}
                   15198: 	return %result;
                   15199:     }
1.845     albertel 15200: 
1.1062    droeschl 15201:     sub get_unique_servers {
                   15202:         my %unique = reverse &get_servers(@_);
                   15203: 	return reverse %unique;
                   15204:     }
                   15205: 
1.844     albertel 15206:     sub host_domain {
1.852     albertel 15207: 	&load_hosts_tab() if (!$loaded);
                   15208: 
1.844     albertel 15209: 	my ($lonid) = @_;
                   15210: 	return $hostdom{$lonid};
                   15211:     }
                   15212: 
1.841     albertel 15213:     sub all_domains {
1.852     albertel 15214: 	&load_hosts_tab() if (!$loaded);
                   15215: 
1.841     albertel 15216: 	my %seen;
                   15217: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   15218: 	return @uniq;
                   15219:     }
1.1074    raeburn  15220: 
                   15221:     sub internet_dom {
                   15222:         &load_hosts_tab() if (!$loaded);
                   15223: 
                   15224:         my ($lonid) = @_;
                   15225:         return $internetdom{$lonid};
                   15226:     }
1.1107    raeburn  15227: 
                   15228:     sub is_LC_dns {
                   15229:         &load_hosts_tab() if (!$loaded);
                   15230: 
                   15231:         my ($hostname) = @_;
                   15232:         return exists($LC_dns_serv{$hostname});
                   15233:     }
                   15234: 
1.1       albertel 15235: }
                   15236: 
1.847     albertel 15237: { 
                   15238:     my %iphost;
1.856     albertel 15239:     my %name_to_ip;
                   15240:     my %lonid_to_ip;
1.869     albertel 15241: 
1.847     albertel 15242:     sub get_hosts_from_ip {
                   15243: 	my ($ip) = @_;
                   15244: 	my %iphosts = &get_iphost();
                   15245: 	if (ref($iphosts{$ip})) {
                   15246: 	    return @{$iphosts{$ip}};
                   15247: 	}
                   15248: 	return;
1.839     albertel 15249:     }
1.864     albertel 15250:     
                   15251:     sub reset_hosts_ip_info {
                   15252: 	undef(%iphost);
                   15253: 	undef(%name_to_ip);
                   15254: 	undef(%lonid_to_ip);
                   15255:     }
1.856     albertel 15256: 
                   15257:     sub get_host_ip {
                   15258: 	my ($lonid) = @_;
                   15259: 	if (exists($lonid_to_ip{$lonid})) {
                   15260: 	    return $lonid_to_ip{$lonid};
                   15261: 	}
                   15262: 	my $name=&hostname($lonid);
                   15263:    	my $ip = gethostbyname($name);
                   15264: 	return if (!$ip || length($ip) ne 4);
                   15265: 	$ip=inet_ntoa($ip);
                   15266: 	$name_to_ip{$name}   = $ip;
                   15267: 	$lonid_to_ip{$lonid} = $ip;
                   15268: 	return $ip;
                   15269:     }
1.847     albertel 15270:     
                   15271:     sub get_iphost {
1.1172.2.70  raeburn  15272: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 15273: 
1.869     albertel 15274: 	if (!$ignore_cache) {
                   15275: 	    if (%iphost) {
                   15276: 		return %iphost;
                   15277: 	    }
                   15278: 	    my ($ip_info,$cached)=
                   15279: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   15280: 	    if ($cached) {
                   15281: 		%iphost      = %{$ip_info->[0]};
                   15282: 		%name_to_ip  = %{$ip_info->[1]};
                   15283: 		%lonid_to_ip = %{$ip_info->[2]};
                   15284: 		return %iphost;
                   15285: 	    }
                   15286: 	}
1.894     albertel 15287: 
                   15288: 	# get yesterday's info for fallback
                   15289: 	my %old_name_to_ip;
                   15290: 	my ($ip_info,$cached)=
                   15291: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   15292: 	if ($cached) {
                   15293: 	    %old_name_to_ip = %{$ip_info->[1]};
                   15294: 	}
                   15295: 
1.1172.2.70  raeburn  15296: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 15297: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 15298: 	    my $ip;
                   15299: 	    if (!exists($name_to_ip{$name})) {
                   15300: 		$ip = gethostbyname($name);
                   15301: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 15302: 		    if (defined($old_name_to_ip{$name})) {
                   15303: 			$ip = $old_name_to_ip{$name};
                   15304: 			&logthis("Can't find $name defaulting to old $ip");
                   15305: 		    } else {
                   15306: 			&logthis("Name $name no IP found");
                   15307: 			next;
                   15308: 		    }
                   15309: 		} else {
                   15310: 		    $ip=inet_ntoa($ip);
1.847     albertel 15311: 		}
                   15312: 		$name_to_ip{$name} = $ip;
                   15313: 	    } else {
                   15314: 		$ip = $name_to_ip{$name};
1.653     albertel 15315: 	    }
1.888     albertel 15316: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   15317: 		$lonid_to_ip{$id} = $ip;
                   15318: 	    }
                   15319: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 15320: 	}
1.1172.2.70  raeburn  15321:         unless ($nocache) {
                   15322: 	    &do_cache_new('iphost','iphost',
                   15323: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   15324: 		          48*60*60);
                   15325:         }
1.869     albertel 15326: 
1.847     albertel 15327: 	return %iphost;
1.598     albertel 15328:     }
                   15329: 
1.992     raeburn  15330:     #
                   15331:     #  Given a DNS returns the loncapa host name for that DNS 
                   15332:     # 
                   15333:     sub host_from_dns {
                   15334:         my ($dns) = @_;
                   15335:         my @hosts;
                   15336:         my $ip;
                   15337: 
1.993     raeburn  15338:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  15339:             $ip = $name_to_ip{$dns};
                   15340:         }
                   15341:         if (!$ip) {
                   15342:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   15343:             if (length($ip) == 4) { 
                   15344: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   15345:             }
                   15346:         }
                   15347:         if ($ip) {
                   15348: 	    @hosts = get_hosts_from_ip($ip);
                   15349: 	    return $hosts[0];
                   15350:         }
                   15351:         return undef;
1.986     foxr     15352:     }
1.992     raeburn  15353: 
1.1074    raeburn  15354:     sub get_internet_names {
                   15355:         my ($lonid) = @_;
                   15356:         return if ($lonid eq '');
                   15357:         my ($idnref,$cached)=
                   15358:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   15359:         if ($cached) {
                   15360:             return $idnref;
                   15361:         }
                   15362:         my $ip = &get_host_ip($lonid);
                   15363:         my @hosts = &get_hosts_from_ip($ip);
                   15364:         my %iphost = &get_iphost();
                   15365:         my (@idns,%seen);
                   15366:         foreach my $id (@hosts) {
                   15367:             my $dom = &host_domain($id);
                   15368:             my $prim_id = &domain($dom,'primary');
                   15369:             my $prim_ip = &get_host_ip($prim_id);
                   15370:             next if ($seen{$prim_ip});
                   15371:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   15372:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   15373:                     my $intdom = &internet_dom($id);
                   15374:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   15375:                         push(@idns,$intdom);
                   15376:                     }
                   15377:                 }
                   15378:             }
                   15379:             $seen{$prim_ip} = 1;
                   15380:         }
1.1172.2.23  raeburn  15381:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  15382:     }
                   15383: 
1.986     foxr     15384: }
                   15385: 
1.1079    raeburn  15386: sub all_loncaparevs {
1.1172.2.39  raeburn  15387:     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  15388: }
                   15389: 
1.1172.2.27  raeburn  15390: # ------------------------------------------------------- Read loncaparev table
                   15391: {
                   15392:     sub load_loncaparevs {
                   15393:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  15394:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  15395:                 while (my $configline=<$config>) {
                   15396:                     chomp($configline);
                   15397:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   15398:                     $loncaparevs{$hostid}=$loncaparev;
                   15399:                 }
                   15400:                 close($config);
                   15401:             }
                   15402:         }
                   15403:     }
                   15404: }
                   15405: 
                   15406: # ----------------------------------------------------- Read serverhostID table
                   15407: {
                   15408:     sub load_serverhomeIDs {
                   15409:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  15410:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  15411:                 while (my $configline=<$config>) {
                   15412:                     chomp($configline);
                   15413:                     my ($name,$id)=split(/:/,$configline);
                   15414:                     $serverhomeIDs{$name}=$id;
                   15415:                 }
                   15416:                 close($config);
                   15417:             }
                   15418:         }
                   15419:     }
                   15420: }
                   15421: 
                   15422: 
1.862     albertel 15423: BEGIN {
                   15424: 
                   15425: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   15426:     unless ($readit) {
                   15427: {
                   15428:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   15429:     %perlvar = (%perlvar,%{$configvars});
                   15430: }
                   15431: 
                   15432: 
1.1       albertel 15433: # ------------------------------------------------------ Read spare server file
                   15434: {
1.1172.2.96  raeburn  15435:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 15436: 
                   15437:     while (my $configline=<$config>) {
                   15438:        chomp($configline);
1.284     matthew  15439:        if ($configline) {
1.784     albertel 15440: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 15441: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 15442: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 15443:        }
                   15444:     }
1.448     albertel 15445:     close($config);
1.1       albertel 15446: }
1.11      www      15447: # ------------------------------------------------------------ Read permissions
                   15448: {
1.1172.2.96  raeburn  15449:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      15450: 
                   15451:     while (my $configline=<$config>) {
1.448     albertel 15452: 	chomp($configline);
                   15453: 	if ($configline) {
                   15454: 	    my ($role,$perm)=split(/ /,$configline);
                   15455: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   15456: 	}
1.11      www      15457:     }
1.448     albertel 15458:     close($config);
1.11      www      15459: }
                   15460: 
                   15461: # -------------------------------------------- Read plain texts for permissions
                   15462: {
1.1172.2.96  raeburn  15463:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      15464: 
                   15465:     while (my $configline=<$config>) {
1.448     albertel 15466: 	chomp($configline);
                   15467: 	if ($configline) {
1.742     raeburn  15468: 	    my ($short,@plain)=split(/:/,$configline);
                   15469:             %{$prp{$short}} = ();
                   15470: 	    if (@plain > 0) {
                   15471:                 $prp{$short}{'std'} = $plain[0];
                   15472:                 for (my $i=1; $i<@plain; $i++) {
                   15473:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   15474:                 }
                   15475:             }
1.448     albertel 15476: 	}
1.135     www      15477:     }
1.448     albertel 15478:     close($config);
1.135     www      15479: }
                   15480: 
                   15481: # ---------------------------------------------------------- Read package table
                   15482: {
1.1172.2.96  raeburn  15483:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      15484: 
                   15485:     while (my $configline=<$config>) {
1.483     albertel 15486: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 15487: 	chomp($configline);
                   15488: 	my ($short,$plain)=split(/:/,$configline);
                   15489: 	my ($pack,$name)=split(/\&/,$short);
                   15490: 	if ($plain ne '') {
                   15491: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   15492: 	    $packagetab{$short}=$plain; 
                   15493: 	}
1.11      www      15494:     }
1.448     albertel 15495:     close($config);
1.329     matthew  15496: }
                   15497: 
1.1172.2.27  raeburn  15498: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  15499: 
1.1172.2.27  raeburn  15500: &load_loncaparevs();
                   15501: 
                   15502: # ------------------------------------------------------- Read serverhostID table
                   15503: 
                   15504: &load_serverhomeIDs();
1.1074    raeburn  15505: 
1.1172.2.27  raeburn  15506: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  15507: {
                   15508:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   15509:     if (-e $file) {
                   15510:         my $parser = HTML::LCParser->new($file);
                   15511:         while (my $token = $parser->get_token()) {
                   15512:             if ($token->[0] eq 'S') {
                   15513:                 my $item = $token->[1];
                   15514:                 my $name = $token->[2]{'name'};
                   15515:                 my $value = $token->[2]{'value'};
                   15516:                 if ($item ne '' && $name ne '' && $value ne '') {
                   15517:                     my $release = $parser->get_text();
                   15518:                     $release =~ s/(^\s*|\s*$ )//gx;
                   15519:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   15520:                 }
                   15521:             }
                   15522:         }
                   15523:     }
1.1073    raeburn  15524: }
                   15525: 
1.1138    raeburn  15526: # ---------------------------------------------------------- Read managers table
                   15527: {
                   15528:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  15529:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  15530:             while (my $configline=<$config>) {
                   15531:                 chomp($configline);
                   15532:                 next if ($configline =~ /^\#/);
                   15533:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   15534:                     $managerstab{$configline} = 1;
                   15535:                 }
                   15536:             }
                   15537:             close($config);
                   15538:         }
                   15539:     }
                   15540: }
                   15541: 
1.329     matthew  15542: # ------------- set up temporary directory
                   15543: {
1.1117    foxr     15544:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  15545: 
1.11      www      15546: }
                   15547: 
1.1172.2.104  raeburn  15548: # ------------- set default texengine (domain default overrides this)
                   15549: {
                   15550:     $deftex = LONCAPA::texengine();
                   15551: }
                   15552: 
1.1172.2.114  raeburn  15553: # ------------- set default minimum length for passwords for internal auth users
                   15554: {
                   15555:     $passwdmin = LONCAPA::passwd_min();
                   15556: }
                   15557: 
1.794     albertel 15558: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   15559: 				'compress_threshold'=> 20_000,
                   15560:  			        });
1.185     www      15561: 
1.281     www      15562: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      15563: $dumpcount=0;
1.958     www      15564: $locknum=0;
1.22      www      15565: 
1.163     harris41 15566: &logtouch();
1.672     albertel 15567: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      15568: $readit=1;
1.564     albertel 15569:     {
                   15570: 	use integer;
                   15571: 	my $test=(2**32)+1;
1.568     albertel 15572: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 15573: 	&logthis(" Detected 64bit platform ($_64bit)");
                   15574:     }
1.195     www      15575: }
1.1       albertel 15576: }
1.179     www      15577: 
1.1       albertel 15578: 1;
1.191     harris41 15579: __END__
                   15580: 
1.243     albertel 15581: =pod
                   15582: 
1.191     harris41 15583: =head1 NAME
                   15584: 
1.243     albertel 15585: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 15586: 
                   15587: =head1 SYNOPSIS
                   15588: 
1.243     albertel 15589: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 15590: 
                   15591:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   15592: 
1.243     albertel 15593: Common parameters:
                   15594: 
                   15595: =over 4
                   15596: 
                   15597: =item *
                   15598: 
                   15599: $uname : an internal username (if $cname expecting a course Id specifically)
                   15600: 
                   15601: =item *
                   15602: 
                   15603: $udom : a domain (if $cdom expecting a course's domain specifically)
                   15604: 
                   15605: =item *
                   15606: 
                   15607: $symb : a resource instance identifier
                   15608: 
                   15609: =item *
                   15610: 
                   15611: $namespace : the name of a .db file that contains the data needed or
                   15612: being set.
                   15613: 
                   15614: =back
                   15615: 
1.394     bowersj2 15616: =head1 OVERVIEW
1.191     harris41 15617: 
1.394     bowersj2 15618: lonnet provides subroutines which interact with the
                   15619: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   15620: about classes, users, and resources.
1.243     albertel 15621: 
                   15622: For many of these objects you can also use this to store data about
                   15623: them or modify them in various ways.
1.191     harris41 15624: 
1.394     bowersj2 15625: =head2 Symbs
1.191     harris41 15626: 
1.394     bowersj2 15627: To identify a specific instance of a resource, LON-CAPA uses symbols
                   15628: or "symbs"X<symb>. These identifiers are built from the URL of the
                   15629: map, the resource number of the resource in the map, and the URL of
                   15630: the resource itself. The latter is somewhat redundant, but might help
                   15631: if maps change.
                   15632: 
                   15633: An example is
                   15634: 
                   15635:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   15636: 
                   15637: The respective map entry is
                   15638: 
                   15639:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   15640:   title="Problem 2">
                   15641:  </resource>
                   15642: 
                   15643: Symbs are used by the random number generator, as well as to store and
                   15644: restore data specific to a certain instance of for example a problem.
                   15645: 
                   15646: =head2 Storing And Retrieving Data
                   15647: 
                   15648: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   15649: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   15650: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   15651: is is the non-critical message twin of cstore. These functions are for
                   15652: handlers to store a perl hash to a user's permanent data space in an
                   15653: easy manner, and to retrieve it again on another call. It is expected
                   15654: that a handler would use this once at the beginning to retrieve data,
                   15655: and then again once at the end to send only the new data back.
                   15656: 
                   15657: The data is stored in the user's data directory on the user's
                   15658: homeserver under the ID of the course.
                   15659: 
                   15660: The hash that is returned by restore will have all of the previous
                   15661: value for all of the elements of the hash.
                   15662: 
                   15663: Example:
                   15664: 
                   15665:  #creating a hash
                   15666:  my %hash;
                   15667:  $hash{'foo'}='bar';
                   15668: 
                   15669:  #storing it
                   15670:  &Apache::lonnet::cstore(\%hash);
                   15671: 
                   15672:  #changing a value
                   15673:  $hash{'foo'}='notbar';
                   15674: 
                   15675:  #adding a new value
                   15676:  $hash{'bar'}='foo';
                   15677:  &Apache::lonnet::cstore(\%hash);
                   15678: 
                   15679:  #retrieving the hash
                   15680:  my %history=&Apache::lonnet::restore();
                   15681: 
                   15682:  #print the hash
                   15683:  foreach my $key (sort(keys(%history))) {
                   15684:    print("\%history{$key} = $history{$key}");
                   15685:  }
                   15686: 
                   15687: Will print out:
1.191     harris41 15688: 
1.394     bowersj2 15689:  %history{1:foo} = bar
                   15690:  %history{1:keys} = foo:timestamp
                   15691:  %history{1:timestamp} = 990455579
                   15692:  %history{2:bar} = foo
                   15693:  %history{2:foo} = notbar
                   15694:  %history{2:keys} = foo:bar:timestamp
                   15695:  %history{2:timestamp} = 990455580
                   15696:  %history{bar} = foo
                   15697:  %history{foo} = notbar
                   15698:  %history{timestamp} = 990455580
                   15699:  %history{version} = 2
                   15700: 
                   15701: Note that the special hash entries C<keys>, C<version> and
                   15702: C<timestamp> were added to the hash. C<version> will be equal to the
                   15703: total number of versions of the data that have been stored. The
                   15704: C<timestamp> attribute will be the UNIX time the hash was
                   15705: stored. C<keys> is available in every historical section to list which
                   15706: keys were added or changed at a specific historical revision of a
                   15707: hash.
                   15708: 
                   15709: B<Warning>: do not store the hash that restore returns directly. This
                   15710: will cause a mess since it will restore the historical keys as if the
                   15711: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 15712: 
1.394     bowersj2 15713: Calling convention:
1.191     harris41 15714: 
1.1172.2.27  raeburn  15715:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  15716:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 15717: 
1.394     bowersj2 15718: For more detailed information, see lonnet specific documentation.
1.191     harris41 15719: 
1.394     bowersj2 15720: =head1 RETURN MESSAGES
1.191     harris41 15721: 
1.394     bowersj2 15722: =over 4
1.191     harris41 15723: 
1.394     bowersj2 15724: =item * B<con_lost>: unable to contact remote host
1.191     harris41 15725: 
1.394     bowersj2 15726: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   15727: when the connection is brought back up
1.191     harris41 15728: 
1.394     bowersj2 15729: =item * B<con_failed>: unable to contact remote host and unable to save message
                   15730: for later delivery
1.191     harris41 15731: 
1.967     bisitz   15732: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 15733: 
1.394     bowersj2 15734: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 15735: that was requested
1.191     harris41 15736: 
1.243     albertel 15737: =back
1.191     harris41 15738: 
1.243     albertel 15739: =head1 PUBLIC SUBROUTINES
1.191     harris41 15740: 
1.243     albertel 15741: =head2 Session Environment Functions
1.191     harris41 15742: 
1.243     albertel 15743: =over 4
1.191     harris41 15744: 
1.394     bowersj2 15745: =item * 
                   15746: X<appenv()>
1.949     raeburn  15747: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 15748: the user envirnoment file, and will be restored for each access this
1.620     albertel 15749: user makes during this session, also modifies the %env for the current
1.949     raeburn  15750: process. Optional rolesarrayref - if defined contains a reference to an array
                   15751: of roles which are exempt from the restriction on modifying user.role entries 
                   15752: in the user's environment.db and in %env.    
1.191     harris41 15753: 
                   15754: =item *
1.394     bowersj2 15755: X<delenv()>
1.987     raeburn  15756: B<delenv($delthis,$regexp)>: removes all items from the session
                   15757: environment file that begin with $delthis. If the 
                   15758: optional second arg - $regexp - is true, $delthis is treated as a 
                   15759: regular expression, otherwise \Q$delthis\E is used. 
                   15760: The values are also deleted from the current processes %env.
1.191     harris41 15761: 
1.795     albertel 15762: =item * get_env_multiple($name) 
                   15763: 
                   15764: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   15765: values may be defined and end up as an array ref.
                   15766: 
                   15767: returns an array of values
                   15768: 
1.243     albertel 15769: =back
                   15770: 
                   15771: =head2 User Information
1.191     harris41 15772: 
1.243     albertel 15773: =over 4
1.191     harris41 15774: 
                   15775: =item *
1.394     bowersj2 15776: X<queryauthenticate()>
                   15777: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 15778: authentication scheme
                   15779: 
                   15780: =item *
1.394     bowersj2 15781: X<authenticate()>
1.1073    raeburn  15782: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 15783: authenticate user from domain's lib servers (first use the current
                   15784: one). C<$upass> should be the users password.
1.1073    raeburn  15785: $checkdefauth is optional (value is 1 if a check should be made to
                   15786:    authenticate user using default authentication method, and allow
                   15787:    account creation if username does not have account in the domain).
                   15788: $clientcancheckhost is optional (value is 1 if checking whether the
                   15789:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 15790: 
                   15791: =item *
1.394     bowersj2 15792: X<homeserver()>
                   15793: B<homeserver($uname,$udom)>: find the server which has
                   15794: the user's directory and files (there must be only one), this caches
                   15795: the answer, and also caches if there is a borken connection.
1.191     harris41 15796: 
                   15797: =item *
1.394     bowersj2 15798: X<idget()>
                   15799: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   15800: (IDs are a unique resource in a domain, there must be only 1 ID per
                   15801: username, and only 1 username per ID in a specific domain) (returns
                   15802: hash: id=>name,id=>name)
1.191     harris41 15803: 
                   15804: =item *
1.394     bowersj2 15805: X<idrget()>
                   15806: B<idrget($udom,@unames)>: find the IDs behind a list of
                   15807: usernames (returns hash: name=>id,name=>id)
1.191     harris41 15808: 
                   15809: =item *
1.394     bowersj2 15810: X<idput()>
                   15811: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 15812: 
                   15813: =item *
1.394     bowersj2 15814: X<rolesinit()>
1.1169    droeschl 15815: B<rolesinit($udom,$username)>: get user privileges.
                   15816: returns user role, first access and timer interval hashes
1.243     albertel 15817: 
                   15818: =item *
1.1171    droeschl 15819: X<privileged()>
                   15820: B<privileged($username,$domain)>: returns a true if user has a
                   15821: privileged and active role (i.e. su or dc), false otherwise.
                   15822: 
                   15823: =item *
1.551     albertel 15824: X<getsection()>
                   15825: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 15826: course $cname, return section name/number or '' for "not in course"
                   15827: and '-1' for "no section"
                   15828: 
                   15829: =item *
1.394     bowersj2 15830: X<userenvironment()>
                   15831: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 15832: passed in @what from the requested user's environment, returns a hash
                   15833: 
1.858     raeburn  15834: =item * 
                   15835: X<userlog_query()>
1.859     albertel 15836: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   15837: activity.log file. %filters defines filters applied when parsing the
                   15838: log file. These can be start or end timestamps, or the type of action
                   15839: - log to look for Login or Logout events, check for Checkin or
                   15840: Checkout, role for role selection. The response is in the form
                   15841: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   15842: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  15843: 
1.243     albertel 15844: =back
                   15845: 
                   15846: =head2 User Roles
                   15847: 
                   15848: =over 4
                   15849: 
                   15850: =item *
                   15851: 
1.1172.2.65  raeburn  15852: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   15853: returns codes for allowed actions.
                   15854: 
                   15855: The first argument is required, all others are optional.
                   15856: 
                   15857: $priv is the privilege being checked.
                   15858: $uri contains additional information about what is being checked for access (e.g.,
                   15859: URL, course ID etc.).
                   15860: $symb is the unique resource instance identifier in a course; if needed,
                   15861: but not provided, it will be retrieved via a call to &symbread().
                   15862: $role is the role for which a priv is being checked (only used if priv is evb).
                   15863: $clientip is the user's IP address (only used when checking for access to portfolio
                   15864: files).
                   15865: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   15866: prevents recursive calls to &allowed.
                   15867: 
1.243     albertel 15868:  F: full access
                   15869:  U,I,K: authentication modes (cxx only)
                   15870:  '': forbidden
                   15871:  1: user needs to choose course
                   15872:  2: browse allowed
1.766     albertel 15873:  A: passphrase authentication needed
1.1172.2.65  raeburn  15874:  B: access temporarily blocked because of a blocking event in a course.
1.1172.2.146.  .1(raebu 15875:22):  D: access blocked because access is required via session initiated via deep-link
1.243     albertel 15876: 
                   15877: =item *
                   15878: 
1.1172.2.13  raeburn  15879: constructaccess($url,$setpriv) : check for access to construction space URL
                   15880: 
                   15881: See if the owner domain and name in the URL match those in the
                   15882: expected environment.  If so, return three element list
                   15883: ($ownername,$ownerdomain,$ownerhome).
                   15884: 
                   15885: Otherwise return the null string.
                   15886: 
                   15887: If second argument 'setpriv' is true, it assigns the privileges,
                   15888: and returns the same three element list, unless the owner has
                   15889: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   15890: in which case the null string is returned.
                   15891: 
                   15892: =item *
                   15893: 
1.1172.2.84  raeburn  15894: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   15895: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   15896: for system, domain, and course level. $uname and $udom are optional (current
                   15897: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 15898: 
                   15899: =item *
                   15900: 
1.988     raeburn  15901: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   15902: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  15903: $type is Course (default) or Community.
1.988     raeburn  15904: If $forcedefault evaluates to true, text returned will be default 
                   15905: text for $type. Otherwise, if this is a course, the text returned 
                   15906: will be a custom name for the role (if defined in the course's 
                   15907: environment).  If no custom name is defined the default is returned.
                   15908:    
1.832     raeburn  15909: =item *
                   15910: 
1.1172.2.23  raeburn  15911: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  15912: All arguments are optional. Returns a hash of a roles, either for
                   15913: co-author/assistant author roles for a user's Construction Space
1.906     albertel 15914: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  15915: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   15916: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   15917: For each key, value is set to colon-separated start and end times for
                   15918: the role.  If no username and domain are specified, will default to
1.934     raeburn  15919: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  15920: of role statuses (active, future or previous), roles 
                   15921: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   15922: to restrict the list of roles reported. If no array ref is 
                   15923: provided for types, will default to return only active roles.
1.834     albertel 15924: 
1.1172.2.13  raeburn  15925: =item *
                   15926: 
                   15927: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   15928: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   15929: 
                   15930: Additional optional arguments are: $type (if role checking is to be restricted
                   15931: to certain user status types -- previous (expired roles), active (currently
                   15932: available roles) or future (roles available in the future), and
                   15933: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  15934: have active Domain Coordinator role in course's domain or in additional
                   15935: domains (specified in 'Domains to check for privileged users' in course
                   15936: environment -- set via:  Course Settings -> Classlists and staff listing).
                   15937: 
                   15938: =item *
                   15939: 
                   15940: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   15941: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   15942: $possdomains and $possroles are optional array refs -- to domains to check and
                   15943: roles to check.  If $possdomains is not specified, a dump will be done of the
                   15944: users' roles.db to check for a dc or su role in any domain. This can be
                   15945: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   15946: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   15947: this then allows &privileged_by_domain() to be used, which caches the identity
                   15948: of privileged users, eliminating the need for repeated calls to &dump().
                   15949: 
                   15950: =item *
                   15951: 
                   15952: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15953: where the outer hash keys are domains specified in the $possdomains array ref,
                   15954: next inner hash keys are privileged roles specified in the $roles array ref,
                   15955: and the innermost hash contains key = value pairs for username:domain = end:start
                   15956: for active or future "privileged" users with that role in that domain. To avoid
                   15957: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15958: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  15959: 
1.243     albertel 15960: =back
                   15961: 
                   15962: =head2 User Modification
                   15963: 
                   15964: =over 4
                   15965: 
                   15966: =item *
                   15967: 
1.957     raeburn  15968: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15969: user for the level given by URL.  Optional start and end dates (leave empty
                   15970: string or zero for "no date")
1.191     harris41 15971: 
                   15972: =item *
                   15973: 
1.243     albertel 15974: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15975: change a users, password, possible return values are: ok,
                   15976: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15977: refused
1.191     harris41 15978: 
                   15979: =item *
                   15980: 
1.243     albertel 15981: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15982: 
                   15983: =item *
                   15984: 
1.1058    raeburn  15985: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   15986:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   15987: 
                   15988: will update user information (firstname,middlename,lastname,generation,
                   15989: permanentemail), and if forceid is true, student/employee ID also.
                   15990: A user's institutional affiliation(s) can also be updated.
                   15991: User information fields will not be overwritten with empty entries 
                   15992: unless the field is included in the $candelete array reference.
                   15993: This array is included when a single user is modified via "Manage Users",
                   15994: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 15995: 
                   15996: =item *
                   15997: 
1.286     matthew  15998: modifystudent
                   15999: 
1.957     raeburn  16000: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  16001: The course id is resolved based on the current user's environment.  
                   16002: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  16003: associated with a course.
                   16004: 
1.297     matthew  16005: This call is essentially a wrapper for lonnet::modifyuser and
                   16006: lonnet::modify_student_enrollment
1.286     matthew  16007: 
                   16008: Inputs: 
                   16009: 
                   16010: =over 4
                   16011: 
1.957     raeburn  16012: =item B<$udom> Student's loncapa domain
1.286     matthew  16013: 
1.957     raeburn  16014: =item B<$uname> Student's loncapa login name
1.286     matthew  16015: 
1.964     bisitz   16016: =item B<$uid> Student/Employee ID
1.286     matthew  16017: 
1.957     raeburn  16018: =item B<$umode> Student's authentication mode
1.286     matthew  16019: 
1.957     raeburn  16020: =item B<$upass> Student's password
1.286     matthew  16021: 
1.957     raeburn  16022: =item B<$first> Student's first name
1.286     matthew  16023: 
1.957     raeburn  16024: =item B<$middle> Student's middle name
1.286     matthew  16025: 
1.957     raeburn  16026: =item B<$last> Student's last name
1.286     matthew  16027: 
1.957     raeburn  16028: =item B<$gene> Student's generation
1.286     matthew  16029: 
1.957     raeburn  16030: =item B<$usec> Student's section in course
1.286     matthew  16031: 
                   16032: =item B<$end> Unix time of the roles expiration
                   16033: 
                   16034: =item B<$start> Unix time of the roles start date
                   16035: 
                   16036: =item B<$forceid> If defined, allow $uid to be changed
                   16037: 
                   16038: =item B<$desiredhome> server to use as home server for student
                   16039: 
1.957     raeburn  16040: =item B<$email> Student's permanent e-mail address
                   16041: 
                   16042: =item B<$type> Type of enrollment (auto or manual)
                   16043: 
1.963     raeburn  16044: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   16045: 
                   16046: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  16047: 
1.963     raeburn  16048: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  16049: 
1.963     raeburn  16050: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  16051: 
1.1172.2.19  raeburn  16052: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   16053: 
                   16054: =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  16055: 
1.286     matthew  16056: =back
1.297     matthew  16057: 
                   16058: =item *
                   16059: 
                   16060: modify_student_enrollment
                   16061: 
1.1172.2.31  raeburn  16062: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  16063: 'role.request.course' must be defined for this function to proceed.
                   16064: 
                   16065: Inputs:
                   16066: 
                   16067: =over 4
                   16068: 
1.1172.2.31  raeburn  16069: =item $udom, student's domain
1.297     matthew  16070: 
1.1172.2.31  raeburn  16071: =item $uname, student's name
1.297     matthew  16072: 
1.1172.2.31  raeburn  16073: =item $uid, student's user id
1.297     matthew  16074: 
1.1172.2.31  raeburn  16075: =item $first, student's first name
1.297     matthew  16076: 
                   16077: =item $middle
                   16078: 
                   16079: =item $last
                   16080: 
                   16081: =item $gene
                   16082: 
                   16083: =item $usec
                   16084: 
                   16085: =item $end
                   16086: 
                   16087: =item $start
                   16088: 
1.957     raeburn  16089: =item $type
                   16090: 
                   16091: =item $locktype
                   16092: 
                   16093: =item $cid
                   16094: 
                   16095: =item $selfenroll
                   16096: 
                   16097: =item $context
                   16098: 
1.1172.2.19  raeburn  16099: =item $credits, number of credits student will earn from this class
                   16100: 
1.1172.2.76  raeburn  16101: =item $instsec, institutional course section code for student
                   16102: 
1.297     matthew  16103: =back
                   16104: 
1.191     harris41 16105: 
                   16106: =item *
                   16107: 
1.243     albertel 16108: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   16109: custom role; give a custom role to a user for the level given by URL.  Specify
                   16110: name and domain of role author, and role name
1.191     harris41 16111: 
                   16112: =item *
                   16113: 
1.243     albertel 16114: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 16115: 
                   16116: =item *
                   16117: 
1.243     albertel 16118: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   16119: 
                   16120: =back
                   16121: 
                   16122: =head2 Course Infomation
                   16123: 
                   16124: =over 4
1.191     harris41 16125: 
                   16126: =item *
                   16127: 
1.1118    foxr     16128: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 16129: specified course id, including all environment settings for the
                   16130: course, the description of the course will be in the hash under the
                   16131: key 'description'
1.191     harris41 16132: 
1.1118    foxr     16133: $options is an optional parameter that if supplied is a hash reference that controls
                   16134: what how this function works.  It has the following key/values:
                   16135: 
                   16136: =over 4
                   16137: 
                   16138: =item freshen_cache
                   16139: 
                   16140: If defined, and the environment cache for the course is valid, it is 
                   16141: returned in the returned hash.
                   16142: 
                   16143: =item one_time
                   16144: 
                   16145: If defined, the last cache time is set to _now_
                   16146: 
                   16147: =item user
                   16148: 
                   16149: If defined, the supplied username is used instead of the current user.
                   16150: 
                   16151: 
                   16152: =back
                   16153: 
1.191     harris41 16154: =item *
                   16155: 
1.624     albertel 16156: resdata($name,$domain,$type,@which) : request for current parameter
                   16157: setting for a specific $type, where $type is either 'course' or 'user',
                   16158: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  16159: answers for 10 minutes.
1.243     albertel 16160: 
1.877     foxr     16161: =item *
                   16162: 
                   16163: get_courseresdata($courseid, $domain) : dump the entire course resource
                   16164: data base, returning a hash that is keyed by the resource name and has
                   16165: values that are the resource value.  I believe that the timestamps and
                   16166: versions are also returned.
                   16167: 
1.243     albertel 16168: =back
                   16169: 
                   16170: =head2 Course Modification
                   16171: 
                   16172: =over 4
1.191     harris41 16173: 
                   16174: =item *
                   16175: 
1.243     albertel 16176: writecoursepref($courseid,%prefs) : write preferences (environment
                   16177: database) for a course
1.191     harris41 16178: 
                   16179: =item *
                   16180: 
1.1011    raeburn  16181: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   16182: 
                   16183: =item *
                   16184: 
1.1038    raeburn  16185: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 16186: 
1.1167    droeschl 16187: =item *
                   16188: 
                   16189: is_course($courseid), is_course($cdom, $cnum)
                   16190: 
                   16191: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   16192: two component version $cdom, $cnum. It checks if the specified course exists.
                   16193: 
                   16194: Returns:
                   16195:     undef if the course doesn't exist, otherwise
                   16196:     in scalar context the combined courseid.
                   16197:     in list context the two components of the course identifier, domain and 
                   16198:     courseid.    
                   16199: 
1.243     albertel 16200: =back
                   16201: 
1.1172.2.109  raeburn  16202: =head2 Bubblesheet Configuration
                   16203: 
                   16204: =over 4
                   16205: 
                   16206: =item *
                   16207: 
                   16208: get_scantron_config($which)
                   16209: 
                   16210: $which - the name of the configuration to parse from the file.
                   16211: 
                   16212: Parses and returns the bubblesheet configuration line selected as a
                   16213: hash of configuration file fields.
                   16214: 
                   16215: 
                   16216: Returns:
                   16217:     If the named configuration is not in the file, an empty
                   16218:     hash is returned.
                   16219: 
                   16220:     a hash with the fields
                   16221:       name         - internal name for the this configuration setup
                   16222:       description  - text to display to operator that describes this config
                   16223:       CODElocation - if 0 or the string 'none'
                   16224:                           - no CODE exists for this config
                   16225:                      if -1 || the string 'letter'
                   16226:                           - a CODE exists for this config and is
                   16227:                             a string of letters
                   16228:                      Unsupported value (but planned for future support)
                   16229:                           if a positive integer
                   16230:                                - The CODE exists as the first n items from
                   16231:                                  the question section of the form
                   16232:                           if the string 'number'
                   16233:                                - The CODE exists for this config and is
                   16234:                                  a string of numbers
                   16235:       CODEstart   - (only matter if a CODE exists) column in the line where
                   16236:                      the CODE starts
                   16237:       CODElength  - length of the CODE
                   16238:       IDstart     - column where the student/employee ID starts
                   16239:       IDlength    - length of the student/employee ID info
                   16240:       Qstart      - column where the information from the bubbled
                   16241:                     'questions' start
                   16242:       Qlength     - number of columns comprising a single bubble line from
                   16243:                     the sheet. (usually either 1 or 10)
                   16244:       Qon         - either a single character representing the character used
                   16245:                     to signal a bubble was chosen in the positional setup, or
                   16246:                     the string 'letter' if the letter of the chosen bubble is
                   16247:                     in the final, or 'number' if a number representing the
                   16248:                     chosen bubble is in the file (1->A 0->J)
                   16249:       Qoff        - the character used to represent that a bubble was
                   16250:                     left blank
                   16251:       PaperID     - if the scanning process generates a unique number for each
                   16252:                     sheet scanned the column that this ID number starts in
                   16253:       PaperIDlength - number of columns that comprise the unique ID number
                   16254:                       for the sheet of paper
                   16255:       FirstName   - column that the first name starts in
                   16256:       FirstNameLength - number of columns that the first name spans
                   16257:       LastName    - column that the last name starts in
                   16258:       LastNameLength - number of columns that the last name spans
                   16259:       BubblesPerRow - number of bubbles available in each row used to
                   16260:                       bubble an answer. (If not specified, 10 assumed).
                   16261: 
                   16262: 
                   16263: =item *
                   16264: 
                   16265: get_scantronformat_file($cdom)
                   16266: 
                   16267: $cdom - the course's domain (optional); if not supplied, uses
                   16268: domain for current $env{'request.course.id'}.
                   16269: 
                   16270: Returns an array containing lines from the scantron format file for
                   16271: the domain of the course.
                   16272: 
                   16273: If a url for a custom.tab file is listed in domain's configuration.db,
                   16274: lines are from this file.
                   16275: 
                   16276: Otherwise, if a default.tab has been published in RES space by the
                   16277: domainconfig user, lines are from this file.
                   16278: 
                   16279: Otherwise, fall back to getting lines from the legacy file on the
                   16280: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   16281: 
                   16282: =back
                   16283: 
1.243     albertel 16284: =head2 Resource Subroutines
                   16285: 
                   16286: =over 4
1.191     harris41 16287: 
                   16288: =item *
                   16289: 
1.243     albertel 16290: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 16291: 
                   16292: =item *
                   16293: 
1.243     albertel 16294: repcopy($filename) : subscribes to the requested file, and attempts to
                   16295: replicate from the owning library server, Might return
1.607     raeburn  16296: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   16297: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 16298: resource. Expects the local filesystem pathname
                   16299: (/home/httpd/html/res/....)
                   16300: 
                   16301: =back
                   16302: 
                   16303: =head2 Resource Information
                   16304: 
                   16305: =over 4
1.191     harris41 16306: 
                   16307: =item *
                   16308: 
1.1172.2.28  raeburn  16309: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   16310: and returns the value of a variety of different possible values,
                   16311: $varname should be a request string, and the other parameters can be
                   16312: used to specify who and what one is asking about. Ordinarily, $cid 
                   16313: does not need to be specified, as it is retrived from 
                   16314: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   16315: within lonuserstate::loadmap() when initializing a course, before
                   16316: $env{'request.course.id'} has been set, so it needs to be provided
                   16317: in that one case.
1.243     albertel 16318: 
                   16319: Possible values for $varname are environment.lastname (or other item
                   16320: from the envirnment hash), user.name (or someother aspect about the
                   16321: user), resource.0.maxtries (or some other part and parameter of a
                   16322: resource)
1.204     albertel 16323: 
                   16324: =item *
                   16325: 
1.243     albertel 16326: directcondval($number) : get current value of a condition; reads from a state
                   16327: string
1.204     albertel 16328: 
                   16329: =item *
                   16330: 
1.243     albertel 16331: condval($condidx) : value of condition index based on state
1.204     albertel 16332: 
                   16333: =item *
                   16334: 
1.1172.2.146.  .13(raeb 16335:-23): metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 16336: resource's metadata, $what should be either a specific key, or either
                   16337: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1172.2.146.  .13(raeb 16338:-23): packages that this resource currently uses, the last 3 arguments are
                   16339:-23): only used internally for recursive metadata.
                   16340:-23): 
                   16341:-23): the toolsymb is only used where the uri is for an external tool (for which
                   16342:-23): the uri as well as the symb are guaranteed to be unique).
1.243     albertel 16343: 
                   16344: this function automatically caches all requests
1.191     harris41 16345: 
                   16346: =item *
                   16347: 
1.243     albertel 16348: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   16349: network of library servers; returns file handle of where SQL and regex results
                   16350: will be stored for query
1.191     harris41 16351: 
                   16352: =item *
                   16353: 
1.1172.2.66  raeburn  16354: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   16355: return symbolic list entry (all arguments optional).
                   16356: 
                   16357: Args: filename is the filename (including path) for the file for which a symb
                   16358: is required; donotrecurse, if true will prevent calls to allowed() being made
                   16359: to check access status if more than one resource was found in the bighash
                   16360: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   16361: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   16362: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   16363: cause possible symbs to be checked to determine if they are subject to content
                   16364: blocking, if so they will not be included as possible symbs; possibles is a
                   16365: ref to a hash, which, as a side effect, will be populated with all possible
                   16366: symbs (content blocking not tested).
                   16367: 
1.243     albertel 16368: returns the data handle
1.191     harris41 16369: 
                   16370: =item *
                   16371: 
1.1172.2.17  raeburn  16372: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  16373: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 16374: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  16375: on failure, user must be in a course, as it assumes the existence of
                   16376: the course initial hash, and uses $env('request.course.id'}.  The third
                   16377: arg is an optional reference to a scalar.  If this arg is passed in the
                   16378: call to symbverify, it will be set to 1 if the symb has been set to be 
                   16379: encrypted; otherwise it will be null.
1.243     albertel 16380: 
1.191     harris41 16381: =item *
                   16382: 
1.243     albertel 16383: symbclean($symb) : removes versions numbers from a symb, returns the
                   16384: cleaned symb
1.191     harris41 16385: 
                   16386: =item *
                   16387: 
1.243     albertel 16388: is_on_map($uri) : checks if the $uri is somewhere on the current
                   16389: course map, user must be in a course for it to work.
1.191     harris41 16390: 
                   16391: =item *
                   16392: 
1.243     albertel 16393: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 16394: 
                   16395: =item *
                   16396: 
1.243     albertel 16397: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   16398: a random seed, all arguments are optional, if they aren't sent it uses the
                   16399: environment to derive them. Note: if symb isn't sent and it can't get one
                   16400: from &symbread it will use the current time as its return value
1.191     harris41 16401: 
                   16402: =item *
                   16403: 
1.243     albertel 16404: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   16405: unfakeable, receipt
1.191     harris41 16406: 
                   16407: =item *
                   16408: 
1.620     albertel 16409: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 16410: 
                   16411: =item *
                   16412: 
1.243     albertel 16413: countacc($url) : count the number of accesses to a given URL
1.191     harris41 16414: 
                   16415: =item *
                   16416: 
1.243     albertel 16417: 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 16418: 
                   16419: =item *
                   16420: 
1.243     albertel 16421: 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 16422: 
                   16423: =item *
                   16424: 
1.243     albertel 16425: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 16426: 
                   16427: =item *
                   16428: 
1.243     albertel 16429: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   16430: forcing spreadsheet to reevaluate the resource scores next time.
                   16431: 
1.1172.2.13  raeburn  16432: =item *
                   16433: 
                   16434: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   16435: when viewing in course context.
                   16436: 
                   16437:  input: six args -- filename (decluttered), course number, course domain,
                   16438:                     url, symb (if registered) and group (if this is a
                   16439:                     group item -- e.g., bulletin board, group page etc.).
                   16440: 
                   16441:  output: array of five scalars --
                   16442:          $cfile -- url for file editing if editable on current server
                   16443:          $home -- homeserver of resource (i.e., for author if published,
                   16444:                                           or course if uploaded.).
                   16445:          $switchserver --  1 if server switch will be needed.
                   16446:          $forceedit -- 1 if icon/link should be to go to edit mode
                   16447:          $forceview -- 1 if icon/link should be to go to view mode
                   16448: 
                   16449: =item *
                   16450: 
                   16451: is_course_upload($file,$cnum,$cdom)
                   16452: 
                   16453: Used in course context to determine if current file was uploaded to
                   16454: the course (i.e., would be found in /userfiles/docs on the course's
                   16455: homeserver.
                   16456: 
                   16457:   input: 3 args -- filename (decluttered), course number and course domain.
                   16458:   output: boolean -- 1 if file was uploaded.
                   16459: 
1.243     albertel 16460: =back
                   16461: 
                   16462: =head2 Storing/Retreiving Data
                   16463: 
                   16464: =over 4
1.191     harris41 16465: 
                   16466: =item *
                   16467: 
1.1172.2.64  raeburn  16468: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   16469: permanently for this url; hashref needs to be given and should be a \%hashname;
                   16470: the remaining args aren't required and if they aren't passed or are '' they will
                   16471: be derived from the env (with the exception of $laststore, which is an
                   16472: optional arg used when a user's submission is stored in grading).
                   16473: $laststore is $version=$timestamp, where $version is the most recent version
                   16474: number retrieved for the corresponding $symb in the $namespace db file, and
                   16475: $timestamp is the timestamp for that transaction (UNIX time).
                   16476: $laststore is currently only passed when cstore() is called by
                   16477: structuretags::finalize_storage().
1.191     harris41 16478: 
                   16479: =item *
                   16480: 
1.1172.2.64  raeburn  16481: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   16482: but uses critical subroutine
1.191     harris41 16483: 
                   16484: =item *
                   16485: 
1.243     albertel 16486: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   16487: all args are optional
1.191     harris41 16488: 
                   16489: =item *
                   16490: 
1.717     albertel 16491: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   16492: dumps the complete (or key matching regexp) namespace into a hash
                   16493: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   16494: normally &store()ed into
                   16495: 
                   16496: $range should be either an integer '100' (give me the first 100
                   16497:                                            matching records)
                   16498:               or be  two integers sperated by a - with no spaces
                   16499:                  '30-50' (give me the 30th through the 50th matching
                   16500:                           records)
                   16501: 
                   16502: 
                   16503: =item *
                   16504: 
1.1172.2.59  raeburn  16505: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 16506: replaces a &store() version of data with a replacement set of data
                   16507: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  16508: reference. If $tolog is true, the transaction is logged in the courselog
                   16509: with an action=PUTSTORE.
1.717     albertel 16510: 
                   16511: =item *
                   16512: 
1.243     albertel 16513: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   16514: works very similar to store/cstore, but all data is stored in a
                   16515: temporary location and can be reset using tmpreset, $storehash should
                   16516: be a hash reference, returns nothing on success
1.191     harris41 16517: 
                   16518: =item *
                   16519: 
1.243     albertel 16520: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   16521: similar to restore, but all data is stored in a temporary location and
                   16522: can be reset using tmpreset. Returns a hash of values on success,
                   16523: error string otherwise.
1.191     harris41 16524: 
                   16525: =item *
                   16526: 
1.243     albertel 16527: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   16528: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 16529: 
                   16530: =item *
                   16531: 
1.243     albertel 16532: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16533: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 16534: 
                   16535: =item *
                   16536: 
1.243     albertel 16537: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   16538: namesp ($udom and $uname are optional)
1.191     harris41 16539: 
                   16540: =item *
                   16541: 
1.702     albertel 16542: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 16543: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 16544: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  16545: 
1.702     albertel 16546: $range should be either an integer '100' (give me the first 100
                   16547:                                            matching records)
                   16548:               or be  two integers sperated by a - with no spaces
                   16549:                  '30-50' (give me the 30th through the 50th matching
                   16550:                           records)
1.449     matthew  16551: =item *
                   16552: 
                   16553: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   16554: $store can be a scalar, an array reference, or if the amount to be 
                   16555: incremented is > 1, a hash reference.
                   16556: 
                   16557: ($udom and $uname are optional)
1.191     harris41 16558: 
                   16559: =item *
                   16560: 
1.243     albertel 16561: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   16562: ($udom and $uname are optional)
1.191     harris41 16563: 
                   16564: =item *
                   16565: 
1.243     albertel 16566: cput($namespace,$storehash,$udom,$uname) : critical put
                   16567: ($udom and $uname are optional)
1.191     harris41 16568: 
                   16569: =item *
                   16570: 
1.748     albertel 16571: newput($namespace,$storehash,$udom,$uname) :
                   16572: 
                   16573: Attempts to store the items in the $storehash, but only if they don't
                   16574: currently exist, if this succeeds you can be certain that you have 
                   16575: successfully created a new key value pair in the $namespace db.
                   16576: 
                   16577: 
                   16578: Args:
                   16579:  $namespace: name of database to store values to
                   16580:  $storehash: hashref to store to the db
                   16581:  $udom: (optional) domain of user containing the db
                   16582:  $uname: (optional) name of user caontaining the db
                   16583: 
                   16584: Returns:
                   16585:  'ok' -> succeeded in storing all keys of $storehash
                   16586:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   16587:                         least <key> already existed in the db (other
                   16588:                         requested keys may also already exist)
1.967     bisitz   16589:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 16590:  'con_lost' -> unable to contact request server
                   16591:  'refused' -> action was not allowed by remote machine
                   16592: 
                   16593: 
                   16594: =item *
                   16595: 
1.243     albertel 16596: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16597: reference filled in from namesp (encrypts the return communication)
                   16598: ($udom and $uname are optional)
1.191     harris41 16599: 
                   16600: =item *
                   16601: 
1.243     albertel 16602: log($udom,$name,$home,$message) : write to permanent log for user; use
                   16603: critical subroutine
                   16604: 
1.806     raeburn  16605: =item *
                   16606: 
1.860     raeburn  16607: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   16608: array reference filled in from namespace found in domain level on either
                   16609: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  16610: 
                   16611: =item *
                   16612: 
1.860     raeburn  16613: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   16614: domain level either on specified domain server ($uhome) or primary domain 
                   16615: server ($udom and $uhome are optional)
1.806     raeburn  16616: 
1.943     raeburn  16617: =item * 
                   16618: 
1.1172.2.35  raeburn  16619: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   16620: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   16621: the target domain.
                   16622: 
                   16623: May also include additional key => value pairs for the following groups:
                   16624: 
                   16625: =over
                   16626: 
                   16627: =item
                   16628: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   16629: 
                   16630: =over
                   16631: 
                   16632: =item defaultquota, authorquota
                   16633: 
                   16634: =back
                   16635: 
                   16636: =item
                   16637: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   16638: portfolio for users).
                   16639: 
                   16640: =over
                   16641: 
                   16642: =item
                   16643: aboutme, blog, webdav, portfolio
                   16644: 
                   16645: =back
                   16646: 
                   16647: =item
                   16648: requestcourses: ability to request courses, and how requests are processed.
                   16649: 
                   16650: =over
                   16651: 
                   16652: =item
1.1172.2.37  raeburn  16653: official, unofficial, community, textbook
1.1172.2.35  raeburn  16654: 
                   16655: =back
                   16656: 
                   16657: =item
                   16658: inststatus: types of institutional affiliation, and order in which they are displayed.
                   16659: 
                   16660: =over
                   16661: 
                   16662: =item
1.1172.2.44  raeburn  16663: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  16664: 
                   16665: =back
                   16666: 
                   16667: =item
                   16668: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   16669: for course's uploaded content.
                   16670: 
                   16671: =over
                   16672: 
                   16673: =item
1.1172.2.68  raeburn  16674: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   16675: communityquota, textbookquota
1.1172.2.35  raeburn  16676: 
                   16677: =back
                   16678: 
                   16679: =item
                   16680: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   16681: on your servers.
                   16682: 
                   16683: =over
                   16684: 
                   16685: =item
                   16686: remotesessions, hostedsessions
                   16687: 
                   16688: =back
                   16689: 
                   16690: =back
                   16691: 
                   16692: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   16693: utility to create a configuration.db file on a domain's primary library server
                   16694: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   16695: -- corresponding values are authentication type (internal, krb4, krb5,
                   16696: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   16697: will be available. Values are retrieved from cache (if current), unless the
                   16698: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   16699: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   16700: 
                   16701: Typical usage:
1.943     raeburn  16702: 
1.1172.2.35  raeburn  16703: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  16704: 
1.243     albertel 16705: =back
                   16706: 
                   16707: =head2 Network Status Functions
                   16708: 
                   16709: =over 4
1.191     harris41 16710: 
                   16711: =item *
                   16712: 
1.1137    raeburn  16713: dirlist() : return directory list based on URI (first arg).
                   16714: 
                   16715: Inputs: 1 required, 5 optional.
                   16716: 
                   16717: =over
                   16718: 
                   16719: =item 
                   16720: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   16721: 
                   16722: =item
                   16723: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   16724: 
                   16725: =item
                   16726: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   16727: 
                   16728: =item
                   16729: $getpropath - boolean: 1 if prepend path using &propath(). 
                   16730: 
                   16731: =item
                   16732: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   16733: 
                   16734: =item 
                   16735: $alternateRoot - path to prepend in place of path from $uri.
                   16736: 
                   16737: =back
                   16738: 
                   16739: Returns: Array of up to two items.
                   16740: 
                   16741: =over
                   16742: 
                   16743: a reference to an array of files/subdirectories
                   16744: 
                   16745: =over
                   16746: 
                   16747: Each element in the array of files/subdirectories is a & separated list of
                   16748: item name and the result of running stat on the item.  If dirlist was requested
                   16749: for a file instead of a directory, the item name will be ''. For a directory 
                   16750: listing, if the item is a metadata file, the element will end &N&M 
                   16751: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   16752: default copyright set (1).  
                   16753: 
                   16754: =back
                   16755: 
                   16756: a scalar containing error condition (if encountered).
                   16757: 
                   16758: =over
                   16759: 
                   16760: =item 
                   16761: no_host (no homeserver identified for $username:$domain).
                   16762: 
                   16763: =item 
                   16764: no_such_host (server contacted for listing not identified as valid host).
                   16765: 
                   16766: =item 
                   16767: con_lost (connection to remote server failed).
                   16768: 
                   16769: =item 
                   16770: refused (invalid $username:$domain received on lond side).
                   16771: 
                   16772: =item 
                   16773: no_such_dir (directory at specified path on lond side does not exist). 
                   16774: 
                   16775: =item 
                   16776: empty (directory at specified path on lond side is empty).
                   16777: 
                   16778: =over
                   16779: 
                   16780: This is currently not encountered because the &ls3, &ls2, 
                   16781: &ls (_handler) routines on the lond side do not filter out
                   16782: . and .. from a directory listing. 
                   16783: 
                   16784: =back
                   16785: 
                   16786: =back
                   16787: 
                   16788: =back
1.191     harris41 16789: 
                   16790: =item *
                   16791: 
1.243     albertel 16792: spareserver() : find server with least workload from spare.tab
                   16793: 
1.986     foxr     16794: 
                   16795: =item *
                   16796: 
                   16797: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   16798: if there is no corresponding loncapa host.
                   16799: 
1.243     albertel 16800: =back
                   16801: 
1.986     foxr     16802: 
1.243     albertel 16803: =head2 Apache Request
                   16804: 
                   16805: =over 4
1.191     harris41 16806: 
                   16807: =item *
                   16808: 
1.243     albertel 16809: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   16810: localhost, posts hash
                   16811: 
                   16812: =back
                   16813: 
                   16814: =head2 Data to String to Data
                   16815: 
                   16816: =over 4
1.191     harris41 16817: 
                   16818: =item *
                   16819: 
1.243     albertel 16820: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   16821: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 16822: 
                   16823: =item *
                   16824: 
1.243     albertel 16825: hashref2str($hashref) : convert a hashref into a string complete with
                   16826: escaping and '=' and '&' separators, supports elements that are
                   16827: arrayrefs and hashrefs
1.191     harris41 16828: 
                   16829: =item *
                   16830: 
1.243     albertel 16831: arrayref2str($arrayref) : convert an arrayref into a string complete
                   16832: with escaping and '&' separators, supports elements that are arrayrefs
                   16833: and hashrefs
1.191     harris41 16834: 
                   16835: =item *
                   16836: 
1.243     albertel 16837: str2hash($string) : convert string to hash using unescaping and
                   16838: splitting on '=' and '&', supports elements that are arrayrefs and
                   16839: hashrefs
1.191     harris41 16840: 
                   16841: =item *
                   16842: 
1.243     albertel 16843: str2array($string) : convert string to hash using unescaping and
                   16844: splitting on '&', supports elements that are arrayrefs and hashrefs
                   16845: 
                   16846: =back
                   16847: 
                   16848: =head2 Logging Routines
                   16849: 
                   16850: 
                   16851: These routines allow one to make log messages in the lonnet.log and
                   16852: lonnet.perm logfiles.
1.191     harris41 16853: 
1.1119    foxr     16854: =over 4
                   16855: 
1.191     harris41 16856: =item *
                   16857: 
1.243     albertel 16858: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 16859: 
                   16860: =item *
                   16861: 
1.243     albertel 16862: logthis() : append message to the normal lonnet.log file, it gets
                   16863: preiodically rolled over and deleted.
1.191     harris41 16864: 
                   16865: =item *
                   16866: 
1.243     albertel 16867: logperm() : append a permanent message to lonnet.perm.log, this log
                   16868: file never gets deleted by any automated portion of the system, only
                   16869: messages of critical importance should go in here.
                   16870: 
1.1119    foxr     16871: 
1.243     albertel 16872: =back
                   16873: 
                   16874: =head2 General File Helper Routines
                   16875: 
                   16876: =over 4
1.191     harris41 16877: 
                   16878: =item *
                   16879: 
1.481     raeburn  16880: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   16881: (a) files in /uploaded
                   16882:   (i) If a local copy of the file exists - 
                   16883:       compares modification date of local copy with last-modified date for 
                   16884:       definitive version stored on home server for course. If local copy is 
                   16885:       stale, requests a new version from the home server and stores it. 
                   16886:       If the original has been removed from the home server, then local copy 
                   16887:       is unlinked.
                   16888:   (ii) If local copy does not exist -
                   16889:       requests the file from the home server and stores it. 
                   16890:   
                   16891:   If $caller is 'uploadrep':  
                   16892:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   16893:     for request for files originally uploaded via DOCS. 
                   16894:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   16895:   
                   16896:   Otherwise:
                   16897:      This indicates a call from the content generation phase of the request.
                   16898:      -  returns the entire contents of the file or -1.
                   16899:      
                   16900: (b) files in /res
                   16901:    - returns the entire contents of a file or -1; 
                   16902:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 16903: 
1.712     albertel 16904: 
                   16905: =item *
                   16906: 
                   16907: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   16908:                   reference
                   16909: 
                   16910: returns either a stat() list of data about the file or an empty list
                   16911: if the file doesn't exist or couldn't find out about it (connection
                   16912: problems or user unknown)
                   16913: 
1.191     harris41 16914: =item *
                   16915: 
1.243     albertel 16916: filelocation($dir,$file) : returns file system location of a file
                   16917: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   16918: directory that relative $file lookups are to looked in ($dir of /a/dir
                   16919: and a file of ../bob will become /a/bob)
1.191     harris41 16920: 
                   16921: =item *
                   16922: 
                   16923: hreflocation($dir,$file) : returns file system location or a URL; same as
                   16924: filelocation except for hrefs
                   16925: 
                   16926: =item *
                   16927: 
1.1172.2.49  raeburn  16928: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   16929: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 16930: 
1.243     albertel 16931: =back
                   16932: 
1.608     albertel 16933: =head2 Usererfile file routines (/uploaded*)
                   16934: 
                   16935: =over 4
                   16936: 
                   16937: =item *
                   16938: 
                   16939: userfileupload(): main rotine for putting a file in a user or course's
                   16940:                   filespace, arguments are,
                   16941: 
1.620     albertel 16942:  formname - required - this is the name of the element in $env where the
1.608     albertel 16943:            filename, and the contents of the file to create/modifed exist
1.620     albertel 16944:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   16945:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  16946:  context - if coursedoc, store the file in the course of the active role
                   16947:              of the current user; 
                   16948:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   16949:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 16950:  subdir - required - subdirectory to put the file in under ../userfiles/
                   16951:          if undefined, it will be placed in "unknown"
                   16952: 
                   16953:  (This routine calls clean_filename() to remove any dangerous
                   16954:  characters from the filename, and then calls finuserfileupload() to
                   16955:  complete the transaction)
                   16956: 
                   16957:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16958:  and /adm/notfound.html if unsuccessful
                   16959: 
                   16960: =item *
                   16961: 
                   16962: clean_filename(): routine for cleaing a filename up for storage in
                   16963:                  userfile space, argument is:
                   16964: 
                   16965:  filename - proposed filename
                   16966: 
                   16967: returns: the new clean filename
                   16968: 
                   16969: =item *
                   16970: 
1.1090    raeburn  16971: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16972: userspace, probably shouldn't be called directly
                   16973: 
                   16974:   docuname: username or courseid of destination for the file
                   16975:   docudom: domain of user/course of destination for the file
                   16976:   formname: same as for userfileupload()
1.1090    raeburn  16977:   fname: filename (including subdirectories) for the file
                   16978:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  16979:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16980:   allfiles: reference to hash used to store objects found by parser
                   16981:   codebase: reference to hash used for codebases of java objects found by parser
                   16982:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16983:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16984:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   16985:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   16986:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   16987:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  16988:   mimetype: reference to scalar to accommodate mime type determined
                   16989:             from File::MMagic if $parser = parse.
1.608     albertel 16990: 
                   16991:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  16992:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   16993:  was 'overwrite').
                   16994:  
1.608     albertel 16995: 
                   16996: =item *
                   16997: 
                   16998: renameuserfile(): renames an existing userfile to a new name
                   16999: 
                   17000:   Args:
                   17001:    docuname: username or courseid of destination for the file
                   17002:    docudom: domain of user/course of destination for the file
                   17003:    old: current file name (including any subdirs under userfiles)
                   17004:    new: desired file name (including any subdirs under userfiles)
                   17005: 
                   17006: =item *
                   17007: 
                   17008: mkdiruserfile(): creates a directory is a userfiles dir
                   17009: 
                   17010:   Args:
                   17011:    docuname: username or courseid of destination for the file
                   17012:    docudom: domain of user/course of destination for the file
                   17013:    dir: dir to create (including any subdirs under userfiles)
                   17014: 
                   17015: =item *
                   17016: 
                   17017: removeuserfile(): removes a file that exists in userfiles
                   17018: 
                   17019:   Args:
                   17020:    docuname: username or courseid of destination for the file
                   17021:    docudom: domain of user/course of destination for the file
                   17022:    fname: filname to delete (including any subdirs under userfiles)
                   17023: 
                   17024: =item *
                   17025: 
                   17026: removeuploadedurl(): convience function for removeuserfile()
                   17027: 
                   17028:   Args:
                   17029:    url:  a full /uploaded/... url to delete
                   17030: 
1.747     albertel 17031: =item * 
                   17032: 
                   17033: get_portfile_permissions():
                   17034:   Args:
                   17035:     domain: domain of user or course contain the portfolio files
                   17036:     user: name of user or num of course contain the portfolio files
                   17037:   Returns:
                   17038:     hashref of a dump of the proper file_permissions.db
                   17039:    
                   17040: 
                   17041: =item * 
                   17042: 
                   17043: get_access_controls():
                   17044: 
                   17045: Args:
                   17046:   current_permissions: the hash ref returned from get_portfile_permissions()
                   17047:   group: (optional) the group you want the files associated with
                   17048:   file: (optional) the file you want access info on
                   17049: 
                   17050: Returns:
1.749     raeburn  17051:     a hash (keys are file names) of hashes containing
                   17052:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   17053:         values are XML containing access control settings (see below) 
1.747     albertel 17054: 
                   17055: Internal notes:
                   17056: 
1.749     raeburn  17057:  access controls are stored in file_permissions.db as key=value pairs.
                   17058:     key -> path to file/file_name\0uniqueID:scope_end_start
                   17059:         where scope -> public,guest,course,group,domains or users.
                   17060:               end -> UNIX time for end of access (0 -> no end date)
                   17061:               start -> UNIX time for start of access
                   17062: 
                   17063:     value -> XML description of access control
                   17064:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   17065:             <start></start>
                   17066:             <end></end>
                   17067: 
                   17068:             <password></password>  for scope type = guest
                   17069: 
                   17070:             <domain></domain>     for scope type = course or group
                   17071:             <number></number>
                   17072:             <roles id="">
                   17073:              <role></role>
                   17074:              <access></access>
                   17075:              <section></section>
                   17076:              <group></group>
                   17077:             </roles>
                   17078: 
                   17079:             <dom></dom>         for scope type = domains
                   17080: 
                   17081:             <users>             for scope type = users
                   17082:              <user>
                   17083:               <uname></uname>
                   17084:               <udom></udom>
                   17085:              </user>
                   17086:             </users>
                   17087:            </scope> 
                   17088:               
                   17089:  Access data is also aggregated for each file in an additional key=value pair:
                   17090:  key -> path to file/file_name\0accesscontrol 
                   17091:  value -> reference to hash
                   17092:           hash contains key = value pairs
                   17093:           where key = uniqueID:scope_end_start
                   17094:                 value = UNIX time record was last updated
                   17095: 
                   17096:           Used to improve speed of look-ups of access controls for each file.  
                   17097:  
                   17098:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   17099: 
1.1172.2.13  raeburn  17100: =item *
                   17101: 
1.749     raeburn  17102: modify_access_controls():
                   17103: 
                   17104: Modifies access controls for a portfolio file
                   17105: Args
                   17106: 1. file name
                   17107: 2. reference to hash of required changes,
                   17108: 3. domain
                   17109: 4. username
                   17110:   where domain,username are the domain of the portfolio owner 
                   17111:   (either a user or a course) 
                   17112: 
                   17113: Returns:
                   17114: 1. result of additions or updates ('ok' or 'error', with error message). 
                   17115: 2. result of deletions ('ok' or 'error', with error message).
                   17116: 3. reference to hash of any new or updated access controls.
                   17117: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   17118:    key = integer (inbound ID)
1.1172.2.13  raeburn  17119:    value = uniqueID
                   17120: 
                   17121: =item *
                   17122: 
                   17123: get_timebased_id():
                   17124: 
                   17125: Attempts to get a unique timestamp-based suffix for use with items added to a
                   17126: course via the Course Editor (e.g., folders, composite pages,
                   17127: group bulletin boards).
                   17128: 
                   17129: Args: (first three required; six others optional)
                   17130: 
                   17131: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   17132:    docssequence, or name of group
                   17133: 
                   17134: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   17135:    e.g., num, boardids
                   17136: 
                   17137: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   17138:    file will be named nohist_namespace.db
                   17139: 
                   17140: 4. cdom: domain of course; default is current course domain from %env
                   17141: 
                   17142: 5. cnum: course number; default is current course number from %env
                   17143: 
                   17144: 6. idtype: set to concat if an additional digit is to be appended to the
                   17145:    unix timestamp to form the suffix, if the plain timestamp is already
                   17146:    in use.  Default is to not do this, but simply increment the unix
                   17147:    timestamp by 1 until a unique key is obtained.
                   17148: 
                   17149: 7. who: holder of locking key; defaults to user:domain for user.
                   17150: 
                   17151: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   17152:    retrying); default is 3.
                   17153: 
                   17154: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   17155: 
                   17156: Returns:
                   17157: 
                   17158: 1. suffix obtained (numeric)
                   17159: 
                   17160: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   17161: 
                   17162: 3. error: contains (localized) error message if an error occurred.
                   17163: 
1.747     albertel 17164: 
1.608     albertel 17165: =back
                   17166: 
1.243     albertel 17167: =head2 HTTP Helper Routines
                   17168: 
                   17169: =over 4
                   17170: 
1.191     harris41 17171: =item *
                   17172: 
                   17173: escape() : unpack non-word characters into CGI-compatible hex codes
                   17174: 
                   17175: =item *
                   17176: 
                   17177: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   17178: 
1.243     albertel 17179: =back
                   17180: 
                   17181: =head1 PRIVATE SUBROUTINES
                   17182: 
                   17183: =head2 Underlying communication routines (Shouldn't call)
                   17184: 
                   17185: =over 4
                   17186: 
                   17187: =item *
                   17188: 
                   17189: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   17190: 
                   17191: =item *
                   17192: 
                   17193: reply() : uses subreply to send a message to remote machine, logs all failures
                   17194: 
                   17195: =item *
                   17196: 
                   17197: critical() : passes a critical message to another server; if cannot
                   17198: get through then place message in connection buffer directory and
                   17199: returns con_delayed, if incapable of saving message, returns
                   17200: con_failed
                   17201: 
                   17202: =item *
                   17203: 
                   17204: reconlonc() : tries to reconnect lonc client processes.
                   17205: 
                   17206: =back
                   17207: 
                   17208: =head2 Resource Access Logging
                   17209: 
                   17210: =over 4
                   17211: 
                   17212: =item *
                   17213: 
                   17214: flushcourselogs() : flush (save) buffer logs and access logs
                   17215: 
                   17216: =item *
                   17217: 
                   17218: courselog($what) : save message for course in hash
                   17219: 
                   17220: =item *
                   17221: 
                   17222: courseacclog($what) : save message for course using &courselog().  Perform
                   17223: special processing for specific resource types (problems, exams, quizzes, etc).
                   17224: 
1.191     harris41 17225: =item *
                   17226: 
                   17227: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   17228: as a PerlChildExitHandler
1.243     albertel 17229: 
                   17230: =back
                   17231: 
                   17232: =head2 Other
                   17233: 
                   17234: =over 4
                   17235: 
                   17236: =item *
                   17237: 
                   17238: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 17239: 
                   17240: =back
                   17241: 
                   17242: =cut
1.877     foxr     17243: 

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