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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1404  ! raeburn     4: # $Id: lonnet.pm,v 1.1403 2019/01/27 23:16:36 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.486     www        74: use HTTP::Date;
1.977     amueller   75: use Image::Magick;
1.1389    raeburn    76: use CGI::Cookie;
1.1182    foxr       77: 
1.1173    foxr       78: use Encode;
                     79: 
1.1245    raeburn    80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     82:             %managerstab);
1.871     albertel   83: 
                     84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        87:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        88: 
1.1       albertel   89: use IO::Socket;
1.31      www        90: use GDBM_File;
1.208     albertel   91: use HTML::LCParser;
1.88      www        92: use Fcntl qw(:flock);
1.870     albertel   93: use Storable qw(thaw nfreeze);
1.1289    damieng    94: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   95: use Cache::Memcached;
1.676     albertel   96: use Digest::MD5;
1.790     albertel   97: use Math::Random;
1.1024    raeburn    98: use File::MMagic;
1.807     albertel   99: use LONCAPA qw(:DEFAULT :match);
1.740     www       100: use LONCAPA::Configuration;
1.1160    www       101: use LONCAPA::lonmetadata;
1.1167    droeschl  102: use LONCAPA::Lond;
1.1345    raeburn   103: use LONCAPA::LWPReq;
1.1117    foxr      104: 
1.1090    raeburn   105: use File::Copy;
1.676     albertel  106: 
1.195     www       107: my $readit;
1.1288    damieng   108: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  109: 
1.619     albertel  110: require Exporter;
                    111: 
                    112: our @ISA = qw (Exporter);
                    113: our @EXPORT = qw(%env);
                    114: 
1.449     matthew   115: 
1.1187    raeburn   116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       117: {
                    118:     my $logid;
1.1187    raeburn   119:     sub write_log {
1.1188    raeburn   120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184    raeburn   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.1184    raeburn   127: 	$logid ++;
1.957     raeburn   128:         my $now = time();
                    129: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1184    raeburn   130:         my $logentry = { 
                    131:                           $id => {
                    132:                                    'exe_uname' => $env{'user.name'},
                    133:                                    'exe_udom'  => $env{'user.domain'},
                    134:                                    'exe_time'  => $now,
                    135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    136:                                    'delflag'   => $delflag,
                    137:                                    'logentry'  => $storehash,
                    138:                                    'uname'     => $uname,
                    139:                                    'udom'      => $udom,
                    140:                                   }
                    141:                        };
                    142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       143:     }
                    144: }
1.1       albertel  145: 
1.163     harris41  146: sub logtouch {
                    147:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  148:     unless (-e "$execdir/logs/lonnet.log") {	
1.1359    raeburn   149: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  150: 	close $fh;
                    151:     }
                    152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    154: }
                    155: 
1.1       albertel  156: sub logthis {
                    157:     my $message=shift;
                    158:     my $execdir=$perlvar{'lonDaemons'};
                    159:     my $now=time;
                    160:     my $local=localtime($now);
1.1359    raeburn   161:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    163: 	print $fh $logstring;
1.448     albertel  164: 	close($fh);
                    165:     }
1.1       albertel  166:     return 1;
                    167: }
                    168: 
                    169: sub logperm {
                    170:     my $message=shift;
                    171:     my $execdir=$perlvar{'lonDaemons'};
                    172:     my $now=time;
                    173:     my $local=localtime($now);
1.1359    raeburn   174:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  175: 	print $fh "$now:$message:$local\n";
                    176: 	close($fh);
                    177:     }
1.1       albertel  178:     return 1;
                    179: }
                    180: 
1.850     albertel  181: sub create_connection {
1.853     albertel  182:     my ($hostname,$lonid) = @_;
1.851     albertel  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  184: 				     Type    => SOCK_STREAM,
                    185: 				     Timeout => 10);
                    186:     return 0 if (!$client);
1.1399    raeburn   187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
1.850     albertel  188:     my $result = <$client>;
                    189:     chomp($result);
                    190:     return 1 if ($result eq 'done');
                    191:     return 0;
                    192: }
                    193: 
1.983     raeburn   194: sub get_server_timezone {
                    195:     my ($cnum,$cdom) = @_;
                    196:     my $home=&homeserver($cnum,$cdom);
                    197:     if ($home ne 'no_host') {
                    198:         my $cachetime = 24*3600;
                    199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    200:         if (defined($cached)) {
                    201:             return $timezone;
                    202:         } else {
                    203:             my $timezone = &reply('servertimezone',$home);
                    204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    205:         }
                    206:     }
                    207: }
1.850     albertel  208: 
1.1106    raeburn   209: sub get_server_distarch {
                    210:     my ($lonhost,$ignore_cache) = @_;
                    211:     if (defined($lonhost)) {
                    212:         if (!defined(&hostname($lonhost))) {
                    213:             return;
                    214:         }
                    215:         my $cachetime = 12*3600;
                    216:         if (!$ignore_cache) {
                    217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    218:             if (defined($cached)) {
                    219:                 return $distarch;
                    220:             }
                    221:         }
                    222:         my $rep = &reply('serverdistarch',$lonhost);
                    223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    225:                 $rep eq '') {
                    226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    227:         }
                    228:     }
                    229:     return;
                    230: }
                    231: 
1.1315    raeburn   232: sub get_servercerts_info {
1.1383    raeburn   233:     my ($lonhost,$hostname,$context) = @_;
                    234:     return if ($lonhost eq '');
                    235:     if ($hostname eq '') {
                    236:         $hostname = &hostname($lonhost);
                    237:     }
                    238:     return if ($hostname eq '');
1.1315    raeburn   239:     my ($rep,$uselocal);
1.1388    raeburn   240:     if ($context eq 'install') {
1.1387    raeburn   241:         $uselocal = 1;
                    242:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
1.1315    raeburn   243:         $uselocal = 1;
                    244:     }
1.1387    raeburn   245:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
1.1315    raeburn   246:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323    raeburn   247:         if ($distro eq '') {
                    248:             $uselocal = 0;
                    249:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315    raeburn   250:             if ($1 < 6) {
                    251:                 $uselocal = 0;
                    252:             }
1.1346    raeburn   253:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
                    254:             if ($1 < 12) {
                    255:                 $uselocal = 0;
                    256:             }
1.1315    raeburn   257:         }
                    258:     }
                    259:     if ($uselocal) {
1.1383    raeburn   260:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
1.1315    raeburn   261:     } else {
                    262:         $rep=&reply('servercerts',$lonhost);
                    263:     }
                    264:     my ($result,%returnhash);
                    265:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    266:         ($rep eq 'unknown_cmd')) {
                    267:         $result = $rep;
                    268:     } else {
                    269:         $result = 'ok';
                    270:         my @pairs=split(/\&/,$rep);
                    271:         foreach my $item (@pairs) {
                    272:             my ($key,$value)=split(/=/,$item,2);
                    273:             my $what = &unescape($key);
                    274:             $returnhash{$what}=&thaw_unescape($value);
                    275:         }
                    276:     }
                    277:     return ($result,\%returnhash);
                    278: }
                    279: 
1.993     raeburn   280: sub get_server_loncaparev {
1.1073    raeburn   281:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   282:     if (defined($lonhost)) {
                    283:         if (!defined(&hostname($lonhost))) {
                    284:             undef($lonhost);
                    285:         }
                    286:     }
                    287:     if (!defined($lonhost)) {
                    288:         if (defined(&domain($dom,'primary'))) {
                    289:             $lonhost=&domain($dom,'primary');
                    290:             if ($lonhost eq 'no_host') {
                    291:                 undef($lonhost);
                    292:             }
                    293:         }
                    294:     }
                    295:     if (defined($lonhost)) {
1.1073    raeburn   296:         my $cachetime = 12*3600;
                    297:         if (!$ignore_cache) {
                    298:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    299:             if (defined($cached)) {
                    300:                 return $loncaparev;
                    301:             }
                    302:         }
                    303:         my ($answer,$loncaparev);
                    304:         my @ids=&current_machine_ids();
                    305:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    306:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   307:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   308:                 $loncaparev = $1;
                    309:             }
                    310:         } else {
                    311:             $answer = &reply('serverloncaparev',$lonhost);
                    312:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    313:                 if ($caller eq 'loncron') {
1.1397    raeburn   314:                     my $hostname = &hostname($lonhost);
1.1073    raeburn   315:                     my $protocol = $protocol{$lonhost};
                    316:                     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn   317:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   318:                     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn   319:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073    raeburn   320:                     unless ($response->is_error()) {
                    321:                         my $content = $response->content;
1.1081    raeburn   322:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   323:                             $loncaparev = $1;
                    324:                         }
                    325:                     }
                    326:                 } else {
                    327:                     $loncaparev = $loncaparevs{$lonhost};
                    328:                 }
1.1081    raeburn   329:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   330:                 $loncaparev = $1;
                    331:             }
1.993     raeburn   332:         }
1.1073    raeburn   333:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   334:     }
                    335: }
                    336: 
1.1074    raeburn   337: sub get_server_homeID {
                    338:     my ($hostname,$ignore_cache,$caller) = @_;
                    339:     unless ($ignore_cache) {
                    340:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    341:         if (defined($cached)) {
                    342:             return $serverhomeID;
                    343:         }
                    344:     }
                    345:     my $cachetime = 12*3600;
                    346:     my $serverhomeID;
                    347:     if ($caller eq 'loncron') { 
                    348:         my @machine_ids = &machine_ids($hostname);
                    349:         foreach my $id (@machine_ids) {
                    350:             my $response = &reply('serverhomeID',$id);
                    351:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    352:                 $serverhomeID = $response;
                    353:                 last;
                    354:             }
                    355:         }
                    356:         if ($serverhomeID eq '') {
                    357:             $serverhomeID = $machine_ids[-1];
                    358:         }
                    359:     } else {
                    360:         $serverhomeID = $serverhomeIDs{$hostname};
                    361:     }
                    362:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    363: }
                    364: 
1.1121    raeburn   365: sub get_remote_globals {
                    366:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   367:     my ($result,%returnhash,%whatneeded);
                    368:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   369:         foreach my $what (sort(keys(%{$whathash}))) {
                    370:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   371:             my ($response,$cached);
1.1121    raeburn   372:             unless ($ignore_cache) {
1.1125    raeburn   373:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   374:             }
                    375:             if (defined($cached)) {
1.1125    raeburn   376:                 $returnhash{$what} = $response;
1.1121    raeburn   377:             } else {
1.1125    raeburn   378:                 $whatneeded{$what} = 1;
1.1121    raeburn   379:             }
                    380:         }
1.1125    raeburn   381:         if (keys(%whatneeded) == 0) {
                    382:             $result = 'ok';
                    383:         } else {
1.1121    raeburn   384:             my $requested = &freeze_escape(\%whatneeded);
                    385:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   386:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    387:                 ($rep eq 'unknown_cmd')) {
                    388:                 $result = $rep;
                    389:             } else {
                    390:                 $result = 'ok';
1.1121    raeburn   391:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   392:                 foreach my $item (@pairs) {
                    393:                     my ($key,$value)=split(/=/,$item,2);
                    394:                     my $what = &unescape($key);
                    395:                     my $hashid = $lonhost.'-'.$what;
                    396:                     $returnhash{$what}=&thaw_unescape($value);
                    397:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   398:                 }
                    399:             }
                    400:         }
                    401:     }
1.1125    raeburn   402:     return ($result,\%returnhash);
1.1121    raeburn   403: }
                    404: 
1.1124    raeburn   405: sub remote_devalidate_cache {
1.1241    raeburn   406:     my ($lonhost,$cachekeys) = @_;
                    407:     my $items;
                    408:     return unless (ref($cachekeys) eq 'ARRAY');
                    409:     my $cachestr = join('&',@{$cachekeys});
                    410:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   411:     return $response;
                    412: }
                    413: 
1.1       albertel  414: # -------------------------------------------------- Non-critical communication
                    415: sub subreply {
                    416:     my ($cmd,$server)=@_;
1.838     albertel  417:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      418:     #
                    419:     #  With loncnew process trimming, there's a timing hole between lonc server
                    420:     #  process exit and the master server picking up the listen on the AF_UNIX
                    421:     #  socket.  In that time interval, a lock file will exist:
                    422: 
                    423:     my $lockfile=$peerfile.".lock";
                    424:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   425: 	sleep(0.1);
1.549     foxr      426:     }
                    427:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      428:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      429:     #
1.550     foxr      430:     #   We'll give the connection a few tries before abandoning it.  If
                    431:     #   connection is not possible, we'll con_lost back to the client.
                    432:     #   
                    433:     my $client;
                    434:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    435: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    436: 				      Type    => SOCK_STREAM,
                    437: 				      Timeout => 10);
1.869     albertel  438: 	if ($client) {
1.550     foxr      439: 	    last;		# Connected!
1.850     albertel  440: 	} else {
1.853     albertel  441: 	    &create_connection(&hostname($server),$server);
1.550     foxr      442: 	}
1.1289    damieng   443:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      444:     }
                    445:     my $answer;
                    446:     if ($client) {
1.704     albertel  447: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      448: 	$answer=<$client>;
                    449: 	if (!$answer) { $answer="con_lost"; }
                    450: 	chomp($answer);
                    451:     } else {
                    452: 	$answer = 'con_lost';	# Failed connection.
                    453:     }
1.1       albertel  454:     return $answer;
                    455: }
                    456: 
                    457: sub reply {
                    458:     my ($cmd,$server)=@_;
1.838     albertel  459:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  460:     my $answer=subreply($cmd,$server);
1.65      www       461:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1396    raeburn   462:         my $logged = $cmd;
                    463:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    464:             my $subcmd = $1;
                    465:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    466:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    467:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
                    468:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    469:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    470:                     splice(@rest,2,1,'Hidden');
                    471:                 } elsif ($subcmd eq 'passwd') {
                    472:                     splice(@rest,2,2,('Hidden','Hidden'));
                    473:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    474:                          ($subcmd eq 'autoexportgrades')) {
                    475:                     splice(@rest,3,1,'Hidden');
                    476:                 }
                    477:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    478:             }
                    479:         }
                    480:         &logthis("<font color=\"blue\">WARNING:".
                    481:                  " $logged to $server returned $answer</font>");
1.12      www       482:     }
1.1       albertel  483:     return $answer;
                    484: }
                    485: 
                    486: # ----------------------------------------------------------- Send USR1 to lonc
                    487: 
                    488: sub reconlonc {
1.891     albertel  489:     my ($lonid) = @_;
                    490:     if ($lonid) {
1.1295    raeburn   491:         my $hostname = &hostname($lonid);
1.891     albertel  492: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    493: 	if ($hostname && -e $peerfile) {
                    494: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    495: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    496: 					     Type    => SOCK_STREAM,
                    497: 					     Timeout => 10);
                    498: 	    if ($client) {
                    499: 		print $client ("reset_retries\n");
                    500: 		my $answer=<$client>;
                    501: 		#reset just this one.
                    502: 	    }
                    503: 	}
                    504: 	return;
                    505:     }
                    506: 
1.836     www       507:     &logthis("Trying to reconnect lonc");
1.1       albertel  508:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359    raeburn   509:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  510: 	my $loncpid=<$fh>;
                    511:         chomp($loncpid);
                    512:         if (kill 0 => $loncpid) {
                    513: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    514:             kill USR1 => $loncpid;
                    515:             sleep 1;
1.1295    raeburn   516:         } else {
1.12      www       517: 	    &logthis(
1.672     albertel  518:                "<font color=\"blue\">WARNING:".
1.12      www       519:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  520:         }
                    521:     } else {
1.836     www       522: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  523:     }
                    524: }
                    525: 
                    526: # ------------------------------------------------------ Critical communication
1.12      www       527: 
1.1       albertel  528: sub critical {
                    529:     my ($cmd,$server)=@_;
1.838     albertel  530:     unless (&hostname($server)) {
1.672     albertel  531:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       532:                " Critical message to unknown server ($server)</font>");
                    533:         return 'no_such_host';
                    534:     }
1.1       albertel  535:     my $answer=reply($cmd,$server);
                    536:     if ($answer eq 'con_lost') {
1.1295    raeburn   537: 	&reconlonc($server);
1.589     albertel  538: 	my $answer=reply($cmd,$server);
1.1       albertel  539:         if ($answer eq 'con_lost') {
                    540:             my $now=time;
                    541:             my $middlename=$cmd;
1.5       www       542:             $middlename=substr($middlename,0,16);
1.1       albertel  543:             $middlename=~s/\W//g;
                    544:             my $dfilename=
1.305     www       545:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    546:             $dumpcount++;
1.1       albertel  547:             {
1.448     albertel  548: 		my $dfh;
1.1359    raeburn   549: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  550: 		    print $dfh "$cmd\n"; 
                    551: 		    close($dfh);
                    552: 		}
1.1       albertel  553:             }
1.1288    damieng   554:             sleep 1;
1.1       albertel  555:             my $wcmd='';
                    556:             {
1.448     albertel  557: 		my $dfh;
1.1359    raeburn   558: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  559: 		    $wcmd=<$dfh>; 
                    560: 		    close($dfh);
                    561: 		}
1.1       albertel  562:             }
                    563:             chomp($wcmd);
1.7       www       564:             if ($wcmd eq $cmd) {
1.672     albertel  565: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       566:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  567:                 &logperm("D:$server:$cmd");
                    568: 	        return 'con_delayed';
                    569:             } else {
1.672     albertel  570:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       571:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  572:                 &logperm("F:$server:$cmd");
                    573:                 return 'con_failed';
                    574:             }
                    575:         }
                    576:     }
                    577:     return $answer;
1.405     albertel  578: }
                    579: 
1.755     albertel  580: # ------------------------------------------- check if return value is an error
                    581: 
                    582: sub error {
                    583:     my ($result) = @_;
1.756     albertel  584:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  585: 	if ($2 == 2) { return undef; }
                    586: 	return $1;
                    587:     }
                    588:     return undef;
                    589: }
                    590: 
1.783     albertel  591: sub convert_and_load_session_env {
                    592:     my ($lonidsdir,$handle)=@_;
                    593:     my @profile;
                    594:     {
1.917     albertel  595: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    596: 	if (!$opened) {
1.915     albertel  597: 	    return 0;
                    598: 	}
1.783     albertel  599: 	flock($idf,LOCK_SH);
                    600: 	@profile=<$idf>;
                    601: 	close($idf);
                    602:     }
                    603:     my %temp_env;
                    604:     foreach my $line (@profile) {
1.786     albertel  605: 	if ($line !~ m/=/) {
                    606: 	    return 0;
                    607: 	}
1.783     albertel  608: 	chomp($line);
                    609: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    610: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    611:     }
                    612:     unlink("$lonidsdir/$handle.id");
                    613:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    614: 	    0640)) {
                    615: 	%disk_env = %temp_env;
                    616: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    617: 	untie(%disk_env);
                    618:     }
1.786     albertel  619:     return 1;
1.783     albertel  620: }
                    621: 
1.374     www       622: # ------------------------------------------- Transfer profile into environment
1.780     albertel  623: my $env_loaded;
                    624: sub transfer_profile_to_env {
1.788     albertel  625:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    626:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       627: 
1.720     albertel  628:     if (!defined($lonidsdir)) {
                    629: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    630:     }
                    631:     if (!defined($handle)) {
                    632:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    633:     }
                    634: 
1.786     albertel  635:     my $convert;
                    636:     {
1.917     albertel  637:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    638: 	if (!$opened) {
1.915     albertel  639: 	    return;
                    640: 	}
1.786     albertel  641: 	flock($idf,LOCK_SH);
                    642: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    643: 		&GDBM_READER(),0640)) {
                    644: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    645: 	    untie(%disk_env);
                    646: 	} else {
                    647: 	    $convert = 1;
                    648: 	}
                    649:     }
                    650:     if ($convert) {
                    651: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    652: 	    &logthis("Failed to load session, or convert session.");
                    653: 	}
1.374     www       654:     }
1.783     albertel  655: 
1.786     albertel  656:     my %remove;
1.783     albertel  657:     while ( my $envname = each(%env) ) {
1.433     matthew   658:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    659:             if ($time < time-300) {
1.783     albertel  660:                 $remove{$key}++;
1.433     matthew   661:             }
                    662:         }
                    663:     }
1.783     albertel  664: 
1.619     albertel  665:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  666:     $env_loaded=1;
1.783     albertel  667:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   668:         &delenv($expired_key);
1.374     www       669:     }
1.1       albertel  670: }
                    671: 
1.916     albertel  672: # ---------------------------------------------------- Check for valid session 
                    673: sub check_for_valid_session {
1.1355    raeburn   674:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  675:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1378    raeburn   676:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
                    677:     if ($name eq 'lonDAV') {
                    678:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    679:     } else {
                    680:         $lonidsdir=$r->dir_config('lonIDsDir');
                    681:         if ($name eq '') {
                    682:             $name = 'lonID';
                    683:         }
                    684:     }
                    685:     if ($name eq 'lonID') {
                    686:         $secure = 'lonSID';
1.1337    raeburn   687:         $linkname = 'lonLinkID';
                    688:         $pubname = 'lonPubID';
1.1378    raeburn   689:         if (exists($cookies{$secure})) {
                    690:             $lonid=$cookies{$secure};
                    691:         } elsif (exists($cookies{$name})) {
                    692:             $lonid=$cookies{$name};
1.1400    raeburn   693:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
1.1337    raeburn   694:             $lonid=$cookies{$linkname};
1.1378    raeburn   695:         } elsif (exists($cookies{$pubname})) {
                    696:             $lonid=$cookies{$pubname};
1.1337    raeburn   697:         }
1.1378    raeburn   698:     } else {
                    699:         $lonid=$cookies{$name};
1.1337    raeburn   700:     }
1.916     albertel  701:     return undef if (!$lonid);
                    702: 
                    703:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1378    raeburn   704:     if (-l "$lonidsdir/$handle.id") {
                    705:         my $link = readlink("$lonidsdir/$handle.id");
                    706:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    707:             $handle = $1;
                    708:         }
1.1155    raeburn   709:     }
1.1355    raeburn   710:     if (!-e "$lonidsdir/$handle.id") {
                    711:         if ((ref($domref)) && ($name eq 'lonID') && 
                    712:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    713:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    714:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    715:                 $$domref = $possudom;
                    716:             }
                    717:         }
                    718:         return undef;
                    719:     }
1.916     albertel  720: 
1.917     albertel  721:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    722:     return undef if (!$opened);
1.916     albertel  723: 
                    724:     flock($idf,LOCK_SH);
                    725:     my %disk_env;
                    726:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    727: 	    &GDBM_READER(),0640)) {
                    728: 	return undef;	
                    729:     }
                    730: 
                    731:     if (!defined($disk_env{'user.name'})
                    732: 	|| !defined($disk_env{'user.domain'})) {
1.1394    raeburn   733:         untie(%disk_env);
1.916     albertel  734: 	return undef;
                    735:     }
1.1245    raeburn   736: 
                    737:     if (ref($userhashref) eq 'HASH') {
                    738:         $userhashref->{'name'} = $disk_env{'user.name'};
                    739:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1361    raeburn   740:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375    raeburn   741:         if ($userhashref->{'lti'}) {
                    742:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
                    743:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
                    744:         }
1.1212    raeburn   745:     }
1.1394    raeburn   746:     untie(%disk_env);
1.1245    raeburn   747: 
1.916     albertel  748:     return $handle;
                    749: }
                    750: 
1.830     albertel  751: sub timed_flock {
                    752:     my ($file,$lock_type) = @_;
                    753:     my $failed=0;
                    754:     eval {
                    755: 	local $SIG{__DIE__}='DEFAULT';
                    756: 	local $SIG{ALRM}=sub {
                    757: 	    $failed=1;
                    758: 	    die("failed lock");
                    759: 	};
                    760: 	alarm(13);
                    761: 	flock($file,$lock_type);
                    762: 	alarm(0);
                    763:     };
                    764:     if ($failed) {
                    765: 	return undef;
                    766:     } else {
                    767: 	return 1;
                    768:     }
                    769: }
                    770: 
1.1392    raeburn   771: sub get_sessionfile_vars {
                    772:     my ($handle,$lonidsdir,$storearr) = @_;
                    773:     my %returnhash;
                    774:     unless (ref($storearr) eq 'ARRAY') {
                    775:         return %returnhash;
                    776:     }
                    777:     if (-l "$lonidsdir/$handle.id") {
                    778:         my $link = readlink("$lonidsdir/$handle.id");
                    779:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    780:             $handle = $1;
                    781:         }
                    782:     }
                    783:     if ((-e "$lonidsdir/$handle.id") &&
                    784:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    785:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    786:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    787:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    788:                 flock($idf,LOCK_SH);
                    789:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    790:                         &GDBM_READER(),0640)) {
                    791:                     foreach my $item (@{$storearr}) {
                    792:                         $returnhash{$item} = $disk_env{$item};
                    793:                     }
                    794:                     untie(%disk_env);
                    795:                 }
                    796:             }
                    797:         }
                    798:     }
                    799:     return %returnhash;
                    800: }
                    801: 
1.5       www       802: # ---------------------------------------------------------- Append Environment
                    803: 
                    804: sub appenv {
1.949     raeburn   805:     my ($newenv,$roles) = @_;
                    806:     if (ref($newenv) eq 'HASH') {
                    807:         foreach my $key (keys(%{$newenv})) {
                    808:             my $refused = 0;
                    809: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    810:                 $refused = 1;
                    811:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   812:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   813:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    814:                         $refused = 0;
                    815:                     }
                    816:                 }
                    817:             }
                    818:             if ($refused) {
                    819:                 &logthis("<font color=\"blue\">WARNING: ".
                    820:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    821:                          .'</font>');
                    822: 	        delete($newenv->{$key});
                    823:             } else {
                    824:                 $env{$key}=$newenv->{$key};
                    825:             }
                    826:         }
1.1376    raeburn   827:         my $lonids = $perlvar{'lonIDsDir'};
                    828:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    829:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    830:             if ($opened
                    831: 	        && &timed_flock($env_file,LOCK_EX)
                    832: 	        &&
                    833: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    834: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    835: 	        while (my ($key,$value) = each(%{$newenv})) {
                    836: 	            $disk_env{$key} = $value;
                    837: 	        }
                    838: 	        untie(%disk_env);
                    839:             }
1.35      www       840:         }
1.191     harris41  841:     }
1.56      www       842:     return 'ok';
                    843: }
                    844: # ----------------------------------------------------- Delete from Environment
                    845: 
                    846: sub delenv {
1.1104    raeburn   847:     my ($delthis,$regexp,$roles) = @_;
                    848:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    849:         my $refused = 1;
                    850:         if (ref($roles) eq 'ARRAY') {
                    851:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    852:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    853:                 $refused = 0;
                    854:             }
                    855:         }
                    856:         if ($refused) {
                    857:             &logthis("<font color=\"blue\">WARNING: ".
                    858:                      "Attempt to delete from environment ".$delthis);
                    859:             return 'error';
                    860:         }
1.56      www       861:     }
1.917     albertel  862:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    863:     if ($opened
1.915     albertel  864: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  865: 	&&
                    866: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    867: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  868: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   869: 	    if ($regexp) {
                    870:                 if ($key=~/^$delthis/) {
                    871:                     delete($env{$key});
                    872:                     delete($disk_env{$key});
                    873:                 } 
                    874:             } else {
                    875:                 if ($key=~/^\Q$delthis\E/) {
                    876: 		    delete($env{$key});
                    877: 		    delete($disk_env{$key});
                    878: 	        }
                    879:             }
1.448     albertel  880: 	}
1.783     albertel  881: 	untie(%disk_env);
1.5       www       882:     }
                    883:     return 'ok';
1.369     albertel  884: }
                    885: 
1.790     albertel  886: sub get_env_multiple {
                    887:     my ($name) = @_;
                    888:     my @values;
                    889:     if (defined($env{$name})) {
                    890:         # exists is it an array
                    891:         if (ref($env{$name})) {
                    892:             @values=@{ $env{$name} };
                    893:         } else {
                    894:             $values[0]=$env{$name};
                    895:         }
                    896:     }
                    897:     return(@values);
                    898: }
                    899: 
1.958     www       900: # ------------------------------------------------------------------- Locking
                    901: 
                    902: sub set_lock {
                    903:     my ($text)=@_;
                    904:     $locknum++;
                    905:     my $id=$$.'-'.$locknum;
                    906:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    907:              'session.lock.'.$id => $text});
                    908:     return $id;
                    909: }
                    910: 
                    911: sub get_locks {
                    912:     my $num=0;
                    913:     my %texts=();
                    914:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    915:        if ($lock=~/\w/) {
                    916:           $num++;
                    917:           $texts{$lock}=$env{'session.lock.'.$lock};
                    918:        }
                    919:    }
                    920:    return ($num,%texts);
                    921: }
                    922: 
                    923: sub remove_lock {
                    924:     my ($id)=@_;
                    925:     my $newlocks='';
                    926:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    927:        if (($lock=~/\w/) && ($lock ne $id)) {
                    928:           $newlocks.=','.$lock;
                    929:        }
                    930:     }
                    931:     &appenv({'session.locks' => $newlocks});
                    932:     &delenv('session.lock.'.$id);
                    933: }
                    934: 
                    935: sub remove_all_locks {
                    936:     my $activelocks=$env{'session.locks'};
                    937:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    938:        if ($lock=~/\w/) {
                    939:           &remove_lock($lock);
                    940:        }
                    941:     }
                    942: }
                    943: 
                    944: 
1.369     albertel  945: # ------------------------------------------ Find out current server userload
                    946: sub userload {
                    947:     my $numusers=0;
                    948:     {
                    949: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    950: 	my $filename;
                    951: 	my $curtime=time;
                    952: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  953: 	    next if ($filename eq '.' || $filename eq '..');
                    954: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1390    raeburn   955:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  956: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  957: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  958: 	}
                    959: 	closedir(LONIDS);
                    960:     }
                    961:     my $userloadpercent=0;
                    962:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    963:     if ($maxuserload) {
1.371     albertel  964: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  965:     }
1.372     albertel  966:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  967:     return $userloadpercent;
1.283     www       968: }
                    969: 
1.1       albertel  970: # ------------------------------ Find server with least workload from spare.tab
1.11      www       971: 
1.1       albertel  972: sub spareserver {
1.1083    raeburn   973:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  974:     my $spare_server;
1.370     albertel  975:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  976:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    977:                                                      :  $userloadpercent;
1.1083    raeburn   978:     my ($uint_dom,$remotesessions);
                    979:     if (($udom ne '') && (&domain($udom) ne '')) {
                    980:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    981:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    982:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    983:         $remotesessions = $udomdefaults{'remotesessions'};
                    984:     }
1.1123    raeburn   985:     my $spareshash = &this_host_spares($udom);
                    986:     if (ref($spareshash) eq 'HASH') {
                    987:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    988:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   989:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    990:                                              $try_server));
1.1123    raeburn   991: 	        ($spare_server, $lowest_load) =
                    992: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    993:             }
1.1083    raeburn   994:         }
1.784     albertel  995: 
1.1123    raeburn   996:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    997: 
                    998:         if (!$found_server) {
                    999:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                   1000: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn  1001:                     next unless (&spare_can_host($udom,$uint_dom,
                   1002:                                                  $remotesessions,$try_server));
1.1123    raeburn  1003: 	            ($spare_server, $lowest_load) =
                   1004: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                   1005:                 }
                   1006: 	    }
                   1007:         }
1.784     albertel 1008:     }
                   1009: 
                   1010:     if (!$want_server_name) {
1.1001    raeburn  1011:         if (defined($spare_server)) {
                   1012:             my $hostname = &hostname($spare_server);
1.1083    raeburn  1013:             if (defined($hostname)) {
1.1397    raeburn  1014:                 my $protocol = 'http';
                   1015:                 if ($protocol{$spare_server} eq 'https') {
                   1016:                     $protocol = $protocol{$spare_server};
                   1017:                 }
1.1001    raeburn  1018: 	        $spare_server = $protocol.'://'.$hostname;
                   1019:             }
                   1020:         }
1.784     albertel 1021:     }
                   1022:     return $spare_server;
                   1023: }
                   1024: 
                   1025: sub compare_server_load {
1.1253    raeburn  1026:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                   1027: 
                   1028:     if ($required) {
                   1029:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   1030:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1031:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   1032:         if (($major eq '' && $minor eq '') ||
                   1033:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   1034:             return ($spare_server,$lowest_load);
                   1035:         }
                   1036:     }
1.784     albertel 1037: 
                   1038:     my $loadans     = &reply('load',    $try_server);
                   1039:     my $userloadans = &reply('userload',$try_server);
                   1040: 
                   1041:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn  1042: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel 1043:     }
                   1044: 
                   1045:     my $load;
                   1046:     if ($loadans =~ /\d/) {
                   1047: 	if ($userloadans =~ /\d/) {
                   1048: 	    #both are numbers, pick the bigger one
                   1049: 	    $load = ($loadans > $userloadans) ? $loadans 
                   1050: 		                              : $userloadans;
1.411     albertel 1051: 	} else {
1.784     albertel 1052: 	    $load = $loadans;
1.411     albertel 1053: 	}
1.784     albertel 1054:     } else {
                   1055: 	$load = $userloadans;
                   1056:     }
                   1057: 
                   1058:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1059: 	$spare_server = $try_server;
                   1060: 	$lowest_load  = $load;
1.370     albertel 1061:     }
1.784     albertel 1062:     return ($spare_server,$lowest_load);
1.202     matthew  1063: }
1.914     albertel 1064: 
                   1065: # --------------------------- ask offload servers if user already has a session
                   1066: sub find_existing_session {
                   1067:     my ($udom,$uname) = @_;
1.1123    raeburn  1068:     my $spareshash = &this_host_spares($udom);
                   1069:     if (ref($spareshash) eq 'HASH') {
                   1070:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1071:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1072:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1073:             }
                   1074:         }
                   1075:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1076:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1077:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1078:             }
                   1079:         }
1.914     albertel 1080:     }
                   1081:     return;
                   1082: }
                   1083: 
1.1389    raeburn  1084: # check if user's browser sent load balancer cookie and server still has session
                   1085: # and is not overloaded.
                   1086: sub check_for_balancer_cookie {
                   1087:     my ($r,$update_mtime) = @_;
                   1088:     my ($otherserver,$cookie);
                   1089:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1090:     if (exists($cookies{'balanceID'})) {
                   1091:         my $balid = $cookies{'balanceID'};
                   1092:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1093:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1094:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1095:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1096:                 my ($possudom,$possuname) = ($1,$2);
                   1097:                 my $has_session = 0;
                   1098:                 if ((&domain($possudom) ne '') &&
                   1099:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1100:                     my $try_server;
                   1101:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1102:                     if ($opened) {
                   1103:                         flock($idf,LOCK_SH);
                   1104:                         while (my $line = <$idf>) {
                   1105:                             chomp($line);
                   1106:                             if (&hostname($line) ne '') {
                   1107:                                 $try_server = $line;
                   1108:                                 last;
                   1109:                             }
                   1110:                         }
                   1111:                         close($idf);
                   1112:                         if (($try_server) &&
                   1113:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1114:                             my $lowest_load = 30000;
                   1115:                             ($otherserver,$lowest_load) =
                   1116:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1117:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1118:                                 $has_session = 1;
                   1119:                             } else {
                   1120:                                 undef($otherserver);
                   1121:                             }
                   1122:                         }
                   1123:                     }
                   1124:                 }
                   1125:                 if ($has_session) {
                   1126:                     if ($update_mtime) {
                   1127:                         my $atime = my $mtime = time;
                   1128:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1129:                     }
                   1130:                 } else {
                   1131:                     unlink("$balancedir/$cookie.id");
                   1132:                 }
                   1133:             }
                   1134:         }
                   1135:     }
                   1136:     return ($otherserver,$cookie);
                   1137: }
                   1138: 
                   1139: sub delbalcookie {
                   1140:     my ($cookie,$balancer) =@_;
                   1141:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1142:         my ($udom,$uname) = ($1,$2);
                   1143:         my $uprimary_id = &domain($udom,'primary');
                   1144:         my $uintdom = &internet_dom($uprimary_id);
                   1145:         my $intdom = &internet_dom($balancer);
                   1146:         my $serverhomedom = &host_domain($balancer);
                   1147:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1148:             return &reply("delbalcookie:$cookie",$balancer);
                   1149:         }
                   1150:     }
                   1151: }
                   1152: 
1.914     albertel 1153: # -------------------------------- ask if server already has a session for user
                   1154: sub has_user_session {
                   1155:     my ($lonid,$udom,$uname) = @_;
                   1156:     my $result = &reply(join(':','userhassession',
                   1157: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1158:     return 1 if ($result eq 'ok');
                   1159: 
                   1160:     return 0;
                   1161: }
                   1162: 
1.1076    raeburn  1163: # --------- determine least loaded server in a user's domain which allows login
                   1164: 
                   1165: sub choose_server {
1.1259    raeburn  1166:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1167:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1168:     my %servers = &get_servers($udom);
1.1076    raeburn  1169:     my $lowest_load = 30000;
1.1259    raeburn  1170:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1171:     if ($skiploadbal) {
                   1172:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1173:         unless (defined($cached)) {
                   1174:             my $cachetime = 60*60*24;
                   1175:             my %domconfig =
                   1176:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1177:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1178:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1179:                                            $cachetime);
                   1180:             }
                   1181:         }
                   1182:     }
1.1076    raeburn  1183:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1184:         if ($skiploadbal) {
                   1185:             if (ref($balancers) eq 'HASH') {
                   1186:                 next if (exists($balancers->{$lonhost}));
                   1187:             }
1.1389    raeburn  1188:         }
1.1115    raeburn  1189:         my $loginvia;
                   1190:         if ($checkloginvia) {
                   1191:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1192:             if ($loginvia) {
                   1193:                 my ($server,$path) = split(/:/,$loginvia);
                   1194:                 ($login_host, $lowest_load) =
1.1253    raeburn  1195:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1196:                 if ($login_host eq $server) {
                   1197:                     $portal_path = $path;
1.1151    raeburn  1198:                     $isredirect = 1;
1.1116    raeburn  1199:                 }
                   1200:             } else {
                   1201:                 ($login_host, $lowest_load) =
1.1253    raeburn  1202:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1203:                 if ($login_host eq $lonhost) {
                   1204:                     $portal_path = '';
1.1151    raeburn  1205:                     $isredirect = ''; 
1.1116    raeburn  1206:                 }
                   1207:             }
                   1208:         } else {
1.1076    raeburn  1209:             ($login_host, $lowest_load) =
1.1253    raeburn  1210:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1211:         }
                   1212:     }
                   1213:     if ($login_host ne '') {
1.1116    raeburn  1214:         $hostname = &hostname($login_host);
1.1076    raeburn  1215:     }
1.1331    raeburn  1216:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1217: }
                   1218: 
1.202     matthew  1219: # --------------------------------------------- Try to change a user's password
                   1220: 
                   1221: sub changepass {
1.799     raeburn  1222:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1223:     $currentpass = &escape($currentpass);
                   1224:     $newpass     = &escape($newpass);
1.1030    raeburn  1225:     my $lonhost = $perlvar{'lonHostID'};
                   1226:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1227: 		       $server);
                   1228:     if (! $answer) {
                   1229: 	&logthis("No reply on password change request to $server ".
                   1230: 		 "by $uname in domain $udom.");
                   1231:     } elsif ($answer =~ "^ok") {
                   1232:         &logthis("$uname in $udom successfully changed their password ".
                   1233: 		 "on $server.");
                   1234:     } elsif ($answer =~ "^pwchange_failure") {
                   1235: 	&logthis("$uname in $udom was unable to change their password ".
                   1236: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1237: 		 "or pwchange");
                   1238:     } elsif ($answer =~ "^non_authorized") {
                   1239:         &logthis("$uname in $udom did not get their password correct when ".
                   1240: 		 "attempting to change it on $server.");
                   1241:     } elsif ($answer =~ "^auth_mode_error") {
                   1242:         &logthis("$uname in $udom attempted to change their password despite ".
                   1243: 		 "not being locally or internally authenticated on $server.");
                   1244:     } elsif ($answer =~ "^unknown_user") {
                   1245:         &logthis("$uname in $udom attempted to change their password ".
                   1246: 		 "on $server but were unable to because $server is not ".
                   1247: 		 "their home server.");
                   1248:     } elsif ($answer =~ "^refused") {
                   1249: 	&logthis("$server refused to change $uname in $udom password because ".
                   1250: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1251:     } elsif ($answer =~ "invalid_client") {
                   1252:         &logthis("$server refused to change $uname in $udom password because ".
                   1253:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1254:     }
                   1255:     return $answer;
1.1       albertel 1256: }
                   1257: 
1.169     harris41 1258: # ----------------------- Try to determine user's current authentication scheme
                   1259: 
                   1260: sub queryauthenticate {
                   1261:     my ($uname,$udom)=@_;
1.456     albertel 1262:     my $uhome=&homeserver($uname,$udom);
                   1263:     if (!$uhome) {
                   1264: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1265: 	return 'no_host';
                   1266:     }
                   1267:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1268:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1269: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1270:     }
1.456     albertel 1271:     return $answer;
1.169     harris41 1272: }
                   1273: 
1.1       albertel 1274: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1275: 
1.1       albertel 1276: sub authenticate {
1.1073    raeburn  1277:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1278:     $upass=&escape($upass);
                   1279:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1280:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1281:     my $newhome;
1.836     www      1282:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1283: # Maybe the machine was offline and only re-appeared again recently?
                   1284:         &reconlonc();
                   1285: # One more
1.952     raeburn  1286: 	$uhome=&homeserver($uname,$udom,1);
                   1287:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1288:             if (defined(&domain($udom,'primary'))) {
                   1289:                 $newhome=&domain($udom,'primary');
                   1290:             }
                   1291:             if ($newhome ne '') {
                   1292:                 $uhome = $newhome;
                   1293:             }
                   1294:         }
1.836     www      1295: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1296: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1297: 	    return 'no_host';
                   1298:         }
1.1       albertel 1299:     }
1.1073    raeburn  1300:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1301:     if ($answer eq 'authorized') {
1.952     raeburn  1302:         if ($newhome) {
                   1303:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1304:             return 'no_account_on_host'; 
                   1305:         } else {
                   1306:             &logthis("User $uname at $udom authorized by $uhome");
                   1307:             return $uhome;
                   1308:         }
1.471     albertel 1309:     }
                   1310:     if ($answer eq 'non_authorized') {
                   1311: 	&logthis("User $uname at $udom rejected by $uhome");
                   1312: 	return 'no_host'; 
1.9       www      1313:     }
1.471     albertel 1314:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1315:     return 'no_host';
                   1316: }
                   1317: 
1.1073    raeburn  1318: sub can_host_session {
1.1074    raeburn  1319:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1320:     my $canhost = 1;
1.1074    raeburn  1321:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1322:     if (ref($remotesessions) eq 'HASH') {
                   1323:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1324:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1325:                 $canhost = 0;
                   1326:             } else {
                   1327:                 $canhost = 1;
                   1328:             }
                   1329:         }
                   1330:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1331:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1332:                 $canhost = 1;
                   1333:             } else {
                   1334:                 $canhost = 0;
                   1335:             }
                   1336:         }
                   1337:         if ($canhost) {
                   1338:             if ($remotesessions->{'version'} ne '') {
                   1339:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1340:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1341:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1342:                         my $major = $1;
                   1343:                         my $minor = $2;
                   1344:                         if (($major < $reqmajor ) ||
                   1345:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1346:                             $canhost = 0;
                   1347:                         }
                   1348:                     } else {
                   1349:                         $canhost = 0;
                   1350:                     }
                   1351:                 }
                   1352:             }
                   1353:         }
                   1354:     }
                   1355:     if ($canhost) {
                   1356:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1357:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1358:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1359:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1360:                 if (($uint_dom ne '') && 
                   1361:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1362:                     $canhost = 0;
                   1363:                 } else {
                   1364:                     $canhost = 1;
                   1365:                 }
                   1366:             }
                   1367:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1368:                 if (($uint_dom ne '') && 
                   1369:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1370:                     $canhost = 1;
                   1371:                 } else {
                   1372:                     $canhost = 0;
                   1373:                 }
                   1374:             }
                   1375:         }
                   1376:     }
                   1377:     return $canhost;
                   1378: }
                   1379: 
1.1083    raeburn  1380: sub spare_can_host {
                   1381:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1382:     my $canhost=1;
1.1279    raeburn  1383:     my $try_server_hostname = &hostname($try_server);
                   1384:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1385:     my $serverhomedom = &host_domain($serverhomeID);
                   1386:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1387:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1388:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1389:             $canhost = 0;
                   1390:         }
                   1391:     }
                   1392:     if (($canhost) && ($uint_dom)) {
                   1393:         my @intdoms;
                   1394:         my $internet_names = &get_internet_names($try_server);
                   1395:         if (ref($internet_names) eq 'ARRAY') {
                   1396:             @intdoms = @{$internet_names};
                   1397:         }
                   1398:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1399:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1400:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1401:                                          $remotesessions,
                   1402:                                          $defdomdefaults{'hostedsessions'});
                   1403:         }
1.1083    raeburn  1404:     }
                   1405:     return $canhost;
                   1406: }
                   1407: 
1.1123    raeburn  1408: sub this_host_spares {
                   1409:     my ($dom) = @_;
1.1126    raeburn  1410:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1411:     my @hosts = &current_machine_ids();
                   1412:     foreach my $lonhost (@hosts) {
                   1413:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1414:             $dom_in_use = $dom;
                   1415:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1416:             last;
                   1417:         }
                   1418:     }
1.1126    raeburn  1419:     if ($dom_in_use ne '') {
                   1420:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1421:     }
                   1422:     if (ref($result) ne 'HASH') {
                   1423:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1424:         $dom_in_use = &host_domain($lonhost_in_use);
                   1425:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1426:         if (ref($result) ne 'HASH') {
                   1427:             $result = \%spareid;
                   1428:         }
                   1429:     }
                   1430:     return $result;
                   1431: }
                   1432: 
                   1433: sub spares_for_offload  {
                   1434:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1435:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1436:     if (defined($cached)) {
                   1437:         return $result;
                   1438:     } else {
1.1126    raeburn  1439:         my $cachetime = 60*60*24;
                   1440:         my %domconfig =
                   1441:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1442:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1443:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1444:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1445:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1446:                 }
                   1447:             }
                   1448:         }
                   1449:     }
1.1126    raeburn  1450:     return;
1.1123    raeburn  1451: }
                   1452: 
1.1129    raeburn  1453: sub get_lonbalancer_config {
                   1454:     my ($servers) = @_;
                   1455:     my ($currbalancer,$currtargets);
                   1456:     if (ref($servers) eq 'HASH') {
                   1457:         foreach my $server (keys(%{$servers})) {
                   1458:             my %what = (
                   1459:                          spareid => 1,
                   1460:                          perlvar => 1,
                   1461:                        );
                   1462:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1463:             if ($result eq 'ok') {
                   1464:                 if (ref($returnhash) eq 'HASH') {
                   1465:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1466:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1467:                             $currbalancer = $server;
                   1468:                             $currtargets = {};
                   1469:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1470:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1471:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1472:                                 }
                   1473:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1474:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1475:                                 }
                   1476:                             }
                   1477:                             last;
                   1478:                         }
                   1479:                     }
                   1480:                 }
                   1481:             }
                   1482:         }
                   1483:     }
                   1484:     return ($currbalancer,$currtargets);
                   1485: }
                   1486: 
                   1487: sub check_loadbalancing {
1.1331    raeburn  1488:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1489:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391    raeburn  1490:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129    raeburn  1491:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1492:     my @hosts = &current_machine_ids();
1.1129    raeburn  1493:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1494:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1495:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1496:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1497:     my $domneedscache;
1.1129    raeburn  1498:     my $cachetime = 60*60*24;
                   1499: 
                   1500:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1501:         $dom_in_use = $udom;
                   1502:         $homeintdom = 1;
                   1503:     } else {
                   1504:         $dom_in_use = $serverhomedom;
                   1505:     }
                   1506:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1507:     unless (defined($cached)) {
                   1508:         my %domconfig =
                   1509:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1510:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1511:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1512:         } else {
                   1513:             $domneedscache = $dom_in_use;
1.1129    raeburn  1514:         }
                   1515:     }
                   1516:     if (ref($result) eq 'HASH') {
1.1391    raeburn  1517:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1518:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1519:         if ($is_balancer) {
                   1520:             if (ref($currrules) eq 'HASH') {
                   1521:                 if ($homeintdom) {
                   1522:                     if ($uname ne '') {
                   1523:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1524:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1525:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1526:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1527:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1528:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1529:                             }
                   1530:                         }
                   1531:                         if ($rule_in_effect eq '') {
                   1532:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1533:                             if ($userenv{'inststatus'} ne '') {
                   1534:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1535:                                 my ($othertitle,$usertypes,$types) =
                   1536:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1537:                                 if (ref($types) eq 'ARRAY') {
                   1538:                                     foreach my $type (@{$types}) {
                   1539:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1540:                                             if (exists($currrules->{$type})) {
                   1541:                                                 $rule_in_effect = $currrules->{$type};
                   1542:                                             }
                   1543:                                         }
                   1544:                                     }
                   1545:                                 }
                   1546:                             } else {
                   1547:                                 if (exists($currrules->{'default'})) {
                   1548:                                     $rule_in_effect = $currrules->{'default'};
                   1549:                                 }
                   1550:                             }
                   1551:                         }
                   1552:                     } else {
                   1553:                         if (exists($currrules->{'default'})) {
                   1554:                             $rule_in_effect = $currrules->{'default'};
                   1555:                         }
                   1556:                     }
                   1557:                 } else {
                   1558:                     if ($currrules->{'_LC_external'} ne '') {
                   1559:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1560:                     }
                   1561:                 }
                   1562:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1563:                                                        $uname,$udom);
                   1564:             }
                   1565:         }
                   1566:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1567:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1568:         unless (defined($cached)) {
                   1569:             my %domconfig =
                   1570:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1571:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1572:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1573:             } else {
                   1574:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1575:             }
                   1576:         }
                   1577:         if (ref($result) eq 'HASH') {
1.1391    raeburn  1578:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1579:                 &check_balancer_result($result,@hosts);
                   1580:             if ($is_balancer) {
1.1129    raeburn  1581:                 if (ref($currrules) eq 'HASH') {
                   1582:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1583:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1584:                     }
                   1585:                 }
                   1586:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1587:                                                        $uname,$udom);
                   1588:             }
                   1589:         } else {
                   1590:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1591:                 $is_balancer = 1;
                   1592:                 $offloadto = &this_host_spares($dom_in_use);
                   1593:             }
1.1307    raeburn  1594:             unless (defined($cached)) {
                   1595:                 $domneedscache = $serverhomedom;
                   1596:             }
1.1129    raeburn  1597:         }
                   1598:     } else {
                   1599:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1600:             $is_balancer = 1;
                   1601:             $offloadto = &this_host_spares($dom_in_use);
                   1602:         }
1.1307    raeburn  1603:         unless (defined($cached)) {
                   1604:             $domneedscache = $serverhomedom;
                   1605:         }
                   1606:     }
                   1607:     if ($domneedscache) {
                   1608:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1609:     }
1.1176    raeburn  1610:     if ($is_balancer) {
                   1611:         my $lowest_load = 30000;
                   1612:         if (ref($offloadto) eq 'HASH') {
                   1613:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1614:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1615:                     ($otherserver,$lowest_load) =
                   1616:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1617:                 }
1.1129    raeburn  1618:             }
1.1176    raeburn  1619:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1620: 
1.1176    raeburn  1621:             if (!$found_server) {
                   1622:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1623:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1624:                         ($otherserver,$lowest_load) =
                   1625:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1626:                     }
                   1627:                 }
                   1628:             }
                   1629:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1630:             if (@{$offloadto} == 1) {
                   1631:                 $otherserver = $offloadto->[0];
                   1632:             } elsif (@{$offloadto} > 1) {
                   1633:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1634:                     ($otherserver,$lowest_load) =
                   1635:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1636:                 }
                   1637:             }
                   1638:         }
1.1331    raeburn  1639:         unless ($caller eq 'login') {
                   1640:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1641:                 $is_balancer = 0;
                   1642:                 if ($uname ne '' && $udom ne '') {
                   1643:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389    raeburn  1644:                         &appenv({'user.loadbalexempt'     => $lonhost,
1.1331    raeburn  1645:                                  'user.loadbalcheck.time' => time});
                   1646:                     }
1.1176    raeburn  1647:                 }
1.1129    raeburn  1648:             }
                   1649:         }
1.1389    raeburn  1650:         unless ($homeintdom) {
                   1651:             undef($setcookie);
                   1652:         }
1.1129    raeburn  1653:     }
1.1391    raeburn  1654:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129    raeburn  1655: }
                   1656: 
1.1191    raeburn  1657: sub check_balancer_result {
                   1658:     my ($result,@hosts) = @_;
1.1391    raeburn  1659:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1660:     if (ref($result) eq 'HASH') {
                   1661:         if ($result->{'lonhost'} ne '') {
                   1662:             my $currbalancer = $result->{'lonhost'};
                   1663:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1664:                 $is_balancer = 1;
                   1665:                 $currtargets = $result->{'targets'};
                   1666:                 $currrules = $result->{'rules'};
                   1667:             }
1.1391    raeburn  1668:             $dom_balancers = $currbalancer;
1.1191    raeburn  1669:         } else {
1.1391    raeburn  1670:             if (keys(%{$result})) {
                   1671:                 foreach my $key (keys(%{$result})) {
                   1672:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1673:                         (ref($result->{$key}) eq 'HASH')) {
                   1674:                         $is_balancer = 1;
                   1675:                         $currrules = $result->{$key}{'rules'};
                   1676:                         $currtargets = $result->{$key}{'targets'};
                   1677:                         $setcookie = $result->{$key}{'cookie'};
                   1678:                         last;
                   1679:                     }
1.1191    raeburn  1680:                 }
1.1391    raeburn  1681:                 $dom_balancers = join(',',sort(keys(%{$result})));
1.1191    raeburn  1682:             }
                   1683:         }
                   1684:     }
1.1391    raeburn  1685:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1686: }
                   1687: 
1.1129    raeburn  1688: sub get_loadbalancer_targets {
                   1689:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1690:     my $offloadto;
1.1175    raeburn  1691:     if ($rule_in_effect eq 'none') {
                   1692:         return [$perlvar{'lonHostID'}];
                   1693:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1694:         $offloadto = $currtargets;
                   1695:     } else {
                   1696:         if ($rule_in_effect eq 'homeserver') {
                   1697:             my $homeserver = &homeserver($uname,$udom);
                   1698:             if ($homeserver ne 'no_host') {
                   1699:                 $offloadto = [$homeserver];
                   1700:             }
                   1701:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1702:             my %domconfig =
                   1703:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1704:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1705:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1706:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1707:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1708:                     }
                   1709:                 }
                   1710:             } else {
1.1178    raeburn  1711:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1712:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1713:                 if (&hostname($remotebalancer) ne '') {
                   1714:                     $offloadto = [$remotebalancer];
                   1715:                 }
                   1716:             }
                   1717:         } elsif (&hostname($rule_in_effect) ne '') {
                   1718:             $offloadto = [$rule_in_effect];
                   1719:         }
                   1720:     }
                   1721:     return $offloadto;
                   1722: }
                   1723: 
1.1127    raeburn  1724: sub internet_dom_servers {
                   1725:     my ($dom) = @_;
                   1726:     my (%uniqservers,%servers);
                   1727:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1728:     my @machinedoms = &machine_domains($primaryserver);
                   1729:     foreach my $mdom (@machinedoms) {
                   1730:         my %currservers = %servers;
                   1731:         my %server = &get_servers($mdom);
                   1732:         %servers = (%currservers,%server);
                   1733:     }
                   1734:     my %by_hostname;
                   1735:     foreach my $id (keys(%servers)) {
                   1736:         push(@{$by_hostname{$servers{$id}}},$id);
                   1737:     }
                   1738:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1739:         if (@{$by_hostname{$hostname}} > 1) {
                   1740:             my $match = 0;
                   1741:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1742:                 if (&host_domain($id) eq $dom) {
                   1743:                     $uniqservers{$id} = $hostname;
                   1744:                     $match = 1;
                   1745:                 }
                   1746:             }
                   1747:             unless ($match) {
                   1748:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1749:             }
                   1750:         } else {
                   1751:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1752:         }
                   1753:     }
                   1754:     return %uniqservers;
                   1755: }
                   1756: 
1.1347    raeburn  1757: sub trusted_domains {
                   1758:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1759:     my ($trusted,$untrusted);
1.1347    raeburn  1760:     if (&domain($calldom) eq '') {
1.1349    raeburn  1761:         return ($trusted,$untrusted);
1.1347    raeburn  1762:     }
1.1395    raeburn  1763:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1764:         return ($trusted,$untrusted);
1.1347    raeburn  1765:     }
                   1766:     my $callprimary = &domain($calldom,'primary');
                   1767:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1768:     if ($intcalldom eq '') {
1.1349    raeburn  1769:         return ($trusted,$untrusted);
1.1347    raeburn  1770:     }
                   1771: 
                   1772:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1773:     unless (defined($cached)) {
                   1774:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1775:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1776:         $trustconfig = $domconfig{'trust'};
                   1777:     }
                   1778:     if (ref($trustconfig)) {
                   1779:         my (%possexc,%possinc,@allexc,@allinc); 
                   1780:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1781:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1782:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1783:             }
                   1784:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395    raeburn  1785:                 $possinc{$intcalldom} = 1;
1.1347    raeburn  1786:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1787:             }
                   1788:         }
                   1789:         if (keys(%possexc)) {
                   1790:             if (keys(%possinc)) {
                   1791:                 foreach my $key (sort(keys(%possexc))) {
                   1792:                     next if ($key eq $intcalldom);
                   1793:                     unless ($possinc{$key}) {
                   1794:                         push(@allexc,$key);
                   1795:                     }
                   1796:                 }
                   1797:             } else {
                   1798:                 @allexc = sort(keys(%possexc));
                   1799:             }
                   1800:         }
                   1801:         if (keys(%possinc)) {
                   1802:             $possinc{$intcalldom} = 1;
                   1803:             @allinc = sort(keys(%possinc));
                   1804:         }
                   1805:         if ((@allexc > 0) || (@allinc > 0)) {
                   1806:             my %doms_by_intdom;
                   1807:             my %allintdoms = &all_host_intdom();
                   1808:             my %alldoms = &all_host_domain();
                   1809:             foreach my $key (%allintdoms) {
                   1810:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1811:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1812:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1813:                     }
                   1814:                 } else {
                   1815:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1816:                 }
                   1817:             }
                   1818:             foreach my $exc (@allexc) {
                   1819:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395    raeburn  1820:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347    raeburn  1821:                 }
                   1822:             }
                   1823:             foreach my $inc (@allinc) {
                   1824:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395    raeburn  1825:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347    raeburn  1826:                 }
                   1827:             }
                   1828:         }
                   1829:     }
1.1349    raeburn  1830:     return ($trusted,$untrusted);
1.1347    raeburn  1831: }
                   1832: 
                   1833: sub will_trust {
                   1834:     my ($cmdtype,$domain,$possdom) = @_;
                   1835:     return 1 if ($domain eq $possdom);
                   1836:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1837:     my $willtrust; 
                   1838:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1839:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1840:             $willtrust = 1;
                   1841:         }
                   1842:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1843:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1844:             $willtrust = 1;
                   1845:         }
                   1846:     } else {
                   1847:         $willtrust = 1;
                   1848:     }
                   1849:     return $willtrust;
                   1850: }
                   1851: 
1.1       albertel 1852: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1853: 
1.599     albertel 1854: my %homecache;
1.1       albertel 1855: sub homeserver {
1.230     stredwic 1856:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1857:     my $index="$uname:$udom";
1.426     albertel 1858: 
1.599     albertel 1859:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1860: 
                   1861:     my %servers = &get_servers($udom,'library');
                   1862:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1863:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1864: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1865: 
                   1866: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1867: 	if ($answer eq 'found') {
                   1868: 	    delete($badServerCache{$tryserver}); 
                   1869: 	    return $homecache{$index}=$tryserver;
                   1870: 	} elsif ($answer eq 'no_host') {
                   1871: 	    $badServerCache{$tryserver}=1;
                   1872: 	}
1.1       albertel 1873:     }    
                   1874:     return 'no_host';
1.70      www      1875: }
                   1876: 
1.1300    raeburn  1877: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1878: 
                   1879: sub idget {
1.1300    raeburn  1880:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1881:     my %returnhash=();
1.1300    raeburn  1882:     my @ids=(); 
                   1883:     if (ref($idsref) eq 'ARRAY') {
                   1884:         @ids = @{$idsref};
                   1885:     } else {
                   1886:         return %returnhash; 
                   1887:     }
                   1888:     if ($namespace eq '') {
                   1889:         $namespace = 'ids';
                   1890:     }
1.70      www      1891:     
1.841     albertel 1892:     my %servers = &get_servers($udom,'library');
                   1893:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1894: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1895: 	if ($namespace eq 'ids') {
                   1896: 	    $idlist=~tr/A-Z/a-z/;
                   1897: 	}
                   1898: 	my $reply;
                   1899: 	if ($namespace eq 'ids') {
                   1900: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1901: 	} else {
                   1902: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1903: 	}
1.841     albertel 1904: 	my @answer=();
                   1905: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1906: 	    @answer=split(/\&/,$reply);
                   1907: 	}                    ;
                   1908: 	my $i;
                   1909: 	for ($i=0;$i<=$#ids;$i++) {
                   1910: 	    if ($answer[$i]) {
1.1299    raeburn  1911: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1912: 	    }
1.841     albertel 1913: 	}
1.1300    raeburn  1914:     }
1.70      www      1915:     return %returnhash;
                   1916: }
                   1917: 
                   1918: # ------------------------------------- Find the IDs behind a list of usernames
                   1919: 
                   1920: sub idrget {
                   1921:     my ($udom,@unames)=@_;
                   1922:     my %returnhash=();
1.800     albertel 1923:     foreach my $uname (@unames) {
                   1924:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1925:     }
1.70      www      1926:     return %returnhash;
                   1927: }
                   1928: 
1.1300    raeburn  1929: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1930: 
                   1931: sub idput {
1.1300    raeburn  1932:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1933:     my %servers=();
1.1300    raeburn  1934:     my %ids=();
                   1935:     my %byid = ();
                   1936:     if (ref($idsref) eq 'HASH') {
                   1937:         %ids=%{$idsref};
                   1938:     }
                   1939:     if ($namespace eq '') {
                   1940:         $namespace = 'ids'; 
                   1941:     }
1.800     albertel 1942:     foreach my $uname (keys(%ids)) {
                   1943: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1944:         if ($uhom eq '') {
                   1945:             $uhom=&homeserver($uname,$udom);
                   1946:         }
1.70      www      1947:         if ($uhom ne 'no_host') {
1.800     albertel 1948:             my $esc_unam=&escape($uname);
1.1300    raeburn  1949:             if ($namespace eq 'ids') {
                   1950:                 my $id=&escape($ids{$uname});
                   1951:                 $id=~tr/A-Z/a-z/;
                   1952:                 my $esc_unam=&escape($uname);
                   1953:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1954:             } else {
1.1300    raeburn  1955:                 my @currids = split(/,/,$ids{$uname});
                   1956:                 foreach my $id (@currids) {
                   1957:                     $byid{$uhom}{$id} .= $uname.',';
                   1958:                 }
                   1959:             }
                   1960:         }
                   1961:     }
                   1962:     if ($namespace eq 'clickers') {
                   1963:         foreach my $server (keys(%byid)) {
                   1964:             if (ref($byid{$server}) eq 'HASH') {
                   1965:                 foreach my $id (keys(%{$byid{$server}})) {
                   1966:                     $byid{$server} =~ s/,$//;
                   1967:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1968:                 }
1.70      www      1969:             }
                   1970:         }
1.191     harris41 1971:     }
1.800     albertel 1972:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1973:         $servers{$server} =~ s/\&$//;
                   1974:         if ($namespace eq 'ids') {     
                   1975:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1976:         } else {
                   1977:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1978:         }
1.191     harris41 1979:     }
1.344     www      1980: }
                   1981: 
1.1300    raeburn  1982: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1983: 
                   1984: sub iddel {
1.1300    raeburn  1985:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1986:     my %result=();
1.1300    raeburn  1987:     my %ids=();
                   1988:     my %byid = ();
                   1989:     if (ref($idshashref) eq 'HASH') {
                   1990:         %ids=%{$idshashref};
                   1991:     } else {
1.1231    raeburn  1992:         return %result;
                   1993:     }
1.1300    raeburn  1994:     if ($namespace eq '') {
                   1995:         $namespace = 'ids';
                   1996:     }
1.1231    raeburn  1997:     my %servers=();
1.1300    raeburn  1998:     while (my ($id,$unamestr) = each(%ids)) {
                   1999:         if ($namespace eq 'ids') {
                   2000:             my $uhom = $uhome;
                   2001:             if ($uhom eq '') { 
                   2002:                 $uhom=&homeserver($unamestr,$udom);
                   2003:             }
                   2004:             if ($uhom ne 'no_host') {
                   2005:                 $servers{$uhom}.='&'.&escape($id);
                   2006:             }
                   2007:          } else {
                   2008:             my @curritems = split(/,/,$ids{$id});
                   2009:             foreach my $uname (@curritems) {
                   2010:                 my $uhom = $uhome;
                   2011:                 if ($uhom eq '') {
                   2012:                     $uhom=&homeserver($uname,$udom);
                   2013:                 }
                   2014:                 if ($uhom ne 'no_host') { 
                   2015:                     $byid{$uhom}{$id} .= $uname.',';
                   2016:                 }
                   2017:             }
1.1231    raeburn  2018:         }
1.1300    raeburn  2019:     }
                   2020:     if ($namespace eq 'clickers') {
                   2021:         foreach my $server (keys(%byid)) {
                   2022:             if (ref($byid{$server}) eq 'HASH') {
                   2023:                 foreach my $id (keys(%{$byid{$server}})) {
                   2024:                     $byid{$server}{$id} =~ s/,$//;
                   2025:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   2026:                 }
1.1231    raeburn  2027:             }
                   2028:         }
                   2029:     }
                   2030:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2031:         $servers{$server} =~ s/\&$//;
                   2032:         if ($namespace eq 'ids') {
                   2033:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   2034:         } elsif ($namespace eq 'clickers') {
                   2035:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   2036:         }
1.1231    raeburn  2037:     }
                   2038:     return %result;
                   2039: }
                   2040: 
1.1300    raeburn  2041: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   2042: 
                   2043: sub updateclickers {
                   2044:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   2045:     my %clickers;
                   2046:     if (ref($idshashref) eq 'HASH') {
                   2047:         %clickers=%{$idshashref};
                   2048:     } else {
                   2049:         return;
                   2050:     }
                   2051:     my $items='';
                   2052:     foreach my $item (keys(%clickers)) {
                   2053:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   2054:     }
                   2055:     $items=~s/\&$//;
                   2056:     my $request = "updateclickers:$udom:$action:$items";
                   2057:     if ($critical) {
                   2058:         return &critical($request,$uhome);
                   2059:     } else {
                   2060:         return &reply($request,$uhome);
                   2061:     }
                   2062: }
                   2063: 
1.1023    raeburn  2064: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  2065: sub dump_dom {
1.1165    droeschl 2066:     my ($namespace, $udom, $regexp) = @_;
                   2067: 
                   2068:     $udom ||= $env{'user.domain'};
                   2069: 
                   2070:     return () unless $udom;
                   2071: 
                   2072:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  2073: }
                   2074: 
1.1023    raeburn  2075: # ------------------------------------------ get items from domain db files   
1.806     raeburn  2076: 
                   2077: sub get_dom {
1.860     raeburn  2078:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  2079:     return if ($udom eq 'public');
1.806     raeburn  2080:     my $items='';
                   2081:     foreach my $item (@$storearr) {
                   2082:         $items.=&escape($item).'&';
                   2083:     }
                   2084:     $items=~s/\&$//;
1.860     raeburn  2085:     if (!$udom) {
                   2086:         $udom=$env{'user.domain'};
1.1267    raeburn  2087:         return if ($udom eq 'public');
1.860     raeburn  2088:         if (defined(&domain($udom,'primary'))) {
                   2089:             $uhome=&domain($udom,'primary');
                   2090:         } else {
1.874     albertel 2091:             undef($uhome);
1.860     raeburn  2092:         }
                   2093:     } else {
                   2094:         if (!$uhome) {
                   2095:             if (defined(&domain($udom,'primary'))) {
                   2096:                 $uhome=&domain($udom,'primary');
                   2097:             }
                   2098:         }
                   2099:     }
                   2100:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  2101:         my $rep;
                   2102:         if ($namespace =~ /^enc/) {
                   2103:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2104:         } else {
                   2105:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2106:         }
1.866     raeburn  2107:         my %returnhash;
1.875     albertel 2108:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2109:             return %returnhash;
                   2110:         }
1.806     raeburn  2111:         my @pairs=split(/\&/,$rep);
                   2112:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2113:             return @pairs;
                   2114:         }
                   2115:         my $i=0;
                   2116:         foreach my $item (@$storearr) {
                   2117:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2118:             $i++;
                   2119:         }
                   2120:         return %returnhash;
                   2121:     } else {
1.880     banghart 2122:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2123:     }
                   2124: }
                   2125: 
                   2126: # -------------------------------------------- put items in domain db files 
                   2127: 
                   2128: sub put_dom {
1.860     raeburn  2129:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   2130:     if (!$udom) {
                   2131:         $udom=$env{'user.domain'};
                   2132:         if (defined(&domain($udom,'primary'))) {
                   2133:             $uhome=&domain($udom,'primary');
                   2134:         } else {
1.874     albertel 2135:             undef($uhome);
1.860     raeburn  2136:         }
                   2137:     } else {
                   2138:         if (!$uhome) {
                   2139:             if (defined(&domain($udom,'primary'))) {
                   2140:                 $uhome=&domain($udom,'primary');
                   2141:             }
                   2142:         }
                   2143:     } 
                   2144:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2145:         my $items='';
                   2146:         foreach my $item (keys(%$storehash)) {
                   2147:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2148:         }
                   2149:         $items=~s/\&$//;
1.1344    raeburn  2150:         if ($namespace =~ /^enc/) {
                   2151:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2152:         } else {
                   2153:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2154:         }
1.806     raeburn  2155:     } else {
1.860     raeburn  2156:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2157:     }
                   2158: }
                   2159: 
1.1023    raeburn  2160: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2161: sub newput_dom {
1.1023    raeburn  2162:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2163:     my $result;
                   2164:     if (!$udom) {
                   2165:         $udom=$env{'user.domain'};
                   2166:     }
1.1023    raeburn  2167:     if ($udom) {
                   2168:         my $uname = &get_domainconfiguser($udom);
                   2169:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2170:     }
                   2171:     return $result;
                   2172: }
                   2173: 
1.1023    raeburn  2174: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2175: sub del_dom {
1.1023    raeburn  2176:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2177:     if (ref($storearr) eq 'ARRAY') {
                   2178:         if (!$udom) {
                   2179:             $udom=$env{'user.domain'};
                   2180:         }
1.1023    raeburn  2181:         if ($udom) {
                   2182:             my $uname = &get_domainconfiguser($udom); 
                   2183:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2184:         }
                   2185:     }
                   2186: }
                   2187: 
1.1023    raeburn  2188: # ----------------------------------construct domainconfig user for a domain 
                   2189: sub get_domainconfiguser {
                   2190:     my ($udom) = @_;
                   2191:     return $udom.'-domainconfig';
                   2192: }
                   2193: 
1.837     raeburn  2194: sub retrieve_inst_usertypes {
                   2195:     my ($udom) = @_;
                   2196:     my (%returnhash,@order);
1.989     raeburn  2197:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2198:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2199:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2200:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2201:     } else {
                   2202:         if (defined(&domain($udom,'primary'))) {
                   2203:             my $uhome=&domain($udom,'primary');
                   2204:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2205:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2206:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2207:                 return (\%returnhash,\@order);
                   2208:             }
                   2209:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2210:             my @pairs=split(/\&/,$hashitems);
                   2211:             foreach my $item (@pairs) {
                   2212:                 my ($key,$value)=split(/=/,$item,2);
                   2213:                 $key = &unescape($key);
                   2214:                 next if ($key =~ /^error: 2 /);
                   2215:                 $returnhash{$key}=&thaw_unescape($value);
                   2216:             }
                   2217:             my @esc_order = split(/\&/,$orderitems);
                   2218:             foreach my $item (@esc_order) {
                   2219:                 push(@order,&unescape($item));
                   2220:             }
                   2221:         } else {
1.1256    raeburn  2222:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2223:         }
1.1256    raeburn  2224:         return (\%returnhash,\@order);
1.837     raeburn  2225:     }
                   2226: }
                   2227: 
1.868     raeburn  2228: sub is_domainimage {
                   2229:     my ($url) = @_;
1.1306    raeburn  2230:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2231:         if (&domain($1) ne '') {
                   2232:             return '1';
                   2233:         }
                   2234:     }
                   2235:     return;
                   2236: }
                   2237: 
1.899     raeburn  2238: sub inst_directory_query {
                   2239:     my ($srch) = @_;
                   2240:     my $udom = $srch->{'srchdomain'};
                   2241:     my %results;
                   2242:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2243:     my $outcome;
1.899     raeburn  2244:     if ($homeserver ne '') {
1.1357    raeburn  2245:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2246:             if ($srch->{'srchby'} eq 'email') {
                   2247:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
                   2248:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2249:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2250:                     (($major == 2) && ($minor < 12))) {
                   2251:                     return;
                   2252:                 }
                   2253:             }
                   2254:         }
1.904     albertel 2255: 	my $queryid=&reply("querysend:instdirsearch:".
                   2256: 			   &escape($srch->{'srchby'}).':'.
                   2257: 			   &escape($srch->{'srchterm'}).':'.
                   2258: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2259: 	my $host=&hostname($homeserver);
                   2260: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2261: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2262: 	    return;
                   2263: 	}
                   2264: 	my $response = &get_query_reply($queryid);
                   2265: 	my $maxtries = 5;
                   2266: 	my $tries = 1;
                   2267: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2268: 	    $response = &get_query_reply($queryid);
                   2269: 	    $tries ++;
                   2270: 	}
                   2271: 
                   2272:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2273:             if ($response eq 'unavailable') {
                   2274:                 $outcome = $response;
                   2275:             } else {
                   2276:                 $outcome = 'ok';
                   2277:                 my @matches = split(/\n/,$response);
                   2278:                 foreach my $match (@matches) {
                   2279:                     my ($key,$value) = split(/=/,$match);
                   2280:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2281:                 }
1.899     raeburn  2282:             }
                   2283:         }
                   2284:     }
1.909     raeburn  2285:     return ($outcome,%results);
1.899     raeburn  2286: }
                   2287: 
                   2288: sub usersearch {
                   2289:     my ($srch) = @_;
                   2290:     my $dom = $srch->{'srchdomain'};
                   2291:     my %results;
                   2292:     my %libserv = &all_library();
                   2293:     my $query = 'usersearch';
                   2294:     foreach my $tryserver (keys(%libserv)) {
                   2295:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2296:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2297:                 if ($srch->{'srchby'} eq 'email') {
                   2298:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
                   2299:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2300:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2301:                              (($major == 2) && ($minor < 12)));
                   2302:                 }
                   2303:             }
1.899     raeburn  2304:             my $host=&hostname($tryserver);
                   2305:             my $queryid=
1.911     raeburn  2306:                 &reply("querysend:".&escape($query).':'.
                   2307:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2308:                        &escape($srch->{'srchtype'}).':'.
                   2309:                        &escape($srch->{'srchterm'}),$tryserver);
                   2310:             if ($queryid !~/^\Q$host\E\_/) {
                   2311:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2312:                 next;
1.899     raeburn  2313:             }
                   2314:             my $reply = &get_query_reply($queryid);
                   2315:             my $maxtries = 1;
                   2316:             my $tries = 1;
                   2317:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2318:                 $reply = &get_query_reply($queryid);
                   2319:                 $tries ++;
                   2320:             }
                   2321:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2322:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2323:             } else {
1.911     raeburn  2324:                 my @matches;
                   2325:                 if ($reply =~ /\n/) {
                   2326:                     @matches = split(/\n/,$reply);
                   2327:                 } else {
                   2328:                     @matches = split(/\&/,$reply);
                   2329:                 }
1.899     raeburn  2330:                 foreach my $match (@matches) {
                   2331:                     my ($uname,$udom,%userhash);
1.911     raeburn  2332:                     foreach my $entry (split(/:/,$match)) {
                   2333:                         my ($key,$value) =
                   2334:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2335:                         $userhash{$key} = $value;
                   2336:                         if ($key eq 'username') {
                   2337:                             $uname = $value;
                   2338:                         } elsif ($key eq 'domain') {
                   2339:                             $udom = $value;
1.911     raeburn  2340:                         }
1.899     raeburn  2341:                     }
                   2342:                     $results{$uname.':'.$udom} = \%userhash;
                   2343:                 }
                   2344:             }
                   2345:         }
                   2346:     }
                   2347:     return %results;
                   2348: }
                   2349: 
1.912     raeburn  2350: sub get_instuser {
                   2351:     my ($udom,$uname,$id) = @_;
                   2352:     my $homeserver = &domain($udom,'primary');
                   2353:     my ($outcome,%results);
                   2354:     if ($homeserver ne '') {
                   2355:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2356:                            &escape($id).':'.&escape($udom),$homeserver);
                   2357:         my $host=&hostname($homeserver);
                   2358:         if ($queryid !~/^\Q$host\E\_/) {
                   2359:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2360:             return;
                   2361:         }
                   2362:         my $response = &get_query_reply($queryid);
                   2363:         my $maxtries = 5;
                   2364:         my $tries = 1;
                   2365:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2366:             $response = &get_query_reply($queryid);
                   2367:             $tries ++;
                   2368:         }
                   2369:         if (!&error($response) && $response ne 'refused') {
                   2370:             if ($response eq 'unavailable') {
                   2371:                 $outcome = $response;
                   2372:             } else {
                   2373:                 $outcome = 'ok';
                   2374:                 my @matches = split(/\n/,$response);
                   2375:                 foreach my $match (@matches) {
                   2376:                     my ($key,$value) = split(/=/,$match);
                   2377:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2378:                 }
                   2379:             }
                   2380:         }
                   2381:     }
                   2382:     my %userinfo;
                   2383:     if (ref($results{$uname}) eq 'HASH') {
                   2384:         %userinfo = %{$results{$uname}};
                   2385:     } 
                   2386:     return ($outcome,%userinfo);
                   2387: }
                   2388: 
1.1290    raeburn  2389: sub get_multiple_instusers {
                   2390:     my ($udom,$users,$caller) = @_;
                   2391:     my ($outcome,$results);
                   2392:     if (ref($users) eq 'HASH') {
                   2393:         my $count = keys(%{$users}); 
                   2394:         my $requested = &freeze_escape($users);
                   2395:         my $homeserver = &domain($udom,'primary');
                   2396:         if ($homeserver ne '') {
                   2397:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2398:             my $host=&hostname($homeserver);
                   2399:             if ($queryid !~/^\Q$host\E\_/) {
                   2400:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2401:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2402:                 return ($outcome,$results);
                   2403:             }
                   2404:             my $response = &get_query_reply($queryid);
                   2405:             my $maxtries = 5;
                   2406:             if ($count > 100) {
                   2407:                 $maxtries = 1+int($count/20);
                   2408:             }
                   2409:             my $tries = 1;
                   2410:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2411:                 $response = &get_query_reply($queryid);
                   2412:                 $tries ++;
                   2413:             }
                   2414:             if ($response eq '') {
                   2415:                 $results = {};
                   2416:                 foreach my $key (keys(%{$users})) {
                   2417:                     my ($uname,$id);
                   2418:                     if ($caller eq 'id') {
                   2419:                         $id = $key;
                   2420:                     } else {
                   2421:                         $uname = $key;
                   2422:                     }
                   2423:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2424:                     $outcome = $resp;
1.1290    raeburn  2425:                     if ($resp eq 'ok') {
                   2426:                         %{$results} = (%{$results}, %info);
                   2427:                     } else {
                   2428:                         last;
                   2429:                     }
                   2430:                 }
                   2431:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2432:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2433:                     $outcome = $response;
                   2434:                 } else {
1.1291    raeburn  2435:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2436:                     if ($outcome eq 'ok') {
                   2437:                         $results = &thaw_unescape($userdata); 
                   2438:                     }
                   2439:                 }
                   2440:             }
                   2441:         }
                   2442:     }
                   2443:     return ($outcome,$results);
                   2444: }
                   2445: 
1.912     raeburn  2446: sub inst_rulecheck {
1.923     raeburn  2447:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2448:     my %returnhash;
                   2449:     if ($udom ne '') {
                   2450:         if (ref($rules) eq 'ARRAY') {
                   2451:             @{$rules} = map {&escape($_);} (@{$rules});
                   2452:             my $rulestr = join(':',@{$rules});
                   2453:             my $homeserver=&domain($udom,'primary');
                   2454:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2455:                 my $response;
                   2456:                 if ($item eq 'username') {                
                   2457:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2458:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2459:                                               $homeserver));
1.923     raeburn  2460:                 } elsif ($item eq 'id') {
                   2461:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2462:                                               ':'.&escape($id).':'.$rulestr,
                   2463:                                               $homeserver));
1.945     raeburn  2464:                 } elsif ($item eq 'selfcreate') {
                   2465:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2466:                                                &escape($udom).':'.&escape($uname).
                   2467:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2468:                 }
1.912     raeburn  2469:                 if ($response ne 'refused') {
                   2470:                     my @pairs=split(/\&/,$response);
                   2471:                     foreach my $item (@pairs) {
                   2472:                         my ($key,$value)=split(/=/,$item,2);
                   2473:                         $key = &unescape($key);
                   2474:                         next if ($key =~ /^error: 2 /);
                   2475:                         $returnhash{$key}=&thaw_unescape($value);
                   2476:                     }
                   2477:                 }
                   2478:             }
                   2479:         }
                   2480:     }
                   2481:     return %returnhash;
                   2482: }
                   2483: 
                   2484: sub inst_userrules {
1.923     raeburn  2485:     my ($udom,$check) = @_;
1.912     raeburn  2486:     my (%ruleshash,@ruleorder);
                   2487:     if ($udom ne '') {
                   2488:         my $homeserver=&domain($udom,'primary');
                   2489:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2490:             my $response;
                   2491:             if ($check eq 'id') {
                   2492:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2493:                                  $homeserver);
1.943     raeburn  2494:             } elsif ($check eq 'email') {
                   2495:                 $response=&reply('instemailrules:'.&escape($udom),
                   2496:                                  $homeserver);
1.923     raeburn  2497:             } else {
                   2498:                 $response=&reply('instuserrules:'.&escape($udom),
                   2499:                                  $homeserver);
                   2500:             }
1.912     raeburn  2501:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2502:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2503:                 ($response ne 'no_such_host')) {
                   2504:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2505:                 my @pairs=split(/\&/,$hashitems);
                   2506:                 foreach my $item (@pairs) {
                   2507:                     my ($key,$value)=split(/=/,$item,2);
                   2508:                     $key = &unescape($key);
                   2509:                     next if ($key =~ /^error: 2 /);
                   2510:                     $ruleshash{$key}=&thaw_unescape($value);
                   2511:                 }
                   2512:                 my @esc_order = split(/\&/,$orderitems);
                   2513:                 foreach my $item (@esc_order) {
                   2514:                     push(@ruleorder,&unescape($item));
                   2515:                 }
                   2516:             }
                   2517:         }
                   2518:     }
                   2519:     return (\%ruleshash,\@ruleorder);
                   2520: }
                   2521: 
1.976     raeburn  2522: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2523: 
                   2524: sub get_domain_defaults {
1.1240    raeburn  2525:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2526:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2527:     my $cachetime = 60*60*24;
1.1240    raeburn  2528:     unless ($ignore_cache) {
                   2529:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2530:         if (defined($cached)) {
                   2531:             if (ref($result) eq 'HASH') {
                   2532:                 return %{$result};
                   2533:             }
1.943     raeburn  2534:         }
                   2535:     }
                   2536:     my %domdefaults;
                   2537:     my %domconfig =
1.989     raeburn  2538:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2539:                                   'requestcourses','inststatus',
1.1183    raeburn  2540:                                   'coursedefaults','usersessions',
1.1258    raeburn  2541:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2542:                                   'coursecategories','ssl','autoenroll',
1.1332    raeburn  2543:                                   'trust','helpsettings'],$domain);
1.1305    raeburn  2544:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2545:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2546:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2547:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2548:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2549:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2550:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2551:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2552:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2553:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2554:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2555:     } else {
                   2556:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2557:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2558:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2559:     }
1.976     raeburn  2560:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2561:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2562:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2563:         } else {
                   2564:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2565:         }
1.1177    raeburn  2566:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2567:         foreach my $item (@usertools) {
                   2568:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2569:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2570:             }
                   2571:         }
1.1229    raeburn  2572:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2573:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2574:         }
1.976     raeburn  2575:     }
1.985     raeburn  2576:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2577:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2578:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2579:         }
                   2580:     }
1.1183    raeburn  2581:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2582:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2583:     }
1.989     raeburn  2584:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2585:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2586:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2587:         }
                   2588:     }
1.1047    raeburn  2589:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2590:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2591:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2592:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2593:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2594:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2595:         }
1.1254    raeburn  2596:         foreach my $type (@coursetypes) {
                   2597:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2598:                 unless ($type eq 'community') {
                   2599:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2600:                 }
                   2601:             }
                   2602:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2603:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2604:             }
1.1277    raeburn  2605:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2606:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2607:                     $domdefaults{$type.'postsubtimeout'} = 
                   2608:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2609:                 }
                   2610:             }
1.1230    raeburn  2611:         }
1.1286    raeburn  2612:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2613:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2614:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2615:                 if (@clonecodes) {
                   2616:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2617:                 }
                   2618:             }
                   2619:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2620:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2621:         }
1.1356    raeburn  2622:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2623:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2624:         } 
1.1047    raeburn  2625:     }
1.1073    raeburn  2626:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2627:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2628:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2629:         }
                   2630:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2631:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2632:         }
1.1279    raeburn  2633:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2634:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2635:         }
1.1073    raeburn  2636:     }
1.1254    raeburn  2637:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2638:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2639:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2640:                             'approval','limit');
                   2641:             foreach my $type (@coursetypes) {
                   2642:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2643:                     my @mgrdc = ();
                   2644:                     foreach my $item (@settings) {
                   2645:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2646:                             push(@mgrdc,$item);
                   2647:                         }
                   2648:                     }
                   2649:                     if (@mgrdc) {
                   2650:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2651:                     }
                   2652:                 }
                   2653:             }
                   2654:         }
                   2655:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2656:             foreach my $type (@coursetypes) {
                   2657:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2658:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2659:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2660:                     }
                   2661:                 }
                   2662:             }
                   2663:         }
                   2664:     }
1.1258    raeburn  2665:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2666:         $domdefaults{'catauth'} = 'std';
                   2667:         $domdefaults{'catunauth'} = 'std';
                   2668:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2669:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2670:         }
                   2671:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2672:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2673:         }
                   2674:     }
1.1315    raeburn  2675:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2676:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2677:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2678:         }
1.1338    raeburn  2679:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2680:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2681:         }
                   2682:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2683:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2684:         }
                   2685:     }
1.1320    raeburn  2686:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2687:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2688:         foreach my $prefix (@prefixes) {
                   2689:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2690:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2691:             }
                   2692:         }
                   2693:     }
1.1314    raeburn  2694:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2695:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2696:     }
1.1332    raeburn  2697:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2698:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2699:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2700:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2701:         }
                   2702:     }
1.1219    raeburn  2703:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2704:     return %domdefaults;
                   2705: }
                   2706: 
1.1311    raeburn  2707: sub course_portal_url {
                   2708:     my ($cnum,$cdom) = @_;
                   2709:     my $chome = &homeserver($cnum,$cdom);
                   2710:     my $hostname = &hostname($chome);
                   2711:     my $protocol = $protocol{$chome};
                   2712:     $protocol = 'http' if ($protocol ne 'https');
                   2713:     my %domdefaults = &get_domain_defaults($cdom);
                   2714:     my $firsturl;
                   2715:     if ($domdefaults{'portal_def'}) {
                   2716:         $firsturl = $domdefaults{'portal_def'};
                   2717:     } else {
                   2718:         $firsturl = $protocol.'://'.$hostname;
                   2719:     }
                   2720:     return $firsturl;
                   2721: }
                   2722: 
1.344     www      2723: # --------------------------------------------------- Assign a key to a student
                   2724: 
                   2725: sub assign_access_key {
1.364     www      2726: #
                   2727: # a valid key looks like uname:udom#comments
                   2728: # comments are being appended
                   2729: #
1.498     www      2730:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2731:     $kdom=
1.620     albertel 2732:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2733:     $knum=
1.620     albertel 2734:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2735:     $cdom=
1.620     albertel 2736:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2737:     $cnum=
1.620     albertel 2738:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2739:     $udom=$env{'user.name'} unless (defined($udom));
                   2740:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2741:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2742:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2743:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2744:                                                   # assigned to this person
                   2745:                                                   # - this should not happen,
1.345     www      2746:                                                   # unless something went wrong
                   2747:                                                   # the first time around
                   2748: # ready to assign
1.364     www      2749:         $logentry=$1.'; '.$logentry;
1.496     www      2750:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2751:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2752: # key now belongs to user
1.346     www      2753: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2754:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2755:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2756:                 return 'ok';
                   2757:             } else {
                   2758:                 return 
                   2759:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2760: 	    }
                   2761:         } else {
                   2762:             return 'error: Could not assign key, try again later.';
                   2763:         }
1.364     www      2764:     } elsif (!$existing{$ckey}) {
1.345     www      2765: # the key does not exist
                   2766: 	return 'error: The key does not exist';
                   2767:     } else {
                   2768: # the key is somebody else's
                   2769: 	return 'error: The key is already in use';
                   2770:     }
1.344     www      2771: }
                   2772: 
1.364     www      2773: # ------------------------------------------ put an additional comment on a key
                   2774: 
                   2775: sub comment_access_key {
                   2776: #
                   2777: # a valid key looks like uname:udom#comments
                   2778: # comments are being appended
                   2779: #
                   2780:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2781:     $cdom=
1.620     albertel 2782:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2783:     $cnum=
1.620     albertel 2784:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2785:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2786:     if ($existing{$ckey}) {
                   2787:         $existing{$ckey}.='; '.$logentry;
                   2788: # ready to assign
1.367     www      2789:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2790:                                                  $cdom,$cnum) eq 'ok') {
                   2791: 	    return 'ok';
                   2792:         } else {
                   2793: 	    return 'error: Count not store comment.';
                   2794:         }
                   2795:     } else {
                   2796: # the key does not exist
                   2797: 	return 'error: The key does not exist';
                   2798:     }
                   2799: }
                   2800: 
1.344     www      2801: # ------------------------------------------------------ Generate a set of keys
                   2802: 
                   2803: sub generate_access_keys {
1.364     www      2804:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2805:     $cdom=
1.620     albertel 2806:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2807:     $cnum=
1.620     albertel 2808:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2809:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2810:     unless (($cdom) && ($cnum)) { return 0; }
                   2811:     if ($number>10000) { return 0; }
                   2812:     sleep(2); # make sure don't get same seed twice
                   2813:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2814:     my $total=0;
                   2815:     for (my $i=1;$i<=$number;$i++) {
                   2816:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2817:                   sprintf("%lx",int(100000*rand)).'-'.
                   2818:                   sprintf("%lx",int(100000*rand));
                   2819:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2820:        $newkey=~s/0/h/g; # and also 0 and O
                   2821:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2822:        if ($existing{$newkey}) {
                   2823:            $i--;
                   2824:        } else {
1.364     www      2825: 	  if (&put('accesskeys',
                   2826:               { $newkey => '# generated '.localtime().
1.620     albertel 2827:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2828:                            '; '.$logentry },
                   2829: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2830:               $total++;
                   2831: 	  }
                   2832:        }
                   2833:     }
1.620     albertel 2834:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2835:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2836:     return $total;
                   2837: }
                   2838: 
                   2839: # ------------------------------------------------------- Validate an accesskey
                   2840: 
                   2841: sub validate_access_key {
                   2842:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2843:     $cdom=
1.620     albertel 2844:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2845:     $cnum=
1.620     albertel 2846:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2847:     $udom=$env{'user.domain'} unless (defined($udom));
                   2848:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2849:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2850:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2851: }
                   2852: 
                   2853: # ------------------------------------- Find the section of student in a course
1.652     albertel 2854: sub devalidate_getsection_cache {
                   2855:     my ($udom,$unam,$courseid)=@_;
                   2856:     my $hashid="$udom:$unam:$courseid";
                   2857:     &devalidate_cache_new('getsection',$hashid);
                   2858: }
1.298     matthew  2859: 
1.815     albertel 2860: sub courseid_to_courseurl {
                   2861:     my ($courseid) = @_;
                   2862:     #already url style courseid
                   2863:     return $courseid if ($courseid =~ m{^/});
                   2864: 
                   2865:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2866: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2867: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2868: 	return "/$cdom/$cnum";
                   2869:     }
                   2870: 
                   2871:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2872:     if (exists($courseinfo{'num'})) {
                   2873: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2874:     }
                   2875: 
                   2876:     return undef;
                   2877: }
                   2878: 
1.298     matthew  2879: sub getsection {
                   2880:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2881:     my $cachetime=1800;
1.551     albertel 2882: 
                   2883:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2884:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2885:     if (defined($cached)) { return $result; }
                   2886: 
1.298     matthew  2887:     my %Pending; 
                   2888:     my %Expired;
                   2889:     #
                   2890:     # Each role can either have not started yet (pending), be active, 
                   2891:     #    or have expired.
                   2892:     #
                   2893:     # If there is an active role, we are done.
                   2894:     #
                   2895:     # If there is more than one role which has not started yet, 
                   2896:     #     choose the one which will start sooner
                   2897:     # If there is one role which has not started yet, return it.
                   2898:     #
                   2899:     # If there is more than one expired role, choose the one which ended last.
                   2900:     # If there is a role which has expired, return it.
                   2901:     #
1.815     albertel 2902:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2903:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2904:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2905:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2906:         my $section=$1;
                   2907:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2908:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2909:         my $now=time;
1.548     albertel 2910:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2911:             $Expired{$end}=$section;
                   2912:             next;
                   2913:         }
1.548     albertel 2914:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2915:             $Pending{$start}=$section;
                   2916:             next;
                   2917:         }
1.599     albertel 2918:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2919:     }
                   2920:     #
                   2921:     # Presumedly there will be few matching roles from the above
                   2922:     # loop and the sorting time will be negligible.
                   2923:     if (scalar(keys(%Pending))) {
                   2924:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2925:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2926:     } 
                   2927:     if (scalar(keys(%Expired))) {
                   2928:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2929:         my $time = pop(@sorted);
1.599     albertel 2930:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2931:     }
1.599     albertel 2932:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2933: }
1.70      www      2934: 
1.599     albertel 2935: sub save_cache {
                   2936:     &purge_remembered();
1.722     albertel 2937:     #&Apache::loncommon::validate_page();
1.620     albertel 2938:     undef(%env);
1.780     albertel 2939:     undef($env_loaded);
1.599     albertel 2940: }
1.452     albertel 2941: 
1.599     albertel 2942: my $to_remember=-1;
                   2943: my %remembered;
                   2944: my %accessed;
                   2945: my $kicks=0;
                   2946: my $hits=0;
1.849     albertel 2947: sub make_key {
                   2948:     my ($name,$id) = @_;
1.872     albertel 2949:     if (length($id) > 65 
                   2950: 	&& length(&escape($id)) > 200) {
                   2951: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2952:     }
1.849     albertel 2953:     return &escape($name.':'.$id);
                   2954: }
                   2955: 
1.599     albertel 2956: sub devalidate_cache_new {
                   2957:     my ($name,$id,$debug) = @_;
                   2958:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  2959:     my $remembered_id=$name.':'.$id;
1.849     albertel 2960:     $id=&make_key($name,$id);
1.599     albertel 2961:     $memcache->delete($id);
1.1319    damieng  2962:     delete($remembered{$remembered_id});
                   2963:     delete($accessed{$remembered_id});
1.599     albertel 2964: }
                   2965: 
                   2966: sub is_cached_new {
                   2967:     my ($name,$id,$debug) = @_;
1.1319    damieng  2968:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   2969:     if (exists($remembered{$remembered_id})) {
                   2970: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2971: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2972: 	$hits++;
1.1319    damieng  2973: 	return ($remembered{$remembered_id},1);
1.599     albertel 2974:     }
1.1319    damieng  2975:     $id=&make_key($name,$id);
1.599     albertel 2976:     my $value = $memcache->get($id);
                   2977:     if (!(defined($value))) {
                   2978: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2979: 	return (undef,undef);
1.416     albertel 2980:     }
1.599     albertel 2981:     if ($value eq '__undef__') {
                   2982: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2983: 	$value=undef;
                   2984:     }
1.1319    damieng  2985:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2986:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2987:     return ($value,1);
                   2988: }
                   2989: 
                   2990: sub do_cache_new {
                   2991:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  2992:     my $remembered_id=$name.':'.$id;
1.849     albertel 2993:     $id=&make_key($name,$id);
1.599     albertel 2994:     my $setvalue=$value;
                   2995:     if (!defined($setvalue)) {
                   2996: 	$setvalue='__undef__';
                   2997:     }
1.623     albertel 2998:     if (!defined($time) ) {
                   2999: 	$time=600;
                   3000:     }
1.599     albertel 3001:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 3002:     my $result = $memcache->set($id,$setvalue,$time);
                   3003:     if (! $result) {
1.872     albertel 3004: 	&logthis("caching of id -> $id  failed");
1.910     albertel 3005: 	$memcache->disconnect_all();
1.872     albertel 3006:     }
1.600     albertel 3007:     # need to make a copy of $value
1.1319    damieng  3008:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3009:     return $value;
                   3010: }
                   3011: 
                   3012: sub make_room {
1.1319    damieng  3013:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3014: 
1.1319    damieng  3015:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3016:                                     : $value;
1.599     albertel 3017:     if ($to_remember<0) { return; }
1.1319    damieng  3018:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3019:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3020:     my $to_kick;
                   3021:     my $max_time=0;
                   3022:     foreach my $other (keys(%accessed)) {
                   3023: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3024: 	    $to_kick=$other;
                   3025: 	    $max_time=&tv_interval($accessed{$other});
                   3026: 	}
                   3027:     }
                   3028:     delete($remembered{$to_kick});
                   3029:     delete($accessed{$to_kick});
                   3030:     $kicks++;
                   3031:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3032:     return;
                   3033: }
                   3034: 
1.599     albertel 3035: sub purge_remembered {
1.604     albertel 3036:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3037:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3038:     undef(%remembered);
                   3039:     undef(%accessed);
1.428     albertel 3040: }
1.70      www      3041: # ------------------------------------- Read an entry from a user's environment
                   3042: 
                   3043: sub userenvironment {
                   3044:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3045:     my $items;
                   3046:     foreach my $item (@what) {
                   3047:         $items.=&escape($item).'&';
                   3048:     }
                   3049:     $items=~s/\&$//;
1.70      www      3050:     my %returnhash=();
1.1009    raeburn  3051:     my $uhome = &homeserver($unam,$udom);
                   3052:     unless ($uhome eq 'no_host') {
                   3053:         my @answer=split(/\&/, 
                   3054:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3055:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3056:             return %returnhash;
                   3057:         }
1.1009    raeburn  3058:         my $i;
                   3059:         for ($i=0;$i<=$#what;$i++) {
                   3060: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3061:         }
1.70      www      3062:     }
                   3063:     return %returnhash;
1.1       albertel 3064: }
                   3065: 
1.617     albertel 3066: # ---------------------------------------------------------- Get a studentphoto
                   3067: sub studentphoto {
                   3068:     my ($udom,$unam,$ext) = @_;
                   3069:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3070:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3071:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3072:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3073:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3074:             } else {
                   3075:                 my ($result,$perm_reqd)=
1.707     albertel 3076: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3077:                 if ($result eq 'ok') {
                   3078:                     if (!($perm_reqd eq 'yes')) {
                   3079:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3080:                     }
                   3081:                 }
                   3082:             }
                   3083:         }
                   3084:     } else {
                   3085:         my ($result,$perm_reqd) = 
1.707     albertel 3086: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3087:         if ($result eq 'ok') {
                   3088:             if (!($perm_reqd eq 'yes')) {
                   3089:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3090:             }
                   3091:         }
                   3092:     }
                   3093:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3094: }
                   3095: 
                   3096: sub retrievestudentphoto {
                   3097:     my ($udom,$unam,$ext,$type) = @_;
                   3098:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3099:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3100:     if ($ret eq 'ok') {
                   3101:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3102:         if ($type eq 'thumbnail') {
                   3103:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3104:         }
                   3105:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3106:         return $tokenurl;
                   3107:     } else {
                   3108:         if ($type eq 'thumbnail') {
                   3109:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3110:         } else { 
                   3111:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3112:         }
1.617     albertel 3113:     }
                   3114: }
                   3115: 
1.263     www      3116: # -------------------------------------------------------------------- New chat
                   3117: 
                   3118: sub chatsend {
1.724     raeburn  3119:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3120:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3121:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3122:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3123:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3124: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3125: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3126: }
                   3127: 
                   3128: # ------------------------------------------ Find current version of a resource
                   3129: 
                   3130: sub getversion {
                   3131:     my $fname=&clutter(shift);
1.1189    raeburn  3132:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3133:     return &currentversion(&filelocation('',$fname));
                   3134: }
                   3135: 
                   3136: sub currentversion {
                   3137:     my $fname=shift;
                   3138:     my $author=$fname;
                   3139:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3140:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3141:     my $home=&homeserver($uname,$udom);
1.292     www      3142:     if ($home eq 'no_host') { 
                   3143:         return -1; 
                   3144:     }
1.1112    www      3145:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3146:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3147: 	return -1;
                   3148:     }
1.1112    www      3149:     return $answer;
1.263     www      3150: }
                   3151: 
1.1111    www      3152: #
                   3153: # Return special version number of resource if set by override, empty otherwise
                   3154: #
                   3155: sub usedversion {
                   3156:     my $fname=shift;
                   3157:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3158:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3159:     if ($urlversion) { return $urlversion; }
                   3160:     return '';
                   3161: }
                   3162: 
1.1       albertel 3163: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3164: 
1.1       albertel 3165: sub subscribe {
                   3166:     my $fname=shift;
1.761     raeburn  3167:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3168:     $fname=~s/[\n\r]//g;
1.1       albertel 3169:     my $author=$fname;
                   3170:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3171:     my ($udom,$uname)=split(/\//,$author);
                   3172:     my $home=homeserver($uname,$udom);
1.335     albertel 3173:     if ($home eq 'no_host') {
                   3174:         return 'not_found';
1.1       albertel 3175:     }
                   3176:     my $answer=reply("sub:$fname",$home);
1.64      www      3177:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3178: 	$answer.=' by '.$home;
                   3179:     }
1.1       albertel 3180:     return $answer;
                   3181: }
                   3182:     
1.8       www      3183: # -------------------------------------------------------------- Replicate file
                   3184: 
                   3185: sub repcopy {
                   3186:     my $filename=shift;
1.23      www      3187:     $filename=~s/\/+/\//g;
1.1142    raeburn  3188:     my $londocroot = $perlvar{'lonDocRoot'};
                   3189:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3190:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3191:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3192: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3193: 	return &repcopy_userfile($filename);
                   3194:     }
1.532     albertel 3195:     $filename=~s/[\n\r]//g;
1.8       www      3196:     my $transname="$filename.in.transfer";
1.828     www      3197: # FIXME: this should flock
1.607     raeburn  3198:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3199:     my $remoteurl=subscribe($filename);
1.64      www      3200:     if ($remoteurl =~ /^con_lost by/) {
                   3201: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3202:            return 'unavailable';
1.8       www      3203:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3204: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3205: 	   return 'not_found';
1.64      www      3206:     } elsif ($remoteurl =~ /^rejected by/) {
                   3207: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3208:            return 'forbidden';
1.20      www      3209:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3210:            return 'ok';
1.8       www      3211:     } else {
1.290     www      3212:         my $author=$filename;
                   3213:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3214:         my ($udom,$uname)=split(/\//,$author);
                   3215:         my $home=homeserver($uname,$udom);
                   3216:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3217:            my @parts=split(/\//,$filename);
                   3218:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3219:            if ($path ne "$londocroot/res") {
1.8       www      3220:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3221: 	       return 'bad_request';
1.8       www      3222:            }
                   3223:            my $count;
                   3224:            for ($count=5;$count<$#parts;$count++) {
                   3225:                $path.="/$parts[$count]";
                   3226:                if ((-e $path)!=1) {
                   3227: 		   mkdir($path,0777);
                   3228:                }
                   3229:            }
                   3230:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3231:            my $response;
                   3232:            if ($remoteurl =~ m{/raw/}) {
                   3233:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3234:            } else {
                   3235:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3236:            }
1.8       www      3237:            if ($response->is_error()) {
                   3238: 	       unlink($transname);
                   3239:                my $message=$response->status_line;
1.672     albertel 3240:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3241:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3242:                return 'unavailable';
1.8       www      3243:            } else {
1.16      www      3244: 	       if ($remoteurl!~/\.meta$/) {
                   3245:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3246:                   my $mresponse;
                   3247:                   if ($remoteurl =~ m{/raw/}) {
                   3248:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3249:                   } else {
                   3250:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3251:                   }
1.16      www      3252:                   if ($mresponse->is_error()) {
                   3253: 		      unlink($filename.'.meta');
                   3254:                       &logthis(
1.672     albertel 3255:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3256:                   }
                   3257: 	       }
1.8       www      3258:                rename($transname,$filename);
1.607     raeburn  3259:                return 'ok';
1.8       www      3260:            }
1.290     www      3261:        }
1.8       www      3262:     }
1.330     www      3263: }
                   3264: 
                   3265: # ------------------------------------------------ Get server side include body
                   3266: sub ssi_body {
1.381     albertel 3267:     my ($filelink,%form)=@_;
1.606     matthew  3268:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3269:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3270:     }
1.953     www      3271:     my $output='';
                   3272:     my $response;
1.980     raeburn  3273:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3274:        ($output,$response)=&externalssi($filelink);
1.953     www      3275:     } else {
1.1004    droeschl 3276:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3277:        $filelink .= 'inhibitmenu=yes';
1.953     www      3278:        ($output,$response)=&ssi($filelink,%form);
                   3279:     }
1.778     albertel 3280:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3281:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3282:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3283:     if (wantarray) {
                   3284:         return ($output, $response);
                   3285:     } else {
                   3286:         return $output;
                   3287:     }
1.8       www      3288: }
                   3289: 
1.15      www      3290: # --------------------------------------------------------- Server Side Include
                   3291: 
1.782     albertel 3292: sub absolute_url {
                   3293:     my ($host_name) = @_;
                   3294:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3295:     if ($host_name eq '') {
                   3296: 	$host_name = $ENV{'SERVER_NAME'};
                   3297:     }
                   3298:     return $protocol.$host_name;
                   3299: }
                   3300: 
1.942     foxr     3301: #
                   3302: #   Server side include.
                   3303: # Parameters:
                   3304: #  fn     Possibly encrypted resource name/id.
                   3305: #  form   Hash that describes how the rendering should be done
                   3306: #         and other things.
1.944     foxr     3307: # Returns:
1.950     raeburn  3308: #   Scalar context: The content of the response.
                   3309: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3310: #     
1.15      www      3311: sub ssi {
                   3312: 
1.944     foxr     3313:     my ($fn,%form)=@_;
1.23      www      3314:     my $request;
1.711     albertel 3315: 
                   3316:     $form{'no_update_last_known'}=1;
1.895     albertel 3317:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3318:     if (%form) {
1.782     albertel 3319:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3320:       $request->content(join('&',map { 
                   3321:             my $name = escape($_);
                   3322:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3323:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3324:             : &escape($form{$_}) );    
                   3325:         } keys(%form)));
1.23      www      3326:     } else {
1.782     albertel 3327:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3328:     }
                   3329: 
1.15      www      3330:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3331:     my $lonhost = $perlvar{'lonHostID'};
1.1385    raeburn  3332:     my $islocal;
                   3333:     if (($env{'request.course.id'}) &&
                   3334:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3335:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3336:         ($form{'grade_symb'} ne '') &&
                   3337:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3338:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
                   3339:         $islocal = 1;
                   3340:     }
1.1384    raeburn  3341:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
1.1385    raeburn  3342:                                                 '','','',$islocal);
1.1182    foxr     3343: 
1.944     foxr     3344:     if (wantarray) {
1.1345    raeburn  3345: 	return ($response->content, $response);
1.944     foxr     3346:     } else {
1.1345    raeburn  3347: 	return $response->content;
1.942     foxr     3348:     }
1.324     www      3349: }
                   3350: 
                   3351: sub externalssi {
                   3352:     my ($url)=@_;
                   3353:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3354:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3355:     if (wantarray) {
                   3356:         return ($response->content, $response);
                   3357:     } else {
                   3358:         return $response->content;
                   3359:     }
1.15      www      3360: }
1.254     www      3361: 
1.1354    raeburn  3362: 
                   3363: # If the local copy of a replicated resource is outdated, trigger a  
                   3364: # connection from the homeserver to flush the delayed queue. If no update 
                   3365: # happens, remove local copies of outdated resource (and corresponding
                   3366: # metadata file).
                   3367: 
1.1352    raeburn  3368: sub remove_stale_resfile {
                   3369:     my ($url) = @_;
1.1354    raeburn  3370:     my $removed;
1.1352    raeburn  3371:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3372:         my $audom = $1;
                   3373:         my $auname = $2;
1.1353    raeburn  3374:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3375:             my $homeserver = &homeserver($auname,$audom);
                   3376:             unless (($homeserver eq 'no_host') ||
                   3377:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3378:                 my $fname = &filelocation('',$url);
                   3379:                 if (-e $fname) {
                   3380:                     my $hostname = &hostname($homeserver);
                   3381:                     if ($hostname) {
1.1397    raeburn  3382:                         my $protocol = $protocol{$homeserver};
                   3383:                         $protocol = 'http' if ($protocol ne 'https');
1.1352    raeburn  3384:                         my $uri = &declutter($url);
                   3385:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3386:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3387:                         if ($response->is_success()) {
                   3388:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3389:                             my $locmodtime = (stat($fname))[9];
                   3390:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3391:                                 my $stale;
                   3392:                                 my $answer = &reply('pong',$homeserver);
                   3393:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3394:                                     sleep(0.2);
                   3395:                                     $locmodtime = (stat($fname))[9];
                   3396:                                     if ($locmodtime < $remmodtime) {
                   3397:                                         my $posstransfer = $fname.'.in.transfer';
                   3398:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3399:                                             $removed = 1;
                   3400:                                         } else {
                   3401:                                             $stale = 1;
                   3402:                                         }
                   3403:                                     } else {
                   3404:                                         $removed = 1;
                   3405:                                     }
                   3406:                                 } else {
                   3407:                                     $stale = 1;
                   3408:                                 }
                   3409:                                 if ($stale) {
                   3410:                                     unlink($fname);
                   3411:                                     if ($uri!~/\.meta$/) {
                   3412:                                         unlink($fname.'.meta');
                   3413:                                     }
                   3414:                                     &reply("unsub:$fname",$homeserver);
                   3415:                                     $removed = 1;
1.1352    raeburn  3416:                                 }
                   3417:                             }
                   3418:                         }
                   3419:                     }
                   3420:                 }
                   3421:             }
                   3422:         }
                   3423:     }
1.1354    raeburn  3424:     return $removed;
1.1352    raeburn  3425: }
                   3426: 
1.492     albertel 3427: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3428: 
                   3429: sub allowuploaded {
                   3430:     my ($srcurl,$url)=@_;
                   3431:     $url=&clutter(&declutter($url));
                   3432:     my $dir=$url;
                   3433:     $dir=~s/\/[^\/]+$//;
                   3434:     my %httpref=();
                   3435:     my $httpurl=&hreflocation('',$url);
                   3436:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3437:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3438: }
1.477     raeburn  3439: 
1.1193    raeburn  3440: #
                   3441: # Determine if the current user should be able to edit a particular resource,
                   3442: # when viewing in course context.
                   3443: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3444: #     Functions.
                   3445: # (b) When displaying folder contents in course editor, used to determine if
                   3446: #     "Edit" link will be displayed alongside resource.
                   3447: #
1.1196    raeburn  3448: #  input: six args -- filename (decluttered), course number, course domain,
                   3449: #                   url, symb (if registered) and group (if this is a group
                   3450: #                   item -- e.g., bulletin board, group page etc.).
                   3451: #  output: array of five scalars -- 
1.1193    raeburn  3452: #          $cfile -- url for file editing if editable on current server
                   3453: #          $home -- homeserver of resource (i.e., for author if published,
                   3454: #                                           or course if uploaded.).
                   3455: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3456: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3457: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3458: #
                   3459: 
                   3460: sub can_edit_resource {
1.1194    raeburn  3461:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3462:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3463: #
                   3464: # For aboutme pages user can only edit his/her own.
                   3465: #
1.1199    raeburn  3466:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3467:         my ($sdom,$sname) = ($1,$2);
                   3468:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3469:             $home = $env{'user.home'};
                   3470:             $cfile = $resurl;
                   3471:             if ($env{'form.forceedit'}) {
                   3472:                 $forceview = 1;
                   3473:             } else {
                   3474:                 $forceedit = 1;
                   3475:             }
                   3476:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3477:         } else {
                   3478:             return;
                   3479:         }
                   3480:     }
                   3481: 
                   3482:     if ($env{'request.course.id'}) {
                   3483:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3484:         if ($group ne '') {
                   3485: # if this is a group homepage or group bulletin board, check group privs
                   3486:             my $allowed = 0;
1.1197    raeburn  3487:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3488:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3489:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3490:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3491:                     $allowed = 1;
                   3492:                 }
1.1197    raeburn  3493:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3494:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3495:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3496:                     $allowed = 1;
                   3497:                 }
                   3498:             }
                   3499:             if ($allowed) {
                   3500:                 $home=&homeserver($cnum,$cdom);
                   3501:                 if ($env{'form.forceedit'}) {
                   3502:                     $forceview = 1;
                   3503:                 } else {
                   3504:                     $forceedit = 1;
                   3505:                 }
                   3506:                 $cfile = $resurl;
                   3507:             } else {
                   3508:                 return;
                   3509:             }
                   3510:         } else {
1.1208    raeburn  3511:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3512:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3513:                     return;
                   3514:                 }
                   3515:             } elsif (!$crsedit) {
1.1194    raeburn  3516: #
                   3517: # No edit allowed where CC has switched to student role.
                   3518: #
                   3519:                 return;
                   3520:             }
                   3521:         }
                   3522:     }
                   3523: 
1.1193    raeburn  3524:     if ($file ne '') {
                   3525:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3526:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3527:                 $uploaded = 1;
                   3528:                 $incourse = 1;
1.1193    raeburn  3529:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3530:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3531:                     if ($env{'form.forceedit'}) {
                   3532:                         $forceview = 1;
                   3533:                     } else {
                   3534:                         $forceedit = 1;
                   3535:                     }
1.1194    raeburn  3536:                 }
                   3537:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3538:                 $incourse = 1;
                   3539:                 if ($env{'form.forceedit'}) {
                   3540:                     $forceview = 1;
                   3541:                 } else {
                   3542:                     $forceedit = 1;
                   3543:                 }
                   3544:                 $cfile = $resurl;
                   3545:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3546:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3547:                     $incourse = 1;
                   3548:                     if ($env{'form.forceedit'}) {
                   3549:                         $forceview = 1;
                   3550:                     } else {
                   3551:                         $forceedit = 1;
                   3552:                     }
                   3553:                     $cfile = $resurl;
1.1199    raeburn  3554:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3555:                     $incourse = 1;
                   3556:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3557:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3558:                     $incourse = 1;
1.1199    raeburn  3559:                     if ($env{'form.forceedit'}) {
                   3560:                         $forceview = 1;
                   3561:                     } else {
                   3562:                         $forceedit = 1;
                   3563:                     }
                   3564:                     $cfile = $resurl;
1.1343    raeburn  3565:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3566:                     $incourse = 1;
                   3567:                     if ($env{'form.forceedit'}) {
                   3568:                         $forceview = 1;
                   3569:                     } else {
                   3570:                         $forceedit = 1;
                   3571:                     }
                   3572:                     $cfile = $resurl;
1.1208    raeburn  3573:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3574:                     $incourse = 1;
                   3575:                     if ($env{'form.forceedit'}) {
                   3576:                         $forceview = 1;
                   3577:                     } else {
                   3578:                         $forceedit = 1;
                   3579:                     }
                   3580:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3581:                 }
                   3582:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3583:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3584:                 if (&is_on_map($template)) { 
                   3585:                     $incourse = 1;
                   3586:                     $forceview = 1;
                   3587:                     $cfile = $template;
1.1193    raeburn  3588:                 }
1.1199    raeburn  3589:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3590:                     $incourse = 1;
                   3591:                     if ($env{'form.forceedit'}) {
                   3592:                         $forceview = 1;
                   3593:                     } else {
                   3594:                         $forceedit = 1;
                   3595:                     }
                   3596:                     $cfile = $resurl;
1.1343    raeburn  3597:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3598:                 $incourse = 1;
                   3599:                 if ($env{'form.forceedit'}) {
                   3600:                     $forceview = 1;
                   3601:                 } else {
                   3602:                     $forceedit = 1;
                   3603:                 }
                   3604:                 $cfile = $resurl;
1.1199    raeburn  3605:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3606:                 $incourse = 1;
                   3607:                 $forceview = 1;
                   3608:                 if ($symb) {
                   3609:                     my ($map,$id,$res)=&decode_symb($symb);
                   3610:                     $env{'request.symb'} = $symb;
                   3611:                     $cfile = &clutter($res);
                   3612:                 } else {
                   3613:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3614:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3615:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3616:                         $cfile = '/adm/wrapper'.$escfile;
                   3617:                     } else {
                   3618:                         $escfile =~ s{^http://}{};
                   3619:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3620:                     }
1.1199    raeburn  3621:                 }
1.1234    raeburn  3622:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3623:                 if ($env{'form.forceedit'}) {
                   3624:                     $forceview = 1;
                   3625:                 } else {
                   3626:                     $forceedit = 1;
                   3627:                 }
                   3628:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3629:             }
                   3630:         }
1.1194    raeburn  3631:         if ($uploaded || $incourse) {
                   3632:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3633:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3634:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3635:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3636:             # Check that the user has permission to edit this resource
                   3637:             my $setpriv = 1;
                   3638:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3639:             if (defined($cfudom)) {
                   3640:                 $home=&homeserver($cfuname,$cfudom);
                   3641:                 $cfile=$file;
                   3642:             }
                   3643:         }
1.1194    raeburn  3644:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3645:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3646:             my @ids=&current_machine_ids();
                   3647:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3648:                 $switchserver=1;
                   3649:             }
                   3650:         }
                   3651:     }
1.1194    raeburn  3652:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3653: }
                   3654: 
                   3655: sub is_course_upload {
                   3656:     my ($file,$cnum,$cdom) = @_;
                   3657:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3658:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3659:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3660:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3661:         return 1;
                   3662:     }
                   3663:     return;
                   3664: }
                   3665: 
1.1194    raeburn  3666: sub in_course {
1.1195    raeburn  3667:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3668:     if ($hideprivileged) {
                   3669:         my $skipuser;
1.1219    raeburn  3670:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3671:         my @possdoms = ($cdom);  
                   3672:         if ($coursehash{'checkforpriv'}) { 
                   3673:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3674:         }
                   3675:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3676:             $skipuser = 1;
                   3677:             if ($coursehash{'nothideprivileged'}) {
                   3678:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3679:                     my $user;
                   3680:                     if ($item =~ /:/) {
                   3681:                         $user = $item;
                   3682:                     } else {
                   3683:                         $user = join(':',split(/[\@]/,$item));
                   3684:                     }
                   3685:                     if ($user eq $uname.':'.$udom) {
                   3686:                         undef($skipuser);
                   3687:                         last;
                   3688:                     }
                   3689:                 }
                   3690:             }
                   3691:             if ($skipuser) {
                   3692:                 return 0;
                   3693:             }
                   3694:         }
                   3695:     }
1.1194    raeburn  3696:     $type ||= 'any';
                   3697:     if (!defined($cdom) || !defined($cnum)) {
                   3698:         my $cid  = $env{'request.course.id'};
                   3699:         $cdom = $env{'course.'.$cid.'.domain'};
                   3700:         $cnum = $env{'course.'.$cid.'.num'};
                   3701:     }
                   3702:     my $typesref;
1.1195    raeburn  3703:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3704:         $typesref = ['active','previous','future'];
                   3705:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3706:         $typesref = [$type];
                   3707:     }
                   3708:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3709:                               $typesref,undef,[$cdom]);
                   3710:     my ($tmp) = keys(%roles);
                   3711:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3712:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3713:     if (@course_roles > 0) {
                   3714:         return 1;
                   3715:     }
                   3716:     return 0;
                   3717: }
                   3718: 
1.478     albertel 3719: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3720: # input: action, courseID, current domain, intended
1.637     raeburn  3721: #        path to file, source of file, instruction to parse file for objects,
                   3722: #        ref to hash for embedded objects,
                   3723: #        ref to hash for codebase of java objects.
1.1095    raeburn  3724: #        reference to scalar to accommodate mime type determined
                   3725: #          from File::MMagic if $parser = parse.
1.637     raeburn  3726: #
1.485     raeburn  3727: # output: url to file (if action was uploaddoc), 
                   3728: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3729: #
1.478     albertel 3730: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3731: # course.
1.477     raeburn  3732: #
1.478     albertel 3733: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3734: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3735: #          course's home server.
1.477     raeburn  3736: #
1.478     albertel 3737: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3738: #          be copied from $source (current location) to 
                   3739: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3740: #         and will then be copied to
                   3741: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3742: #         course's home server.
1.485     raeburn  3743: #
1.481     raeburn  3744: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3745: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3746: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3747: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3748: #         in course's home server.
1.637     raeburn  3749: #
1.477     raeburn  3750: 
                   3751: sub process_coursefile {
1.1095    raeburn  3752:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3753:         $mimetype)=@_;
1.477     raeburn  3754:     my $fetchresult;
1.638     albertel 3755:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3756:     if ($action eq 'propagate') {
1.638     albertel 3757:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3758: 			     $home);
1.481     raeburn  3759:     } else {
1.477     raeburn  3760:         my $fpath = '';
                   3761:         my $fname = $file;
1.478     albertel 3762:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3763:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3764:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3765:         if ($action eq 'copy') {
                   3766:             if ($source eq '') {
                   3767:                 $fetchresult = 'no source file';
                   3768:                 return $fetchresult;
                   3769:             } else {
                   3770:                 my $destination = $filepath.'/'.$fname;
                   3771:                 rename($source,$destination);
                   3772:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3773:                                  $home);
1.481     raeburn  3774:             }
                   3775:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  3776:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3777:             print $fh $env{'form.'.$source};
1.481     raeburn  3778:             close($fh);
1.637     raeburn  3779:             if ($parser eq 'parse') {
1.1024    raeburn  3780:                 my $mm = new File::MMagic;
1.1095    raeburn  3781:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3782:                 if ($type eq 'text/html') {
1.1024    raeburn  3783:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3784:                     unless ($parse_result eq 'ok') {
                   3785:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3786:                     }
1.637     raeburn  3787:                 }
1.1095    raeburn  3788:                 if (ref($mimetype)) {
                   3789:                     $$mimetype = $type;
                   3790:                 } 
1.637     raeburn  3791:             }
1.477     raeburn  3792:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3793:                                  $home);
1.481     raeburn  3794:             if ($fetchresult eq 'ok') {
                   3795:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3796:             } else {
                   3797:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3798:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3799:                 return '/adm/notfound.html';
                   3800:             }
1.477     raeburn  3801:         }
                   3802:     }
1.485     raeburn  3803:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3804:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3805:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3806:     }
                   3807:     return $fetchresult;
                   3808: }
                   3809: 
1.637     raeburn  3810: sub build_filepath {
                   3811:     my ($fpath) = @_;
                   3812:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3813:     unless ($fpath eq '') {
                   3814:         my @parts=split('/',$fpath);
                   3815:         foreach my $part (@parts) {
                   3816:             $filepath.= '/'.$part;
                   3817:             if ((-e $filepath)!=1) {
                   3818:                 mkdir($filepath,0777);
                   3819:             }
                   3820:         }
                   3821:     }
                   3822:     return $filepath;
                   3823: }
                   3824: 
                   3825: sub store_edited_file {
1.638     albertel 3826:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3827:     my $file = $primary_url;
                   3828:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3829:     my $fpath = '';
                   3830:     my $fname = $file;
                   3831:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3832:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3833:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  3834:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3835:     print $fh $content;
                   3836:     close($fh);
1.638     albertel 3837:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3838:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3839: 			  $home);
1.637     raeburn  3840:     if ($$fetchresult eq 'ok') {
                   3841:         return '/uploaded/'.$fpath.'/'.$fname;
                   3842:     } else {
1.638     albertel 3843:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3844: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3845:         return '/adm/notfound.html';
                   3846:     }
                   3847: }
                   3848: 
1.531     albertel 3849: sub clean_filename {
1.831     albertel 3850:     my ($fname,$args)=@_;
1.315     www      3851: # Replace Windows backslashes by forward slashes
1.257     www      3852:     $fname=~s/\\/\//g;
1.831     albertel 3853:     if (!$args->{'keep_path'}) {
                   3854:         # Get rid of everything but the actual filename
                   3855: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3856:     }
1.315     www      3857: # Replace spaces by underscores
                   3858:     $fname=~s/\s+/\_/g;
                   3859: # Replace all other weird characters by nothing
1.831     albertel 3860:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3861: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3862: # numbers
                   3863:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3864:     return $fname;
                   3865: }
1.1051    raeburn  3866: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3867: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3868: # image with the same aspect ratio as the original, but with dimensions which do 
                   3869: # not exceed $resizewidth and $resizeheight.
                   3870:  
1.984     neumanie 3871: sub resizeImage {
1.1051    raeburn  3872:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3873:     my $ima = Image::Magick->new;
                   3874:     my $resized;
                   3875:     if (-e $img_path) {
                   3876:         $ima->Read($img_path);
                   3877:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3878:             my $width = $ima->Get('width');
                   3879:             my $height = $ima->Get('height');
                   3880:             if ($width > $resizewidth) {
                   3881: 	        my $factor = $width/$resizewidth;
                   3882:                 my $newheight = $height/$factor;
                   3883:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3884:                 $resized = 1;
                   3885:             }
                   3886:         }
                   3887:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3888:             my $width = $ima->Get('width');
                   3889:             my $height = $ima->Get('height');
                   3890:             if ($height > $resizeheight) {
                   3891:                 my $factor = $height/$resizeheight;
                   3892:                 my $newwidth = $width/$factor;
                   3893:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3894:                 $resized = 1;
                   3895:             }
                   3896:         }
                   3897:         if ($resized) {
                   3898:             $ima->Write($img_path);
                   3899:         }
                   3900:     }
                   3901:     return;
1.977     amueller 3902: }
                   3903: 
1.608     albertel 3904: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3905: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3906: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3907: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1401    raeburn  3908: #                                    canceloverwrite, scantron or ''.
1.1090    raeburn  3909: #                   if 'coursedoc': upload to the current course
                   3910: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3911: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3912: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3913: #        $subdir - directory in userfile to store the file into
1.1401    raeburn  3914: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3915: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3916: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
                   3917: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3918: #        $allfiles - reference to hash for embedded objects
                   3919: #        $codebase - reference to hash for codebase of java objects
                   3920: #        $desuname - username for permanent storage of uploaded file
                   3921: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3922: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3923: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3924: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3925: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3926: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3927: #                    from File::MMagic.
1.858     raeburn  3928: # 
1.686     albertel 3929: # output: url of file in userspace, or error: <message> 
                   3930: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3931: 
1.531     albertel 3932: sub userfileupload {
1.1090    raeburn  3933:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3934:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3935:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3936:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3937:     $fname=&clean_filename($fname);
1.1090    raeburn  3938:     # See if there is anything left
1.257     www      3939:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3940:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3941:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3942:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3943:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3944:         my $now = time;
1.1090    raeburn  3945:         my $filepath;
1.1095    raeburn  3946:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3947:              $filepath = 'tmp/helprequests/'.$now;
                   3948:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3949:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3950:                          '_'.$env{'user.domain'}.'/pending';
                   3951:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3952:             my ($docuname,$docudom);
1.1350    raeburn  3953:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3954:                 $docudom = $destudom;
                   3955:             } else {
                   3956:                 $docudom = $env{'user.domain'};
                   3957:             }
1.1350    raeburn  3958:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  3959:                 $docuname = $destuname;
                   3960:             } else {
                   3961:                 $docuname = $env{'user.name'};
                   3962:             }
                   3963:             if (exists($env{'form.group'})) {
                   3964:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3965:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3966:             }
                   3967:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3968:             if ($context eq 'canceloverwrite') {
                   3969:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3970:                 if (-e  $tempfile) {
                   3971:                     my @info = stat($tempfile);
                   3972:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3973:                         unlink($tempfile);
                   3974:                     }
                   3975:                 }
                   3976:                 return;
1.523     raeburn  3977:             }
                   3978:         }
1.1090    raeburn  3979:         # Create the directory if not present
1.741     raeburn  3980:         my @parts=split(/\//,$filepath);
                   3981:         my $fullpath = $perlvar{'lonDaemons'};
                   3982:         for (my $i=0;$i<@parts;$i++) {
                   3983:             $fullpath .= '/'.$parts[$i];
                   3984:             if ((-e $fullpath)!=1) {
                   3985:                 mkdir($fullpath,0777);
                   3986:             }
                   3987:         }
1.1359    raeburn  3988:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3989:         print $fh $env{'form.'.$formname};
                   3990:         close($fh);
1.1090    raeburn  3991:         if ($context eq 'existingfile') {
                   3992:             my @info = stat($fullpath.'/'.$fname);
                   3993:             return ($fullpath.'/'.$fname,$info[9]);
                   3994:         } else {
                   3995:             return $fullpath.'/'.$fname;
                   3996:         }
1.523     raeburn  3997:     }
1.995     raeburn  3998:     if ($subdir eq 'scantron') {
                   3999:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4000:     } else {
1.995     raeburn  4001:         $fname="$subdir/$fname";
                   4002:     }
1.1090    raeburn  4003:     if ($context eq 'coursedoc') {
1.638     albertel 4004: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4005: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4006:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4007:             return &finishuserfileupload($docuname,$docudom,
                   4008: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4009: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4010:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4011:         } else {
1.1218    raeburn  4012:             if ($env{'form.folder'}) {
                   4013:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4014:             }
1.638     albertel 4015:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4016: 				       $fname,$formname,$parser,
1.1095    raeburn  4017: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4018:         }
1.719     banghart 4019:     } elsif (defined($destuname)) {
                   4020:         my $docuname=$destuname;
                   4021:         my $docudom=$destudom;
1.860     raeburn  4022: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4023: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4024:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4025:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4026:     } else {
1.638     albertel 4027:         my $docuname=$env{'user.name'};
                   4028:         my $docudom=$env{'user.domain'};
1.1220    raeburn  4029:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4030:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4031:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4032:         }
1.860     raeburn  4033: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4034: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4035:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4036:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4037:     }
1.271     www      4038: }
                   4039: 
                   4040: sub finishuserfileupload {
1.860     raeburn  4041:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4042:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4043:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4044:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4045:   
1.860     raeburn  4046:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4047:     $file=$fname;
                   4048:     if ($fname=~m|/|) {
                   4049:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4050: 	$path.=$fnamepath.'/';
                   4051:     }
1.259     www      4052:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4053:     my $count;
                   4054:     for ($count=4;$count<=$#parts;$count++) {
                   4055:         $filepath.="/$parts[$count]";
                   4056:         if ((-e $filepath)!=1) {
                   4057: 	    mkdir($filepath,0777);
                   4058:         }
                   4059:     }
1.984     neumanie 4060: 
1.258     www      4061: # Save the file
                   4062:     {
1.1359    raeburn  4063: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4064: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4065: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4066: 	    return '/adm/notfound.html';
                   4067: 	}
1.1090    raeburn  4068:         if ($context eq 'overwrite') {
1.1117    foxr     4069:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4070:             my $target = $filepath.'/'.$file;
                   4071:             if (-e $source) {
                   4072:                 my @info = stat($source);
                   4073:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4074:                     unless (&File::Copy::move($source,$target)) {
                   4075:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4076:                         return "Moving from $source failed";
                   4077:                     }
                   4078:                 } else {
                   4079:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4080:                 }
                   4081:             } else {
                   4082:                 return "Temporary file: $source missing";
                   4083:             }
                   4084:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4085: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4086: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4087: 	    return '/adm/notfound.html';
                   4088: 	}
1.570     albertel 4089: 	close(FH);
1.1051    raeburn  4090:         if ($resizewidth && $resizeheight) {
                   4091:             my $mm = new File::MMagic;
                   4092:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4093:             if ($mime_type =~ m{^image/}) {
                   4094: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4095:             }  
1.977     amueller 4096: 	}
1.258     www      4097:     }
1.1152    raeburn  4098:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4099:         if (ref($mimetype)) {
                   4100:             if ($$mimetype eq '') {
                   4101:                 my $mm = new File::MMagic;
                   4102:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4103:                 $$mimetype = $type;
                   4104:             }
                   4105:         }
                   4106:     }
1.1401    raeburn  4107:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4108:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4109:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4110:                                                        $allfiles,$codebase);
                   4111:             unless ($parse_result eq 'ok') {
                   4112:                 &logthis('Failed to parse '.$filepath.$file.
                   4113: 	   	         ' for embedded media: '.$parse_result); 
                   4114:             }
1.637     raeburn  4115:         }
1.1401    raeburn  4116:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4117:         my $format = $env{'form.scantron_format'};
                   4118:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4119:     }
1.860     raeburn  4120:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4121:         my $input = $filepath.'/'.$file;
                   4122:         my $output = $filepath.'/'.'tn-'.$file;
                   4123:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  4124:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4125:         system({$args[0]} @args);
1.860     raeburn  4126:         if (-e $filepath.'/'.'tn-'.$file) {
                   4127:             $fetchthumb  = 1; 
                   4128:         }
                   4129:     }
1.858     raeburn  4130:  
1.259     www      4131: # Notify homeserver to grep it
                   4132: #
1.984     neumanie 4133:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4134:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4135:     if ($fetchresult eq 'ok') {
1.860     raeburn  4136:         if ($fetchthumb) {
                   4137:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4138:             if ($thumbresult ne 'ok') {
                   4139:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4140:                          $docuhome.': '.$thumbresult);
                   4141:             }
                   4142:         }
1.259     www      4143: #
1.258     www      4144: # Return the URL to it
1.494     albertel 4145:         return '/uploaded/'.$path.$file;
1.263     www      4146:     } else {
1.494     albertel 4147:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4148: 		 ': '.$fetchresult);
1.263     www      4149:         return '/adm/notfound.html';
1.858     raeburn  4150:     }
1.493     albertel 4151: }
                   4152: 
1.637     raeburn  4153: sub extract_embedded_items {
1.961     raeburn  4154:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4155:     my @state = ();
1.1164    raeburn  4156:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4157:     my %javafiles = (
                   4158:                       codebase => '',
                   4159:                       code => '',
                   4160:                       archive => ''
                   4161:                     );
                   4162:     my %mediafiles = (
                   4163:                       src => '',
                   4164:                       movie => '',
                   4165:                      );
1.648     raeburn  4166:     my $p;
                   4167:     if ($content) {
                   4168:         $p = HTML::LCParser->new($content);
                   4169:     } else {
1.961     raeburn  4170:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4171:     }
1.641     albertel 4172:     while (my $t=$p->get_token()) {
1.640     albertel 4173: 	if ($t->[0] eq 'S') {
                   4174: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4175: 	    push(@state, $tagname);
1.648     raeburn  4176:             if (lc($tagname) eq 'allow') {
                   4177:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4178:             }
1.640     albertel 4179: 	    if (lc($tagname) eq 'img') {
                   4180: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4181: 	    }
1.886     albertel 4182: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4183:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4184:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4185:                 }
1.886     albertel 4186: 	    }
1.645     raeburn  4187:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4188:                 my $src;
1.645     raeburn  4189:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4190:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4191:                 } else {
1.1164    raeburn  4192:                     if ($attr->{'src'} ne '') {
                   4193:                         $src = $attr->{'src'};
                   4194:                         &add_filetype($allfiles,$src,'src');
                   4195:                     }
                   4196:                 }
                   4197:                 my $text = $p->get_trimmed_text();
                   4198:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4199:                     my @swfargs = split(/,/,$1);
                   4200:                     foreach my $item (@swfargs) {
                   4201:                         $item =~ s/["']//g;
                   4202:                         $item =~ s/^\s+//;
                   4203:                         $item =~ s/\s+$//;
                   4204:                     }
                   4205:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4206:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4207:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4208:                         } else {
                   4209:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4210:                         }
                   4211:                     }
1.645     raeburn  4212:                 }
                   4213:             }
                   4214:             if (lc($tagname) eq 'link') {
                   4215:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4216:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4217:                 }
                   4218:             }
1.640     albertel 4219: 	    if (lc($tagname) eq 'object' ||
                   4220: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4221: 		foreach my $item (keys(%javafiles)) {
                   4222: 		    $javafiles{$item} = '';
                   4223: 		}
1.1164    raeburn  4224:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4225:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4226:                 }
1.640     albertel 4227: 	    }
                   4228: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4229: 		my $name = lc($attr->{'name'});
                   4230: 		foreach my $item (keys(%javafiles)) {
                   4231: 		    if ($name eq $item) {
                   4232: 			$javafiles{$item} = $attr->{'value'};
                   4233: 			last;
                   4234: 		    }
                   4235: 		}
1.1164    raeburn  4236:                 my $pathfrom;
1.640     albertel 4237: 		foreach my $item (keys(%mediafiles)) {
                   4238: 		    if ($name eq $item) {
1.1164    raeburn  4239:                         $pathfrom = $attr->{'value'};
                   4240:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4241: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4242: 			last;
                   4243: 		    }
                   4244: 		}
1.1164    raeburn  4245:                 if ($name eq 'flashvars') {
                   4246:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4247:                 }
                   4248:                 if ($pathfrom ne '') {
                   4249:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4250:                                          $pathfrom);
                   4251:                 }
1.640     albertel 4252: 	    }
                   4253: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4254: 		foreach my $item (keys(%javafiles)) {
                   4255: 		    if ($attr->{$item}) {
                   4256: 			$javafiles{$item} = $attr->{$item};
                   4257: 			last;
                   4258: 		    }
                   4259: 		}
                   4260: 		foreach my $item (keys(%mediafiles)) {
                   4261: 		    if ($attr->{$item}) {
                   4262: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4263: 			last;
                   4264: 		    }
                   4265: 		}
1.1164    raeburn  4266:                 if (lc($tagname) eq 'embed') {
                   4267:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4268:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4269:                                              $attr->{'src'});
                   4270:                     }
                   4271:                 }
1.640     albertel 4272: 	    }
1.1243    raeburn  4273:             if (lc($tagname) eq 'iframe') {
                   4274:                 my $src = $attr->{'src'} ;
                   4275:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4276:                     &add_filetype($allfiles,$src,'src');
                   4277:                 } elsif ($src =~ m{^/}) {
                   4278:                     if ($env{'request.course.id'}) {
                   4279:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4280:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4281:                         my $url = &hreflocation('',$fullpath);
                   4282:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4283:                             my $relpath = $1;
                   4284:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4285:                                 &add_filetype($allfiles,$1,'src');
                   4286:                             }
                   4287:                         }
                   4288:                     }
                   4289:                 }
                   4290:             }
1.1164    raeburn  4291:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4292:                 pop(@state);
1.1164    raeburn  4293:             }
1.640     albertel 4294: 	} elsif ($t->[0] eq 'E') {
                   4295: 	    my ($tagname) = ($t->[1]);
                   4296: 	    if ($javafiles{'codebase'} ne '') {
                   4297: 		$javafiles{'codebase'} .= '/';
                   4298: 	    }  
                   4299: 	    if (lc($tagname) eq 'applet' ||
                   4300: 		lc($tagname) eq 'object' ||
                   4301: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4302: 		) {
                   4303: 		foreach my $item (keys(%javafiles)) {
                   4304: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4305: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4306: 			&add_filetype($allfiles,$file,$item);
                   4307: 		    }
                   4308: 		}
                   4309: 	    } 
                   4310: 	    pop @state;
                   4311: 	}
                   4312:     }
1.1164    raeburn  4313:     foreach my $id (sort(keys(%flashvars))) {
                   4314:         if ($shockwave{$id} ne '') {
                   4315:             my @pairs = split(/\&/,$flashvars{$id});
                   4316:             foreach my $pair (@pairs) {
                   4317:                 my ($key,$value) = split(/\=/,$pair);
                   4318:                 if ($key eq 'thumb') {
                   4319:                     &add_filetype($allfiles,$value,$key);
                   4320:                 } elsif ($key eq 'content') {
                   4321:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4322:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4323:                     if ($ext ne '') {
                   4324:                         &add_filetype($allfiles,$path.$value,$ext);
                   4325:                     }
                   4326:                 }
                   4327:             }
                   4328:         }
                   4329:     }
1.637     raeburn  4330:     return 'ok';
                   4331: }
                   4332: 
1.639     albertel 4333: sub add_filetype {
                   4334:     my ($allfiles,$file,$type)=@_;
                   4335:     if (exists($allfiles->{$file})) {
                   4336: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4337: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4338: 	}
                   4339:     } else {
                   4340: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4341:     }
                   4342: }
                   4343: 
1.1164    raeburn  4344: sub embedded_dependency {
                   4345:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4346:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4347:         if (($identifier ne '') &&
                   4348:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4349:             ($pathfrom ne '')) {
                   4350:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4351:             foreach my $dep (@{$related->{$identifier}}) {
                   4352:                 &add_filetype($allfiles,$path.$dep,'object');
                   4353:             }
                   4354:         }
                   4355:     }
                   4356:     return;
                   4357: }
                   4358: 
1.1401    raeburn  4359: sub bubblesheet_converter {
                   4360:     my ($cdom,$fullpath,$config,$format) = @_;
                   4361:     if ((&domain($cdom) ne '') &&
1.1403    raeburn  4362:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401    raeburn  4363:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404  ! raeburn  4364:         my (%csvcols,%csvoptions);
        !          4365:         if (ref($config->{'fields'}) eq 'HASH') {  
        !          4366:             %csvcols = %{$config->{'fields'}};
        !          4367:         }
        !          4368:         if (ref($config->{'options'}) eq 'HASH') {
        !          4369:             %csvoptions = %{$config->{'options'}};
        !          4370:         }
1.1401    raeburn  4371:         my %csvbynum = reverse(%csvcols);
                   4372:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4373:         if (keys(%scantronconf)) {
                   4374:             my %bynum = (
                   4375:                           $scantronconf{CODEstart} => 'CODEstart',
                   4376:                           $scantronconf{IDstart}   => 'IDstart',
                   4377:                           $scantronconf{PaperID}   => 'PaperID',
                   4378:                           $scantronconf{FirstName} => 'FirstName',
                   4379:                           $scantronconf{LastName}  => 'LastName',
                   4380:                           $scantronconf{Qstart}    => 'Qstart',
                   4381:                         );
                   4382:             my @ordered;
                   4383:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403    raeburn  4384:                 push(@ordered,$bynum{$item});
1.1401    raeburn  4385:             }
                   4386:             my %mapstart = (
                   4387:                               CODEstart => 'CODE',
                   4388:                               IDstart   => 'ID',
                   4389:                               PaperID   => 'PaperID',
                   4390:                               FirstName => 'FirstName',
                   4391:                               LastName  => 'LastName',
                   4392:                               Qstart    => 'FirstQuestion',
                   4393:                            );
                   4394:             my %maplength = (
                   4395:                               CODEstart => 'CODElength',
                   4396:                               IDstart   => 'IDlength',
                   4397:                               PaperID   => 'PaperIDlength',
                   4398:                               FirstName => 'FirstNamelength',
                   4399:                               LastName  => 'LastNamelength',
                   4400:             );
                   4401:             if (open(my $fh,'<',$fullpath)) {
                   4402:                 my $output;
1.1403    raeburn  4403:                 my %lettdig = &letter_to_digits();
                   4404:                 my %diglett = reverse(%lettdig);
                   4405:                 my $numletts = scalar(keys(%lettdig));
1.1404  ! raeburn  4406:                 my $num = 0;
1.1401    raeburn  4407:                 while (my $line=<$fh>) {
1.1404  ! raeburn  4408:                     $num ++;
        !          4409:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401    raeburn  4410:                     $line =~ s{[\r\n]+$}{};
                   4411:                     my %found;
                   4412:                     my @values = split(/,/,$line);
                   4413:                     my ($qstart,$record);
                   4414:                     for (my $i=0; $i<@values; $i++) {
1.1403    raeburn  4415:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4416:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4417:                             if ($values[$i] eq '') {
                   4418:                                 $values[$i] = $scantronconf{'Qoff'};
                   4419:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4420:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4421:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4422:                                 }
                   4423:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4424:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4425:                                     $values[$i] = $diglett{$values[$i]};
                   4426:                                 }
                   4427:                             } else {
                   4428:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4429:                                     my $digit;
                   4430:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4431:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4432:                                         if ($values[$i] eq 'J') {
                   4433:                                             $digit += $numletts;
                   4434:                                         }
                   4435:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4436:                                         $digit = $values[$i]-1;
                   4437:                                         if ($values[$i] eq '0') {
                   4438:                                             $digit += $numletts;
                   4439:                                         }
                   4440:                                     }
                   4441:                                     my $qval='';
                   4442:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4443:                                         if ($j == $digit) {
                   4444:                                             $qval .= $scantronconf{'Qon'};
                   4445:                                         } else {
                   4446:                                             $qval .= $scantronconf{'Qoff'};
                   4447:                                         }
                   4448:                                     }
                   4449:                                     $values[$i] = $qval;
                   4450:                                 }
                   4451:                             }
                   4452:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4453:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4454:                             }
                   4455:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4456:                             if ($numblank > 0) {
                   4457:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4458:                             }
1.1401    raeburn  4459:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4460:                                 $qstart = $i;
1.1403    raeburn  4461:                                 $found{$csvbynum{$i}} = $values[$i];
1.1401    raeburn  4462:                             } else {
1.1403    raeburn  4463:                                 $found{'FirstQuestion'} .= $values[$i];
                   4464:                             }
                   4465:                         } elsif (exists($csvbynum{$i})) {
1.1404  ! raeburn  4466:                             if ($csvoptions{'rem'}) {
        !          4467:                                 $values[$i] =~ s/^\s+//;
        !          4468:                             }
        !          4469:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403    raeburn  4470:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4471:                                     $values[$i] = '0'.$values[$i];
1.1401    raeburn  4472:                                 }
                   4473:                             }
                   4474:                             $found{$csvbynum{$i}} = $values[$i];
                   4475:                         }
                   4476:                     }
                   4477:                     foreach my $item (@ordered) {
                   4478:                         my $currlength = 1+length($record);
                   4479:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4480:                         if ($numspaces > 0) {
                   4481:                             $record .= (' ' x $numspaces);
                   4482:                         }
                   4483:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4484:                             unless ($item eq 'Qstart') {
                   4485:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4486:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4487:                                 }
                   4488:                             }
                   4489:                             $record .= $found{$mapstart{$item}};
                   4490:                         }
                   4491:                     }
                   4492:                     $output .= "$record\n";
                   4493:                 }
                   4494:                 close($fh);
                   4495:                 if ($output) {
                   4496:                     if (open(my $fh,'>',$fullpath)) {
                   4497:                         print $fh $output;
                   4498:                         close($fh);
                   4499:                     }
                   4500:                 }
                   4501:             }
                   4502:         }
                   4503:         return;
                   4504:     }
                   4505: }
                   4506: 
1.1403    raeburn  4507: sub letter_to_digits {
                   4508:     my %lettdig = (
                   4509:                     A => 1,
                   4510:                     B => 2,
                   4511:                     C => 3,
                   4512:                     D => 4,
                   4513:                     E => 5,
                   4514:                     F => 6,
                   4515:                     G => 7,
                   4516:                     H => 8,
                   4517:                     I => 9,
                   4518:                     J => 0,
                   4519:                   );
                   4520:     return %lettdig;
                   4521: }
                   4522: 
1.1401    raeburn  4523: sub get_scantron_config {
                   4524:     my ($which,$cdom) = @_;
                   4525:     my @lines = &get_scantronformat_file($cdom);
                   4526:     my %config;
                   4527:     #FIXME probably should move to XML it has already gotten a bit much now
                   4528:     foreach my $line (@lines) {
                   4529:         my ($name,$descrip)=split(/:/,$line);
                   4530:         if ($name ne $which ) { next; }
                   4531:         chomp($line);
                   4532:         my @config=split(/:/,$line);
                   4533:         $config{'name'}=$config[0];
                   4534:         $config{'description'}=$config[1];
                   4535:         $config{'CODElocation'}=$config[2];
                   4536:         $config{'CODEstart'}=$config[3];
                   4537:         $config{'CODElength'}=$config[4];
                   4538:         $config{'IDstart'}=$config[5];
                   4539:         $config{'IDlength'}=$config[6];
                   4540:         $config{'Qstart'}=$config[7];
                   4541:         $config{'Qlength'}=$config[8];
                   4542:         $config{'Qoff'}=$config[9];
                   4543:         $config{'Qon'}=$config[10];
                   4544:         $config{'PaperID'}=$config[11];
                   4545:         $config{'PaperIDlength'}=$config[12];
                   4546:         $config{'FirstName'}=$config[13];
                   4547:         $config{'FirstNamelength'}=$config[14];
                   4548:         $config{'LastName'}=$config[15];
                   4549:         $config{'LastNamelength'}=$config[16];
                   4550:         $config{'BubblesPerRow'}=$config[17];
                   4551:         last;
                   4552:     }
                   4553:     return %config;
                   4554: }
                   4555: 
                   4556: sub get_scantronformat_file {
                   4557:     my ($cdom) = @_;
                   4558:     if ($cdom eq '') {
                   4559:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4560:     }
                   4561:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4562:     my $gottab = 0;
                   4563:     my @lines;
                   4564:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4565:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4566:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4567:             if ($formatfile ne '-1') {
                   4568:                 @lines = split("\n",$formatfile,-1);
                   4569:                 $gottab = 1;
                   4570:             }
                   4571:         }
                   4572:     }
                   4573:     if (!$gottab) {
                   4574:         my $confname = $cdom.'-domainconfig';
                   4575:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4576:         my $formatfile = &getfile($default);
                   4577:         if ($formatfile ne '-1') {
                   4578:             @lines = split("\n",$formatfile,-1);
                   4579:             $gottab = 1;
                   4580:         }
                   4581:     }
                   4582:     if (!$gottab) {
                   4583:         my @domains = &current_machine_domains();
                   4584:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4585:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4586:                 @lines = <$fh>;
                   4587:                 close($fh);
1.1403    raeburn  4588:             }
1.1401    raeburn  4589:         } else {
                   4590:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4591:                 @lines = <$fh>;
                   4592:                 close($fh);
                   4593:             }
                   4594:         }
                   4595:     }
                   4596:     return @lines;
                   4597: }
                   4598: 
1.493     albertel 4599: sub removeuploadedurl {
1.984     neumanie 4600:     my ($url)=@_;	
                   4601:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4602:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4603: }
                   4604: 
                   4605: sub removeuserfile {
                   4606:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4607:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4608:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4609:     if ($result eq 'ok') {	
1.798     raeburn  4610:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4611:             my $metafile = $fname.'.meta';
                   4612:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4613: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4614:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4615:             my $sqlresult = 
1.823     albertel 4616:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4617:                                         'portfolio_metadata',$group,
                   4618:                                         'delete');
1.798     raeburn  4619:         }
                   4620:     }
                   4621:     return $result;
1.257     www      4622: }
1.15      www      4623: 
1.530     albertel 4624: sub mkdiruserfile {
                   4625:     my ($docuname,$docudom,$dir)=@_;
                   4626:     my $home=&homeserver($docuname,$docudom);
                   4627:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4628: }
                   4629: 
1.531     albertel 4630: sub renameuserfile {
                   4631:     my ($docuname,$docudom,$old,$new)=@_;
                   4632:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4633:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4634:                         &escape("$old").':'.&escape("$new"),$home);
                   4635:     if ($result eq 'ok') {
                   4636:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4637:             my $oldmeta = $old.'.meta';
                   4638:             my $newmeta = $new.'.meta';
                   4639:             my $metaresult = 
                   4640:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4641: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4642:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4643:             my $sqlresult = 
1.823     albertel 4644:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4645:                                         'portfolio_metadata',$group,
                   4646:                                         'delete');
1.798     raeburn  4647:         }
                   4648:     }
                   4649:     return $result;
1.531     albertel 4650: }
                   4651: 
1.14      www      4652: # ------------------------------------------------------------------------- Log
                   4653: 
                   4654: sub log {
                   4655:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4656:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4657: }
                   4658: 
                   4659: # ------------------------------------------------------------------ Course Log
1.352     www      4660: #
                   4661: # This routine flushes several buffers of non-mission-critical nature
                   4662: #
1.157     www      4663: 
                   4664: sub flushcourselogs {
1.352     www      4665:     &logthis('Flushing log buffers');
                   4666: #
                   4667: # course logs
                   4668: # This is a log of all transactions in a course, which can be used
                   4669: # for data mining purposes
                   4670: #
                   4671: # It also collects the courseid database, which lists last transaction
                   4672: # times and course titles for all courseids
                   4673: #
                   4674:     my %courseidbuffer=();
1.921     raeburn  4675:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4676:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4677: 		          &escape($courselogs{$crsid}),
                   4678: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4679: 	    delete $courselogs{$crsid};
                   4680:         } else {
                   4681:             &logthis('Failed to flush log buffer for '.$crsid);
                   4682:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4683:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4684:                         " exceeded maximum size, deleting.</font>");
                   4685:                delete $courselogs{$crsid};
                   4686:             }
1.352     www      4687:         }
1.920     raeburn  4688:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4689:             'description' => $coursedescrbuf{$crsid},
                   4690:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4691:             'type'        => $coursetypebuf{$crsid},
                   4692:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4693:         };
1.191     harris41 4694:     }
1.352     www      4695: #
                   4696: # Write course id database (reverse lookup) to homeserver of courses 
                   4697: # Is used in pickcourse
                   4698: #
1.840     albertel 4699:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4700:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4701:                                     $courseidbuffer{$crs_home},
                   4702:                                     $crs_home,'timeonly');
1.352     www      4703:     }
                   4704: #
                   4705: # File accesses
                   4706: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4707: #
1.449     matthew  4708:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4709:         if ($entry =~ /___count$/) {
                   4710:             my ($dom,$name);
1.807     albertel 4711:             ($dom,$name,undef)=
1.811     albertel 4712: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4713:             if (! defined($dom) || $dom eq '' || 
                   4714:                 ! defined($name) || $name eq '') {
1.620     albertel 4715:                 my $cid = $env{'request.course.id'};
                   4716:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4717:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4718:             }
1.450     matthew  4719:             my $value = $accesshash{$entry};
                   4720:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4721:             my %temphash=($url => $value);
1.449     matthew  4722:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4723:             if ($result eq 'ok') {
                   4724:                 delete $accesshash{$entry};
                   4725:             }
                   4726:         } else {
1.811     albertel 4727:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4728:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4729:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4730:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4731:                 delete $accesshash{$entry};
                   4732:             }
1.185     www      4733:         }
1.191     harris41 4734:     }
1.352     www      4735: #
                   4736: # Roles
                   4737: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4738: #
1.800     albertel 4739:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4740:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4741: 	    split(/\:/,$entry);
                   4742:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4743:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4744:                 $rudom,$runame) eq 'ok') {
                   4745: 	    delete $userrolehash{$entry};
                   4746:         }
                   4747:     }
1.662     raeburn  4748: #
1.1334    raeburn  4749: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4750: #
                   4751:     my %domrolebuffer = ();
1.1000    raeburn  4752:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4753:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4754:         if ($domrolebuffer{$rudom}) {
                   4755:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4756:                       '='.&escape($domainrolehash{$entry});
                   4757:         } else {
                   4758:             $domrolebuffer{$rudom}.=&escape($entry).
                   4759:                       '='.&escape($domainrolehash{$entry});
                   4760:         }
                   4761:         delete $domainrolehash{$entry};
                   4762:     }
                   4763:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4764: 	my %servers;
                   4765: 	if (defined(&domain($dom,'primary'))) {
                   4766: 	    my $primary=&domain($dom,'primary');
                   4767: 	    my $hostname=&hostname($primary);
                   4768: 	    $servers{$primary} = $hostname;
                   4769: 	} else { 
                   4770: 	    %servers = &get_servers($dom,'library');
                   4771: 	}
1.841     albertel 4772: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4773: 	    if (&reply('domroleput:'.$dom.':'.
                   4774: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4775: 		last;
                   4776: 	    } else {  
1.841     albertel 4777: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4778: 	    }
1.662     raeburn  4779:         }
                   4780:     }
1.186     www      4781:     $dumpcount++;
1.157     www      4782: }
                   4783: 
                   4784: sub courselog {
                   4785:     my $what=shift;
1.158     www      4786:     $what=time.':'.$what;
1.620     albertel 4787:     unless ($env{'request.course.id'}) { return ''; }
                   4788:     $coursedombuf{$env{'request.course.id'}}=
                   4789:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4790:     $coursenumbuf{$env{'request.course.id'}}=
                   4791:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4792:     $coursehombuf{$env{'request.course.id'}}=
                   4793:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4794:     $coursedescrbuf{$env{'request.course.id'}}=
                   4795:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4796:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4797:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4798:     $courseownerbuf{$env{'request.course.id'}}=
                   4799:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4800:     $coursetypebuf{$env{'request.course.id'}}=
                   4801:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4802:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4803: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4804:     } else {
1.620     albertel 4805: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4806:     }
1.620     albertel 4807:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4808: 	&flushcourselogs();
                   4809:     }
1.158     www      4810: }
                   4811: 
                   4812: sub courseacclog {
                   4813:     my $fnsymb=shift;
1.620     albertel 4814:     unless ($env{'request.course.id'}) { return ''; }
                   4815:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4816:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4817:         $what.=':POST';
1.583     matthew  4818:         # FIXME: Probably ought to escape things....
1.800     albertel 4819: 	foreach my $key (keys(%env)) {
                   4820:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4821:                 my $formitem = $1;
                   4822:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4823:                     $what.=':'.$formitem.'='.$env{$key};
                   4824:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4825:                     $what.=':'.$formitem.'='.$env{$key};
                   4826:                 }
1.158     www      4827:             }
1.191     harris41 4828:         }
1.583     matthew  4829:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4830:         # FIXME: We should not be depending on a form parameter that someone
                   4831:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4832:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4833:             $what.= ':POST';
                   4834:             # FIXME: Probably ought to escape things....
                   4835:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4836:                                  'crsdiscuss') {
1.620     albertel 4837:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4838:             }
                   4839:         }
1.158     www      4840:     }
                   4841:     &courselog($what);
1.149     www      4842: }
                   4843: 
1.185     www      4844: sub countacc {
                   4845:     my $url=&declutter(shift);
1.458     matthew  4846:     return if (! defined($url) || $url eq '');
1.620     albertel 4847:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4848: #
                   4849: # Mark that this url was used in this course
                   4850: #
1.620     albertel 4851:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4852: #
                   4853: # Increase the access count for this resource in this child process
                   4854: #
1.281     www      4855:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4856:     $accesshash{$key}++;
1.185     www      4857: }
1.349     www      4858: 
1.361     www      4859: sub linklog {
                   4860:     my ($from,$to)=@_;
                   4861:     $from=&declutter($from);
                   4862:     $to=&declutter($to);
                   4863:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4864:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4865: }
1.1160    www      4866: 
                   4867: sub statslog {
                   4868:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4869:     if ($users<2) { return; }
                   4870:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4871:             'course'       => $env{'request.course.id'},
                   4872:             'sections'     => '"all"',
                   4873:             'num_students' => $users,
                   4874:             'part'         => $part,
                   4875:             'symb'         => $symb,
                   4876:             'mean_tries'   => $av_attempts,
                   4877:             'deg_of_diff'  => $degdiff});
                   4878:     foreach my $key (keys(%dynstore)) {
                   4879:         $accesshash{$key}=$dynstore{$key};
                   4880:     }
                   4881: }
1.361     www      4882:   
1.349     www      4883: sub userrolelog {
                   4884:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4885:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4886:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4887:        $userrolehash
                   4888:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4889:                     =$tend.':'.$tstart;
1.662     raeburn  4890:     }
1.1169    droeschl 4891:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4892:        $userrolehash
                   4893:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4894:                     =$tend.':'.$tstart;
                   4895:     }
1.1334    raeburn  4896:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4897:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4898:        $domainrolehash
                   4899:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4900:                     = $tend.':'.$tstart;
                   4901:     }
1.351     www      4902: }
                   4903: 
1.957     raeburn  4904: sub courserolelog {
                   4905:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4906:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4907:         my $cdom = $1;
                   4908:         my $cnum = $2;
                   4909:         my $sec = $3;
                   4910:         my $namespace = 'rolelog';
                   4911:         my %storehash = (
                   4912:                            role    => $trole,
                   4913:                            start   => $tstart,
                   4914:                            end     => $tend,
                   4915:                            selfenroll => $selfenroll,
                   4916:                            context    => $context,
                   4917:                         );
                   4918:         if ($trole eq 'gr') {
                   4919:             $namespace = 'groupslog';
                   4920:             $storehash{'group'} = $sec;
                   4921:         } else {
                   4922:             $storehash{'section'} = $sec;
                   4923:         }
1.1188    raeburn  4924:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4925:                    $domain,$cnum,$cdom);
1.1184    raeburn  4926:         if (($trole ne 'st') || ($sec ne '')) {
                   4927:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4928:         }
                   4929:     }
                   4930:     return;
                   4931: }
                   4932: 
1.1184    raeburn  4933: sub domainrolelog {
                   4934:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4935:     if ($area =~ m{^/($match_domain)/$}) {
                   4936:         my $cdom = $1;
                   4937:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4938:         my $namespace = 'rolelog';
                   4939:         my %storehash = (
                   4940:                            role    => $trole,
                   4941:                            start   => $tstart,
                   4942:                            end     => $tend,
                   4943:                            context => $context,
                   4944:                         );
1.1188    raeburn  4945:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4946:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4947:     }
                   4948:     return;
                   4949: 
                   4950: }
                   4951: 
                   4952: sub coauthorrolelog {
                   4953:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4954:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4955:         my $audom = $1;
                   4956:         my $auname = $2;
                   4957:         my $namespace = 'rolelog';
                   4958:         my %storehash = (
                   4959:                            role    => $trole,
                   4960:                            start   => $tstart,
                   4961:                            end     => $tend,
                   4962:                            context => $context,
                   4963:                         );
1.1188    raeburn  4964:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4965:                    $domain,$auname,$audom);
1.1184    raeburn  4966:     }
                   4967:     return;
                   4968: }
                   4969: 
1.351     www      4970: sub get_course_adv_roles {
1.948     raeburn  4971:     my ($cid,$codes) = @_;
1.620     albertel 4972:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4973:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4974:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4975:     my %nothide=();
1.800     albertel 4976:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4977:         if ($user !~ /:/) {
                   4978: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4979:         } else {
                   4980:             $nothide{$user}=1;
                   4981:         }
1.470     www      4982:     }
1.1219    raeburn  4983:     my @possdoms = ($coursehash{'domain'});
                   4984:     if ($coursehash{'checkforpriv'}) {
                   4985:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4986:     }
1.351     www      4987:     my %returnhash=();
                   4988:     my %dumphash=
                   4989:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4990:     my $now=time;
1.997     raeburn  4991:     my %privileged;
1.1000    raeburn  4992:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4993: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4994:         if (($tstart) && ($tstart<0)) { next; }
                   4995:         if (($tend) && ($tend<$now)) { next; }
                   4996:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4997:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4998: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4999:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5000:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5001: 	if ($role eq 'cr') { next; }
1.948     raeburn  5002:         if ($codes) {
                   5003:             if ($section) { $role .= ':'.$section; }
                   5004:             if ($returnhash{$role}) {
                   5005:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5006:             } else {
                   5007:                 $returnhash{$role}=$username.':'.$domain;
                   5008:             }
1.351     www      5009:         } else {
1.988     raeburn  5010:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5011:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5012:             if ($returnhash{$key}) {
                   5013: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5014:             } else {
                   5015:                 $returnhash{$key}=$username.':'.$domain;
                   5016:             }
1.351     www      5017:         }
1.948     raeburn  5018:     }
1.400     www      5019:     return %returnhash;
                   5020: }
                   5021: 
                   5022: sub get_my_roles {
1.937     raeburn  5023:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5024:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5025:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5026:     my (%dumphash,%nothide);
1.1086    raeburn  5027:     if ($context eq 'userroles') {
1.1166    raeburn  5028:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5029:     } else {
1.1219    raeburn  5030:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5031:         if ($hidepriv) {
                   5032:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5033:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5034:                 if ($user !~ /:/) {
                   5035:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5036:                 } else {
                   5037:                     $nothide{$user} = 1;
                   5038:                 }
                   5039:             }
                   5040:         }
1.858     raeburn  5041:     }
1.400     www      5042:     my %returnhash=();
                   5043:     my $now=time;
1.999     raeburn  5044:     my %privileged;
1.800     albertel 5045:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5046:         my ($role,$tend,$tstart);
                   5047:         if ($context eq 'userroles') {
1.1149    raeburn  5048:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5049: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5050:         } else {
                   5051:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5052:         }
1.400     www      5053:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5054:         my $status = 'active';
1.939     raeburn  5055:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5056:             $status = 'previous';
                   5057:         } 
                   5058:         if (($tstart) && ($now<$tstart)) {
                   5059:             $status = 'future';
                   5060:         }
                   5061:         if (ref($types) eq 'ARRAY') {
                   5062:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5063:                 next;
                   5064:             } 
                   5065:         } else {
                   5066:             if ($status ne 'active') {
                   5067:                 next;
                   5068:             }
                   5069:         }
1.867     raeburn  5070:         my ($rolecode,$username,$domain,$section,$area);
                   5071:         if ($context eq 'userroles') {
1.1186    raeburn  5072:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5073:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5074:         } else {
                   5075:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5076:         }
1.832     raeburn  5077:         if (ref($roledoms) eq 'ARRAY') {
                   5078:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5079:                 next;
                   5080:             }
                   5081:         }
                   5082:         if (ref($roles) eq 'ARRAY') {
                   5083:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5084:                 if ($role =~ /^cr\//) {
                   5085:                     if (!grep(/^cr$/,@{$roles})) {
                   5086:                         next;
                   5087:                     }
1.1104    raeburn  5088:                 } elsif ($role =~ /^gr\//) {
                   5089:                     if (!grep(/^gr$/,@{$roles})) {
                   5090:                         next;
                   5091:                     }
1.922     raeburn  5092:                 } else {
                   5093:                     next;
                   5094:                 }
1.832     raeburn  5095:             }
1.867     raeburn  5096:         }
1.937     raeburn  5097:         if ($hidepriv) {
1.1219    raeburn  5098:             my @privroles = ('dc','su');
1.999     raeburn  5099:             if ($context eq 'userroles') {
1.1219    raeburn  5100:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5101:             } else {
1.1219    raeburn  5102:                 my $possdoms = [$domain];
                   5103:                 if (ref($roledoms) eq 'ARRAY') {
                   5104:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  5105:                 }
1.1219    raeburn  5106:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5107:                     if (!$nothide{$username.':'.$domain}) {
                   5108:                         next;
                   5109:                     }
                   5110:                 }
1.937     raeburn  5111:             }
                   5112:         }
1.933     raeburn  5113:         if ($withsec) {
                   5114:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5115:                 $tstart.':'.$tend;
                   5116:         } else {
                   5117:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5118:         }
1.832     raeburn  5119:     }
1.373     www      5120:     return %returnhash;
1.399     www      5121: }
                   5122: 
1.1333    raeburn  5123: sub get_all_adhocroles {
                   5124:     my ($dom) = @_;
                   5125:     my @roles_by_num = ();
                   5126:     my %domdefaults = &get_domain_defaults($dom);
                   5127:     my (%description,%access_in_dom,%access_info);
                   5128:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5129:         my $count = 0;
                   5130:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5131:         my %ordered;
                   5132:         foreach my $role (sort(keys(%domcurrent))) {
                   5133:             my ($order,$desc,$access_in_dom);
                   5134:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5135:                 $order = $domcurrent{$role}{'order'};
                   5136:                 $desc = $domcurrent{$role}{'desc'};
                   5137:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5138:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5139:             }
                   5140:             if ($order eq '') {
                   5141:                 $order = $count;
                   5142:             }
                   5143:             $ordered{$order} = $role;
                   5144:             if ($desc ne '') {
                   5145:                 $description{$role} = $desc;
                   5146:             } else {
                   5147:                 $description{$role}= $role;
                   5148:             }
                   5149:             $count++;
                   5150:         }
                   5151:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5152:             push(@roles_by_num,$ordered{$item});
                   5153:         }
                   5154:     }
                   5155:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5156: }
                   5157: 
1.1332    raeburn  5158: sub get_my_adhocroles {
1.1333    raeburn  5159:     my ($cid,$checkreg) = @_;
                   5160:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5161:     if ($env{'request.course.id'} eq $cid) {
                   5162:         $cdom = $env{'course.'.$cid.'.domain'};
                   5163:         $cnum = $env{'course.'.$cid.'.num'};
                   5164:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5165:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5166:         $cdom = $1;
                   5167:         $cnum = $2;
                   5168:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5169:                                      $cdom,$cnum);
                   5170:     }
                   5171:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5172:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5173:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5174:         if ($rosterhash{$user} ne '') {
                   5175:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5176:             return ([],{}) if ($type eq 'auto');
                   5177:         }
                   5178:     }
                   5179:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  5180:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  5181:             my $then=$env{'user.login.time'};
                   5182:             my $update=$env{'user.update.time'};
1.1335    raeburn  5183:             if (!$update) {
                   5184:                 $update = $then;
                   5185:             }
                   5186:             my @liveroles;
1.1334    raeburn  5187:             foreach my $role ('dh','da') {
                   5188:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  5189:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  5190:                     my $limit = $update;
                   5191:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5192:                         $limit = $then;
                   5193:                     }
1.1335    raeburn  5194:                     my $activerole = 1;
                   5195:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5196:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5197:                     if ($activerole) {
                   5198:                         push(@liveroles,$role);
                   5199:                     }
1.1334    raeburn  5200:                 }
1.1332    raeburn  5201:             }
1.1335    raeburn  5202:             if (@liveroles) {
1.1332    raeburn  5203:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  5204:                     my ($accessref,$accessinfo,%access_in_dom);
                   5205:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5206:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5207:                         if (@{$roles_by_num}) {
1.1332    raeburn  5208:                             my %settings;
                   5209:                             if ($env{'request.course.id'} eq $cid) {
                   5210:                                 foreach my $envkey (keys(%env)) {
                   5211:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5212:                                         $settings{$1} = $env{$envkey};
                   5213:                                     }
                   5214:                                 }
                   5215:                             } else {
                   5216:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5217:                             }
                   5218:                             my %setincrs;
                   5219:                             if ($settings{'internal.adhocaccess'}) {
                   5220:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5221:                             }
                   5222:                             my @statuses;
                   5223:                             if ($env{'environment.inststatus'}) {
                   5224:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5225:                             }
                   5226:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  5227:                             if (ref($accessref) eq 'HASH') {
                   5228:                                 %access_in_dom = %{$accessref};
                   5229:                             }
                   5230:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  5231:                                 my ($curraccess,@okstatus,@personnel);
                   5232:                                 if ($setincrs{$role}) {
                   5233:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5234:                                     if ($curraccess eq 'status') {
                   5235:                                         @okstatus = split(/\&/,$rest);
                   5236:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5237:                                         @personnel = split(/\&/,$rest);
                   5238:                                     }
                   5239:                                 } else {
                   5240:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  5241:                                     if (ref($accessinfo) eq 'HASH') {
                   5242:                                         if ($curraccess eq 'status') {
                   5243:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5244:                                                 @okstatus = @{$accessinfo->{$role}};
                   5245:                                             }
                   5246:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5247:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5248:                                                 @personnel = @{$accessinfo->{$role}};
                   5249:                                             }
1.1332    raeburn  5250:                                         }
                   5251:                                     }
                   5252:                                 }
                   5253:                                 if ($curraccess eq 'none') {
                   5254:                                     next;
                   5255:                                 } elsif ($curraccess eq 'all') {
                   5256:                                     push(@possroles,$role);
1.1336    raeburn  5257:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  5258:                                     if (grep(/^dh$/,@liveroles)) {
                   5259:                                         push(@possroles,$role);
                   5260:                                     } else {
                   5261:                                         next;
                   5262:                                     }
1.1336    raeburn  5263:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  5264:                                     if (grep(/^da$/,@liveroles)) {
                   5265:                                         push(@possroles,$role);
                   5266:                                     } else {
                   5267:                                         next;
                   5268:                                     }
1.1332    raeburn  5269:                                 } elsif ($curraccess eq 'status') {
                   5270:                                     if (@okstatus) {
                   5271:                                         if (!@statuses) {
                   5272:                                             if (grep(/^default$/,@okstatus)) {
                   5273:                                                 push(@possroles,$role);
                   5274:                                             }
                   5275:                                         } else {
                   5276:                                             foreach my $status (@okstatus) {
                   5277:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5278:                                                     push(@possroles,$role);
                   5279:                                                     last;
                   5280:                                                 }
                   5281:                                             }
                   5282:                                         }
                   5283:                                     }
                   5284:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5285:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5286:                                         if ($curraccess eq 'exc') {
                   5287:                                             push(@possroles,$role);
                   5288:                                         }
                   5289:                                     } elsif ($curraccess eq 'inc') {
                   5290:                                         push(@possroles,$role);
                   5291:                                     }
                   5292:                                 }
                   5293:                             }
                   5294:                         }
                   5295:                     }
                   5296:                 }
                   5297:             }
                   5298:         }
                   5299:     }
1.1333    raeburn  5300:     unless (ref($description) eq 'HASH') {
                   5301:         if (ref($roles_by_num) eq 'ARRAY') {
                   5302:             my %desc;
                   5303:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5304:             $description = \%desc;
                   5305:         } else {
                   5306:             $description = {};
                   5307:         }
                   5308:     }
                   5309:     return (\@possroles,$description);
1.1332    raeburn  5310: }
                   5311: 
1.399     www      5312: # ----------------------------------------------------- Frontpage Announcements
                   5313: #
                   5314: #
                   5315: 
                   5316: sub postannounce {
                   5317:     my ($server,$text)=@_;
1.844     albertel 5318:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5319:     unless ($text=~/\w/) { $text=''; }
                   5320:     return &reply('setannounce:'.&escape($text),$server);
                   5321: }
                   5322: 
                   5323: sub getannounce {
1.448     albertel 5324: 
1.1359    raeburn  5325:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5326: 	my $announcement='';
1.800     albertel 5327: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5328: 	close($fh);
1.399     www      5329: 	if ($announcement=~/\w/) { 
                   5330: 	    return 
                   5331:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5332:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5333: 	} else {
                   5334: 	    return '';
                   5335: 	}
                   5336:     } else {
                   5337: 	return '';
                   5338:     }
1.351     www      5339: }
1.353     www      5340: 
                   5341: # ---------------------------------------------------------- Course ID routines
                   5342: # Deal with domain's nohist_courseid.db files
                   5343: #
                   5344: 
                   5345: sub courseidput {
1.921     raeburn  5346:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5347:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5348:     my $outcome;
                   5349:     if ($caller eq 'timeonly') {
                   5350:         my $cids = '';
                   5351:         foreach my $item (keys(%$storehash)) {
                   5352:             $cids.=&escape($item).'&';
                   5353:         }
                   5354:         $cids=~s/\&$//;
                   5355:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5356:                           $coursehome);       
                   5357:     } else {
                   5358:         my $items = '';
                   5359:         foreach my $item (keys(%$storehash)) {
                   5360:             $items.= &escape($item).'='.
                   5361:                      &freeze_escape($$storehash{$item}).'&';
                   5362:         }
                   5363:         $items=~s/\&$//;
                   5364:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5365:                           $coursehome);
1.918     raeburn  5366:     }
                   5367:     if ($outcome eq 'unknown_cmd') {
                   5368:         my $what;
                   5369:         foreach my $cid (keys(%$storehash)) {
                   5370:             $what .= &escape($cid).'=';
1.921     raeburn  5371:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5372:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5373:             }
                   5374:             $what =~ s/\:$/&/;
                   5375:         }
                   5376:         $what =~ s/\&$//;  
                   5377:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5378:     } else {
                   5379:         return $outcome;
                   5380:     }
1.353     www      5381: }
                   5382: 
                   5383: sub courseiddump {
1.921     raeburn  5384:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5385:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5386:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  5387:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  5388:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5389:     my $as_hash = 1;
                   5390:     my %returnhash;
                   5391:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5392:     my %libserv = &all_library();
                   5393:     foreach my $tryserver (keys(%libserv)) {
                   5394:         if ( (  $hostidflag == 1 
                   5395: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5396: 	     || (!defined($hostidflag)) ) {
                   5397: 
1.918     raeburn  5398: 	    if (($domfilter eq '') ||
                   5399: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5400:                 my $rep;
                   5401:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5402:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5403:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5404:                                 &escape($descfilter), &escape($instcodefilter), 
                   5405:                                 &escape($ownerfilter), &escape($coursefilter),
                   5406:                                 &escape($typefilter), &escape($regexp_ok), 
                   5407:                                 $as_hash, &escape($selfenrollonly), 
                   5408:                                 &escape($catfilter), $showhidden, $caller, 
                   5409:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5410:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5411:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5412:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5413:                 } else {
                   5414:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5415:                              $sincefilter.':'.&escape($descfilter).':'.
                   5416:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5417:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5418:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5419:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5420:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5421:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5422:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5423:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5424:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5425:                 }
                   5426:                      
1.918     raeburn  5427:                 my @pairs=split(/\&/,$rep);
                   5428:                 foreach my $item (@pairs) {
                   5429:                     my ($key,$value)=split(/\=/,$item,2);
                   5430:                     $key = &unescape($key);
                   5431:                     next if ($key =~ /^error: 2 /);
                   5432:                     my $result = &thaw_unescape($value);
                   5433:                     if (ref($result) eq 'HASH') {
                   5434:                         $returnhash{$key}=$result;
                   5435:                     } else {
1.921     raeburn  5436:                         my @responses = split(/:/,$value);
                   5437:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5438:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5439:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5440:                         }
1.1008    raeburn  5441:                     }
1.353     www      5442:                 }
                   5443:             }
                   5444:         }
                   5445:     }
                   5446:     return %returnhash;
                   5447: }
                   5448: 
1.1055    raeburn  5449: sub courselastaccess {
                   5450:     my ($cdom,$cnum,$hostidref) = @_;
                   5451:     my %returnhash;
                   5452:     if ($cdom && $cnum) {
                   5453:         my $chome = &homeserver($cnum,$cdom);
                   5454:         if ($chome ne 'no_host') {
                   5455:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5456:             &extract_lastaccess(\%returnhash,$rep);
                   5457:         }
                   5458:     } else {
                   5459:         if (!$cdom) { $cdom=''; }
                   5460:         my %libserv = &all_library();
                   5461:         foreach my $tryserver (keys(%libserv)) {
                   5462:             if (ref($hostidref) eq 'ARRAY') {
                   5463:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5464:             } 
                   5465:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5466:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5467:                 &extract_lastaccess(\%returnhash,$rep);
                   5468:             }
                   5469:         }
                   5470:     }
                   5471:     return %returnhash;
                   5472: }
                   5473: 
                   5474: sub extract_lastaccess {
                   5475:     my ($returnhash,$rep) = @_;
                   5476:     if (ref($returnhash) eq 'HASH') {
                   5477:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5478:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5479:                  $rep eq '') {
                   5480:             my @pairs=split(/\&/,$rep);
                   5481:             foreach my $item (@pairs) {
                   5482:                 my ($key,$value)=split(/\=/,$item,2);
                   5483:                 $key = &unescape($key);
                   5484:                 next if ($key =~ /^error: 2 /);
                   5485:                 $returnhash->{$key} = &thaw_unescape($value);
                   5486:             }
                   5487:         }
                   5488:     }
                   5489:     return;
                   5490: }
                   5491: 
1.658     raeburn  5492: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5493: 
                   5494: sub dcmailput {
1.685     raeburn  5495:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5496:     my $status = &Apache::lonnet::critical(
1.740     www      5497:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5498:        &escape($message),$server);
1.662     raeburn  5499:     return $status;
                   5500: }
                   5501: 
1.658     raeburn  5502: sub dcmaildump {
                   5503:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5504:     my %returnhash=();
1.846     albertel 5505: 
                   5506:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5507:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5508:                                                          &escape($enddate).':';
                   5509: 	my @esc_senders=map { &escape($_)} @$senders;
                   5510: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5511: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5512:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5513:             if (($key) && ($value)) {
                   5514:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5515:             }
                   5516:         }
                   5517:     }
                   5518:     return %returnhash;
                   5519: }
1.662     raeburn  5520: # ---------------------------------------------------------- Domain roles
                   5521: 
                   5522: sub get_domain_roles {
                   5523:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5524:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5525:         $startdate = '.';
                   5526:     }
1.1018    raeburn  5527:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5528:         $enddate = '.';
                   5529:     }
1.922     raeburn  5530:     my $rolelist;
                   5531:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5532:         $rolelist = join('&',@{$roles});
1.922     raeburn  5533:     }
1.662     raeburn  5534:     my %personnel = ();
1.841     albertel 5535: 
                   5536:     my %servers = &get_servers($dom,'library');
                   5537:     foreach my $tryserver (keys(%servers)) {
                   5538: 	%{$personnel{$tryserver}}=();
                   5539: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5540: 					    &escape($startdate).':'.
                   5541: 					    &escape($enddate).':'.
                   5542: 					    &escape($rolelist), $tryserver))) {
                   5543: 	    my ($key,$value) = split(/\=/,$line,2);
                   5544: 	    if (($key) && ($value)) {
                   5545: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5546: 	    }
                   5547: 	}
1.662     raeburn  5548:     }
                   5549:     return %personnel;
                   5550: }
1.658     raeburn  5551: 
1.1332    raeburn  5552: sub get_active_domroles {
                   5553:     my ($dom,$roles) = @_;
                   5554:     return () unless (ref($roles) eq 'ARRAY');
                   5555:     my $now = time;
                   5556:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5557:     my %domroles;
                   5558:     foreach my $server (keys(%dompersonnel)) {
                   5559:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5560:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5561:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5562:         }
                   5563:     }
                   5564:     return %domroles;
                   5565: }
                   5566: 
1.1057    www      5567: # ----------------------------------------------------------- Interval timing 
1.149     www      5568: 
1.1153    www      5569: {
                   5570: # Caches needed for speedup of navmaps
                   5571: # We don't want to cache this for very long at all (5 seconds at most)
                   5572: # 
                   5573: # The user for whom we cache
                   5574: my $cachedkey='';
                   5575: # The cached times for this user
                   5576: my %cachedtimes=();
                   5577: # When this was last done
1.1282    raeburn  5578: my $cachedtime='';
1.1153    www      5579: 
                   5580: sub load_all_first_access {
1.1308    raeburn  5581:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5582:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5583:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5584:         (!$ignorecache)) {
1.1154    raeburn  5585:         return;
                   5586:     }
                   5587:     $cachedtime=time;
                   5588:     $cachedkey=$uname.':'.$udom;
                   5589:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5590: }
                   5591: 
1.504     albertel 5592: sub get_first_access {
1.1308    raeburn  5593:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5594:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5595:     if ($argsymb) { $symb=$argsymb; }
                   5596:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5597:     if ($argmap) { $map = $argmap; }
1.926     albertel 5598:     if ($type eq 'course') {
                   5599: 	$res='course';
                   5600:     } elsif ($type eq 'map') {
1.588     albertel 5601: 	$res=&symbread($map);
                   5602:     } else {
                   5603: 	$res=$symb;
                   5604:     }
1.1308    raeburn  5605:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5606:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5607: }
                   5608: 
                   5609: sub set_first_access {
1.1162    raeburn  5610:     my ($type,$interval)=@_;
1.790     albertel 5611:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5612:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5613:     if ($type eq 'course') {
                   5614: 	$res='course';
                   5615:     } elsif ($type eq 'map') {
1.588     albertel 5616: 	$res=&symbread($map);
                   5617:     } else {
                   5618: 	$res=$symb;
                   5619:     }
1.1153    www      5620:     $cachedkey='';
1.1162    raeburn  5621:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  5622:     if ($firstaccess) {
                   5623:         &logthis("First access time already set ($firstaccess) when attempting ".
1.1393    raeburn  5624:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5625:                  "in $courseid");
1.1386    raeburn  5626:         return 'already_set';
                   5627:     } else {
1.1162    raeburn  5628:         my $start = time;
                   5629: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5630:                           $udom,$uname);
                   5631:         if ($putres eq 'ok') {
                   5632:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5633:                  $udom,$uname); 
                   5634:             &appenv(
                   5635:                      {
                   5636:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5637:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5638:                      }
                   5639:                   );
1.1365    raeburn  5640:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5641:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5642:             }
1.1386    raeburn  5643:         } elsif ($putres ne 'refused') {
                   5644:             &logthis("Result: $putres when attempting to set first access time ".
                   5645:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5646:         }
                   5647:         return $putres;
1.505     albertel 5648:     }
                   5649:     return 'already_set';
1.504     albertel 5650: }
1.1153    www      5651: }
1.1282    raeburn  5652: 
1.110     www      5653: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5654: 
                   5655: sub expirespread {
                   5656:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5657:     my $cid=$env{'request.course.id'}; 
1.110     www      5658:     if ($cid) {
                   5659:        my $now=time;
                   5660:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5661:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5662:                             $env{'course.'.$cid.'.num'}.
1.110     www      5663: 	        	    ':nohist_expirationdates:'.
                   5664:                             &escape($key).'='.$now,
1.620     albertel 5665:                             $env{'course.'.$cid.'.home'})
1.110     www      5666:     }
                   5667:     return 'ok';
1.14      www      5668: }
                   5669: 
1.109     www      5670: # ----------------------------------------------------- Devalidate Spreadsheets
                   5671: 
                   5672: sub devalidate {
1.325     www      5673:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5674:     my $cid=$env{'request.course.id'}; 
1.109     www      5675:     if ($cid) {
1.391     matthew  5676:         # delete the stored spreadsheets for
                   5677:         # - the student level sheet of this user in course's homespace
                   5678:         # - the assessment level sheet for this resource 
                   5679:         #   for this user in user's homespace
1.553     albertel 5680: 	# - current conditional state info
1.325     www      5681: 	my $key=$uname.':'.$udom.':';
1.109     www      5682:         my $status=
1.299     matthew  5683: 	    &del('nohist_calculatedsheets',
1.391     matthew  5684: 		 [$key.'studentcalc:'],
1.620     albertel 5685: 		 $env{'course.'.$cid.'.domain'},
                   5686: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5687: 		.' '.
                   5688: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5689: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5690:         unless ($status eq 'ok ok') {
                   5691:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5692:                     $uname.' at '.$udom.' for '.
1.109     www      5693: 		    $symb.': '.$status);
1.133     albertel 5694:         }
1.553     albertel 5695: 	&delenv('user.state.'.$cid);
1.109     www      5696:     }
                   5697: }
                   5698: 
1.265     albertel 5699: sub get_scalar {
                   5700:     my ($string,$end) = @_;
                   5701:     my $value;
                   5702:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5703: 	$value = $1;
                   5704:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5705: 	$value = $1;
                   5706:     }
                   5707:     return &unescape($value);
                   5708: }
                   5709: 
                   5710: sub array2str {
                   5711:   my (@array) = @_;
                   5712:   my $result=&arrayref2str(\@array);
                   5713:   $result=~s/^__ARRAY_REF__//;
                   5714:   $result=~s/__END_ARRAY_REF__$//;
                   5715:   return $result;
                   5716: }
                   5717: 
1.204     albertel 5718: sub arrayref2str {
                   5719:   my ($arrayref) = @_;
1.265     albertel 5720:   my $result='__ARRAY_REF__';
1.204     albertel 5721:   foreach my $elem (@$arrayref) {
1.265     albertel 5722:     if(ref($elem) eq 'ARRAY') {
                   5723:       $result.=&arrayref2str($elem).'&';
                   5724:     } elsif(ref($elem) eq 'HASH') {
                   5725:       $result.=&hashref2str($elem).'&';
                   5726:     } elsif(ref($elem)) {
                   5727:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5728:     } else {
                   5729:       $result.=&escape($elem).'&';
                   5730:     }
                   5731:   }
                   5732:   $result=~s/\&$//;
1.265     albertel 5733:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5734:   return $result;
                   5735: }
                   5736: 
1.168     albertel 5737: sub hash2str {
1.204     albertel 5738:   my (%hash) = @_;
                   5739:   my $result=&hashref2str(\%hash);
1.265     albertel 5740:   $result=~s/^__HASH_REF__//;
                   5741:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5742:   return $result;
                   5743: }
                   5744: 
                   5745: sub hashref2str {
                   5746:   my ($hashref)=@_;
1.265     albertel 5747:   my $result='__HASH_REF__';
1.800     albertel 5748:   foreach my $key (sort(keys(%$hashref))) {
                   5749:     if (ref($key) eq 'ARRAY') {
                   5750:       $result.=&arrayref2str($key).'=';
                   5751:     } elsif (ref($key) eq 'HASH') {
                   5752:       $result.=&hashref2str($key).'=';
                   5753:     } elsif (ref($key)) {
1.265     albertel 5754:       $result.='=';
1.800     albertel 5755:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5756:     } else {
1.1132    raeburn  5757: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5758:     }
                   5759: 
1.800     albertel 5760:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5761:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5762:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5763:       $result.=&hashref2str($hashref->{$key}).'&';
                   5764:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5765:        $result.='&';
1.800     albertel 5766:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5767:     } else {
1.800     albertel 5768:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5769:     }
                   5770:   }
1.168     albertel 5771:   $result=~s/\&$//;
1.265     albertel 5772:   $result .= '__END_HASH_REF__';
1.168     albertel 5773:   return $result;
                   5774: }
                   5775: 
                   5776: sub str2hash {
1.265     albertel 5777:     my ($string)=@_;
                   5778:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5779:     return %$hash;
                   5780: }
                   5781: 
                   5782: sub str2hashref {
1.168     albertel 5783:   my ($string) = @_;
1.265     albertel 5784: 
                   5785:   my %hash;
                   5786: 
                   5787:   if($string !~ /^__HASH_REF__/) {
                   5788:       if (! ($string eq '' || !defined($string))) {
                   5789: 	  $hash{'error'}='Not hash reference';
                   5790:       }
                   5791:       return (\%hash, $string);
                   5792:   }
                   5793: 
                   5794:   $string =~ s/^__HASH_REF__//;
                   5795: 
                   5796:   while($string !~ /^__END_HASH_REF__/) {
                   5797:       #key
                   5798:       my $key='';
                   5799:       if($string =~ /^__HASH_REF__/) {
                   5800:           ($key, $string)=&str2hashref($string);
                   5801:           if(defined($key->{'error'})) {
                   5802:               $hash{'error'}='Bad data';
                   5803:               return (\%hash, $string);
                   5804:           }
                   5805:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5806:           ($key, $string)=&str2arrayref($string);
                   5807:           if($key->[0] eq 'Array reference error') {
                   5808:               $hash{'error'}='Bad data';
                   5809:               return (\%hash, $string);
                   5810:           }
                   5811:       } else {
                   5812:           $string =~ s/^(.*?)=//;
1.267     albertel 5813: 	  $key=&unescape($1);
1.265     albertel 5814:       }
                   5815:       $string =~ s/^=//;
                   5816: 
                   5817:       #value
                   5818:       my $value='';
                   5819:       if($string =~ /^__HASH_REF__/) {
                   5820:           ($value, $string)=&str2hashref($string);
                   5821:           if(defined($value->{'error'})) {
                   5822:               $hash{'error'}='Bad data';
                   5823:               return (\%hash, $string);
                   5824:           }
                   5825:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5826:           ($value, $string)=&str2arrayref($string);
                   5827:           if($value->[0] eq 'Array reference error') {
                   5828:               $hash{'error'}='Bad data';
                   5829:               return (\%hash, $string);
                   5830:           }
                   5831:       } else {
                   5832: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5833:       }
                   5834:       $string =~ s/^&//;
                   5835: 
                   5836:       $hash{$key}=$value;
1.204     albertel 5837:   }
1.265     albertel 5838: 
                   5839:   $string =~ s/^__END_HASH_REF__//;
                   5840: 
                   5841:   return (\%hash, $string);
1.204     albertel 5842: }
                   5843: 
                   5844: sub str2array {
1.265     albertel 5845:     my ($string)=@_;
                   5846:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5847:     return @$array;
                   5848: }
                   5849: 
                   5850: sub str2arrayref {
1.204     albertel 5851:   my ($string) = @_;
1.265     albertel 5852:   my @array;
                   5853: 
                   5854:   if($string !~ /^__ARRAY_REF__/) {
                   5855:       if (! ($string eq '' || !defined($string))) {
                   5856: 	  $array[0]='Array reference error';
                   5857:       }
                   5858:       return (\@array, $string);
                   5859:   }
                   5860: 
                   5861:   $string =~ s/^__ARRAY_REF__//;
                   5862: 
                   5863:   while($string !~ /^__END_ARRAY_REF__/) {
                   5864:       my $value='';
                   5865:       if($string =~ /^__HASH_REF__/) {
                   5866:           ($value, $string)=&str2hashref($string);
                   5867:           if(defined($value->{'error'})) {
                   5868:               $array[0] ='Array reference error';
                   5869:               return (\@array, $string);
                   5870:           }
                   5871:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5872:           ($value, $string)=&str2arrayref($string);
                   5873:           if($value->[0] eq 'Array reference error') {
                   5874:               $array[0] ='Array reference error';
                   5875:               return (\@array, $string);
                   5876:           }
                   5877:       } else {
                   5878: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5879:       }
                   5880:       $string =~ s/^&//;
                   5881: 
                   5882:       push(@array, $value);
1.191     harris41 5883:   }
1.265     albertel 5884: 
                   5885:   $string =~ s/^__END_ARRAY_REF__//;
                   5886: 
                   5887:   return (\@array, $string);
1.168     albertel 5888: }
                   5889: 
1.167     albertel 5890: # -------------------------------------------------------------------Temp Store
                   5891: 
1.168     albertel 5892: sub tmpreset {
                   5893:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5894:   if (!$symb) {
                   5895:     $symb=&symbread();
1.620     albertel 5896:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5897:   }
                   5898:   $symb=escape($symb);
                   5899: 
1.620     albertel 5900:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5901:   $namespace=~s/\//\_/g;
                   5902:   $namespace=~s/\W//g;
                   5903: 
1.620     albertel 5904:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5905:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5906:   if ($domain eq 'public' && $stuname eq 'public') {
                   5907:       $stuname=$ENV{'REMOTE_ADDR'};
                   5908:   }
1.1117    foxr     5909:   my $path=LONCAPA::tempdir();
1.168     albertel 5910:   my %hash;
                   5911:   if (tie(%hash,'GDBM_File',
                   5912: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5913: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5914:     foreach my $key (keys(%hash)) {
1.180     albertel 5915:       if ($key=~ /:$symb/) {
1.168     albertel 5916: 	delete($hash{$key});
                   5917:       }
                   5918:     }
                   5919:   }
                   5920: }
                   5921: 
1.167     albertel 5922: sub tmpstore {
1.168     albertel 5923:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5924: 
                   5925:   if (!$symb) {
                   5926:     $symb=&symbread();
1.620     albertel 5927:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5928:   }
                   5929:   $symb=escape($symb);
                   5930: 
                   5931:   if (!$namespace) {
                   5932:     # I don't think we would ever want to store this for a course.
                   5933:     # it seems this will only be used if we don't have a course.
1.620     albertel 5934:     #$namespace=$env{'request.course.id'};
1.168     albertel 5935:     #if (!$namespace) {
1.620     albertel 5936:       $namespace=$env{'request.state'};
1.168     albertel 5937:     #}
                   5938:   }
                   5939:   $namespace=~s/\//\_/g;
                   5940:   $namespace=~s/\W//g;
1.620     albertel 5941:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5942:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5943:   if ($domain eq 'public' && $stuname eq 'public') {
                   5944:       $stuname=$ENV{'REMOTE_ADDR'};
                   5945:   }
1.168     albertel 5946:   my $now=time;
                   5947:   my %hash;
1.1117    foxr     5948:   my $path=LONCAPA::tempdir();
1.168     albertel 5949:   if (tie(%hash,'GDBM_File',
                   5950: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5951: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5952:     $hash{"version:$symb"}++;
                   5953:     my $version=$hash{"version:$symb"};
                   5954:     my $allkeys=''; 
                   5955:     foreach my $key (keys(%$storehash)) {
                   5956:       $allkeys.=$key.':';
1.591     albertel 5957:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5958:     }
                   5959:     $hash{"$version:$symb:timestamp"}=$now;
                   5960:     $allkeys.='timestamp';
                   5961:     $hash{"$version:keys:$symb"}=$allkeys;
                   5962:     if (untie(%hash)) {
                   5963:       return 'ok';
                   5964:     } else {
                   5965:       return "error:$!";
                   5966:     }
                   5967:   } else {
                   5968:     return "error:$!";
                   5969:   }
                   5970: }
1.167     albertel 5971: 
1.168     albertel 5972: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5973: 
1.168     albertel 5974: sub tmprestore {
                   5975:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5976: 
1.168     albertel 5977:   if (!$symb) {
                   5978:     $symb=&symbread();
1.620     albertel 5979:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5980:   }
                   5981:   $symb=escape($symb);
                   5982: 
1.620     albertel 5983:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5984: 
1.620     albertel 5985:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5986:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5987:   if ($domain eq 'public' && $stuname eq 'public') {
                   5988:       $stuname=$ENV{'REMOTE_ADDR'};
                   5989:   }
1.168     albertel 5990:   my %returnhash;
                   5991:   $namespace=~s/\//\_/g;
                   5992:   $namespace=~s/\W//g;
                   5993:   my %hash;
1.1117    foxr     5994:   my $path=LONCAPA::tempdir();
1.168     albertel 5995:   if (tie(%hash,'GDBM_File',
                   5996: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5997: 	  &GDBM_READER(),0640)) {
1.168     albertel 5998:     my $version=$hash{"version:$symb"};
                   5999:     $returnhash{'version'}=$version;
                   6000:     my $scope;
                   6001:     for ($scope=1;$scope<=$version;$scope++) {
                   6002:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6003:       my @keys=split(/:/,$vkeys);
                   6004:       my $key;
                   6005:       $returnhash{"$scope:keys"}=$vkeys;
                   6006:       foreach $key (@keys) {
1.591     albertel 6007: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6008: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6009:       }
                   6010:     }
1.168     albertel 6011:     if (!(untie(%hash))) {
                   6012:       return "error:$!";
                   6013:     }
                   6014:   } else {
                   6015:     return "error:$!";
                   6016:   }
                   6017:   return %returnhash;
1.167     albertel 6018: }
                   6019: 
1.9       www      6020: # ----------------------------------------------------------------------- Store
                   6021: 
                   6022: sub store {
1.1269    raeburn  6023:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6024:     my $home='';
                   6025: 
1.168     albertel 6026:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6027: 
1.213     www      6028:     $symb=&symbclean($symb);
1.122     albertel 6029:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6030: 
1.620     albertel 6031:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6032:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6033: 
                   6034:     &devalidate($symb,$stuname,$domain);
1.109     www      6035: 
                   6036:     $symb=escape($symb);
1.187     www      6037:     if (!$namespace) { 
1.620     albertel 6038:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6039:           return ''; 
                   6040:        } 
                   6041:     }
1.620     albertel 6042:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6043: 
                   6044:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6045:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6046: 
1.12      www      6047:     my $namevalue='';
1.800     albertel 6048:     foreach my $key (keys(%$storehash)) {
                   6049:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6050:     }
1.12      www      6051:     $namevalue=~s/\&$//;
1.187     www      6052:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  6053:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6054: }
                   6055: 
1.47      www      6056: # -------------------------------------------------------------- Critical Store
                   6057: 
                   6058: sub cstore {
1.1269    raeburn  6059:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6060:     my $home='';
                   6061: 
1.168     albertel 6062:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6063: 
1.213     www      6064:     $symb=&symbclean($symb);
1.122     albertel 6065:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6066: 
1.620     albertel 6067:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6068:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6069: 
                   6070:     &devalidate($symb,$stuname,$domain);
1.109     www      6071: 
                   6072:     $symb=escape($symb);
1.187     www      6073:     if (!$namespace) { 
1.620     albertel 6074:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6075:           return ''; 
                   6076:        } 
                   6077:     }
1.620     albertel 6078:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6079: 
                   6080:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6081:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6082: 
1.47      www      6083:     my $namevalue='';
1.800     albertel 6084:     foreach my $key (keys(%$storehash)) {
                   6085:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6086:     }
1.47      www      6087:     $namevalue=~s/\&$//;
1.187     www      6088:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6089:     return critical
1.1269    raeburn  6090:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6091: }
                   6092: 
1.9       www      6093: # --------------------------------------------------------------------- Restore
                   6094: 
                   6095: sub restore {
1.124     www      6096:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6097:     my $home='';
                   6098: 
1.168     albertel 6099:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6100: 
1.122     albertel 6101:     if (!$symb) {
1.1224    raeburn  6102:         return if ($namespace eq 'courserequests');
                   6103:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6104:     } else {
1.1224    raeburn  6105:         unless ($namespace eq 'courserequests') {
                   6106:             $symb=&escape(&symbclean($symb));
                   6107:         }
1.122     albertel 6108:     }
1.188     www      6109:     if (!$namespace) { 
1.620     albertel 6110:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6111:           return ''; 
                   6112:        } 
                   6113:     }
1.620     albertel 6114:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6115:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6116:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6117:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6118: 
1.12      www      6119:     my %returnhash=();
1.800     albertel 6120:     foreach my $line (split(/\&/,$answer)) {
                   6121: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6122:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6123:     }
1.75      www      6124:     my $version;
                   6125:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6126:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6127:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6128:        }
1.75      www      6129:     }
1.13      www      6130:     return %returnhash;
1.34      www      6131: }
                   6132: 
                   6133: # ---------------------------------------------------------- Course Description
1.1118    foxr     6134: #
                   6135: #  
1.34      www      6136: 
                   6137: sub coursedescription {
1.731     albertel 6138:     my ($courseid,$args)=@_;
1.34      www      6139:     $courseid=~s/^\///;
1.49      www      6140:     $courseid=~s/\_/\//g;
1.34      www      6141:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6142:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6143:     my $normalid=$cdomain.'_'.$cnum;
                   6144:     # need to always cache even if we get errors otherwise we keep 
                   6145:     # trying and trying and trying to get the course description.
                   6146:     my %envhash=();
                   6147:     my %returnhash=();
1.731     albertel 6148:     
                   6149:     my $expiretime=600;
                   6150:     if ($env{'request.course.id'} eq $normalid) {
                   6151: 	$expiretime=120;
                   6152:     }
                   6153: 
                   6154:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6155:     if (!$args->{'freshen_cache'}
                   6156: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6157: 	foreach my $key (keys(%env)) {
                   6158: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6159: 	    my ($setting) = $1;
                   6160: 	    $returnhash{$setting} = $env{$key};
                   6161: 	}
                   6162: 	return %returnhash;
                   6163:     }
                   6164: 
1.1118    foxr     6165:     # get the data again
                   6166: 
1.731     albertel 6167:     if (!$args->{'one_time'}) {
                   6168: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6169:     }
1.811     albertel 6170: 
1.34      www      6171:     if ($chome ne 'no_host') {
1.302     albertel 6172:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6173:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6174: 	   my $username = $env{'user.name'}; # Defult username
                   6175: 	   if(defined $args->{'user'}) {
                   6176: 	       $username = $args->{'user'};
                   6177: 	   }
1.129     albertel 6178:            $returnhash{'home'}= $chome;
                   6179: 	   $returnhash{'domain'} = $cdomain;
                   6180: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6181:            if (!defined($returnhash{'type'})) {
                   6182:                $returnhash{'type'} = 'Course';
                   6183:            }
1.130     albertel 6184:            while (my ($name,$value) = each %returnhash) {
1.53      www      6185:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6186:            }
1.270     www      6187:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6188:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6189: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6190:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6191:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6192:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6193:        }
                   6194:     }
1.731     albertel 6195:     if (!$args->{'one_time'}) {
1.949     raeburn  6196: 	&appenv(\%envhash);
1.731     albertel 6197:     }
1.302     albertel 6198:     return %returnhash;
1.461     www      6199: }
                   6200: 
1.1080    raeburn  6201: sub update_released_required {
                   6202:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6203:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6204:         $cid = $env{'request.course.id'};
                   6205:         $cdom = $env{'course.'.$cid.'.domain'};
                   6206:         $cnum = $env{'course.'.$cid.'.num'};
                   6207:         $chome = $env{'course.'.$cid.'.home'};
                   6208:     }
                   6209:     if ($needsrelease) {
                   6210:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6211:         my $needsupdate;
                   6212:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6213:             $needsupdate = 1;
                   6214:         } else {
                   6215:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6216:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6217:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6218:                 $needsupdate = 1;
                   6219:             }
                   6220:         }
                   6221:         if ($needsupdate) {
                   6222:             my %needshash = (
                   6223:                              'internal.releaserequired' => $needsrelease,
                   6224:                             );
                   6225:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6226:             if ($putresult eq 'ok') {
                   6227:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6228:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6229:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6230:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6231:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6232:                 }
                   6233:             }
                   6234:         }
                   6235:     }
                   6236:     return;
                   6237: }
                   6238: 
1.461     www      6239: # -------------------------------------------------See if a user is privileged
                   6240: 
                   6241: sub privileged {
1.1219    raeburn  6242:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6243:     my $now = time;
1.1219    raeburn  6244:     my $roles;
                   6245:     if (ref($possroles) eq 'ARRAY') {
                   6246:         $roles = $possroles; 
                   6247:     } else {
                   6248:         $roles = ['dc','su'];
                   6249:     }
                   6250:     if (ref($possdomains) eq 'ARRAY') {
                   6251:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6252:         foreach my $dom (@{$possdomains}) {
                   6253:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6254:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6255:                 foreach my $role (@{$roles}) {
                   6256:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6257:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6258:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6259:                             return 1 unless (($end && $end < $now) ||
                   6260:                                              ($start && $start > $now));
                   6261:                         }
                   6262:                     }
                   6263:                 }
                   6264:             }
                   6265:         }
                   6266:     } else {
                   6267:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6268:         my $now = time;
1.1170    droeschl 6269: 
1.1275    musolffc 6270:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6271:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  6272:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 6273:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  6274:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6275:             }
1.1219    raeburn  6276:         }
                   6277:     }
                   6278:     return 0;
                   6279: }
1.1170    droeschl 6280: 
1.1219    raeburn  6281: sub privileged_by_domain {
                   6282:     my ($domains,$roles) = @_;
                   6283:     my %privileged = ();
                   6284:     my $cachetime = 60*60*24;
                   6285:     my $now = time;
                   6286:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6287:         return %privileged;
                   6288:     }
                   6289:     foreach my $dom (@{$domains}) {
                   6290:         next if (ref($privileged{$dom}) eq 'HASH');
                   6291:         my $needroles;
                   6292:         foreach my $role (@{$roles}) {
                   6293:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6294:             if (defined($cached)) {
                   6295:                 if (ref($result) eq 'HASH') {
                   6296:                     $privileged{$dom}{$role} = $result;
                   6297:                 }
                   6298:             } else {
                   6299:                 $needroles = 1;
                   6300:             }
                   6301:         }
                   6302:         if ($needroles) {
                   6303:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6304:             $privileged{$dom} = {};
                   6305:             foreach my $server (keys(%dompersonnel)) {
                   6306:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6307:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6308:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6309:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6310:                         next if ($end && $end < $now);
                   6311:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   6312:                             $dompersonnel{$server}{$item};
                   6313:                     }
                   6314:                 }
                   6315:             }
                   6316:             if (ref($privileged{$dom}) eq 'HASH') {
                   6317:                 foreach my $role (@{$roles}) {
                   6318:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6319:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6320:                     } else {
                   6321:                         my %hash = ();
                   6322:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6323:                     }
                   6324:                 }
                   6325:             }
                   6326:         }
                   6327:     }
                   6328:     return %privileged;
1.9       www      6329: }
1.1       albertel 6330: 
1.103     harris41 6331: # -------------------------------------------------------- Get user privileges
1.11      www      6332: 
                   6333: sub rolesinit {
1.1169    droeschl 6334:     my ($domain, $username) = @_;
                   6335:     my %userroles = ('user.login.time' => time);
                   6336:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6337: 
                   6338:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6339:     # also, blocking can be triggered by an activating timer
                   6340:     # it's saved in the user's %env.
                   6341:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6342:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6343:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6344:         %timerintchk, %timerintenv);
                   6345: 
1.1162    raeburn  6346:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6347:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6348:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6349:     }
1.1169    droeschl 6350: 
1.1162    raeburn  6351:     foreach my $key (keys(%timerinterval)) {
                   6352:         my ($cid,$rest) = split(/\0/,$key);
                   6353:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6354:     }
1.1169    droeschl 6355: 
1.11      www      6356:     my %allroles=();
1.1162    raeburn  6357:     my %allgroups=();
1.11      www      6358: 
1.1274    raeburn  6359:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6360:         my $role = $rolesdump{$area};
                   6361:         $area =~ s/\_\w\w$//;
                   6362: 
                   6363:         my ($trole, $tend, $tstart, $group_privs);
                   6364: 
                   6365:         if ($role =~ /^cr/) {
                   6366:         # Custom role, defined by a user 
                   6367:         # e.g., user.role.cr/msu/smith/mynewrole
                   6368:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6369:                 $trole = $1;
                   6370:                 ($tend, $tstart) = split('_', $2);
                   6371:             } else {
                   6372:                 $trole = $role;
                   6373:             }
                   6374:         } elsif ($role =~ m|^gr/|) {
                   6375:         # Role of member in a group, defined within a course/community
                   6376:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6377:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6378:             next if $tstart eq '-1';
                   6379:             ($trole, $group_privs) = split(/\//, $trole);
                   6380:             $group_privs = &unescape($group_privs);
                   6381:         } else {
                   6382:         # Just a normal role, defined in roles.tab
                   6383:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6384:         }
                   6385: 
                   6386:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6387:                  $username);
                   6388:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6389: 
                   6390:         # role expired or not available yet?
                   6391:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6392:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6393: 
                   6394:         next if $area eq '' or $trole eq '';
                   6395: 
                   6396:         my $spec = "$trole.$area";
                   6397:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6398: 
                   6399:         if ($trole =~ /^cr\//) {
                   6400:         # Custom role, defined by a user
                   6401:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6402:         } elsif ($trole eq 'gr') {
                   6403:         # Role of a member in a group, defined within a course/community
                   6404:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6405:             next;
                   6406:         } else {
                   6407:         # Normal role, defined in roles.tab
                   6408:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6409:         }
                   6410: 
                   6411:         my $cid = $tdomain.'_'.$trest;
                   6412:         unless ($firstaccchk{$cid}) {
                   6413:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6414:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6415:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6416:                         $coursetimerstarts{$cid}{$item}; 
                   6417:                 }
                   6418:             }
                   6419:             $firstaccchk{$cid} = 1;
                   6420:         }
                   6421:         unless ($timerintchk{$cid}) {
                   6422:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6423:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6424:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6425:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6426:                 }
1.12      www      6427:             }
1.1169    droeschl 6428:             $timerintchk{$cid} = 1;
1.191     harris41 6429:         }
1.11      www      6430:     }
1.1169    droeschl 6431: 
1.1341    raeburn  6432:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6433:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6434:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6435:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6436: 
1.1162    raeburn  6437:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6438: }
                   6439: 
1.567     raeburn  6440: sub set_arearole {
1.1215    raeburn  6441:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6442:     unless ($nolog) {
1.567     raeburn  6443: # log the associated role with the area
1.1215    raeburn  6444:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6445:     }
1.743     albertel 6446:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6447: }
                   6448: 
                   6449: sub custom_roleprivs {
                   6450:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6451:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6452:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6453:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6454:         my ($rdummy,$roledef)=
                   6455:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6456:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6457:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6458:             if (defined($syspriv)) {
1.1043    raeburn  6459:                 if ($trest =~ /^$match_community$/) {
                   6460:                     $syspriv =~ s/bre\&S//; 
                   6461:                 }
1.567     raeburn  6462:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6463:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6464:             }
                   6465:             if ($tdomain ne '') {
                   6466:                 if (defined($dompriv)) {
                   6467:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6468:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6469:                 }
                   6470:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6471:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6472:                         my $rolename = $1;
                   6473:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6474:                     }
1.567     raeburn  6475:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6476:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6477:                 }
                   6478:             }
                   6479:         }
                   6480:     }
                   6481: }
                   6482: 
1.1332    raeburn  6483: sub course_adhocrole_privs {
                   6484:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6485:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6486:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6487:         my (%currprivs,%storeprivs);
                   6488:         foreach my $item (split(/:/,$coursepriv)) {
                   6489:             my ($priv,$restrict) = split(/\&/,$item);
                   6490:             $currprivs{$priv} = $restrict;
                   6491:         }
                   6492:         my (%possadd,%possremove,%full);
                   6493:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6494:             my ($priv,$restrict)=split(/\&/,$item);
                   6495:             $full{$priv} = $restrict;
                   6496:         }
                   6497:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6498:              next if ($item eq '');
                   6499:              my ($rule,$rest) = split(/=/,$item);
                   6500:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6501:              foreach my $priv (split(/:/,$rest)) {
                   6502:                  if ($priv ne '') {
                   6503:                      if ($rule eq 'off') {
                   6504:                          $possremove{$priv} = 1;
                   6505:                      } else {
                   6506:                          $possadd{$priv} = 1;
                   6507:                      }
                   6508:                  }
                   6509:              }
                   6510:          }
                   6511:          foreach my $priv (sort(keys(%full))) {
                   6512:              if (exists($currprivs{$priv})) {
                   6513:                  unless (exists($possremove{$priv})) {
                   6514:                      $storeprivs{$priv} = $currprivs{$priv};
                   6515:                  }
                   6516:              } elsif (exists($possadd{$priv})) {
                   6517:                  $storeprivs{$priv} = $full{$priv};
                   6518:              }
                   6519:          }
                   6520:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6521:      }
                   6522:      return $coursepriv;
                   6523: }
                   6524: 
1.678     raeburn  6525: sub group_roleprivs {
                   6526:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6527:     my $access = 1;
                   6528:     my $now = time;
                   6529:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6530:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6531:     if ($access) {
1.811     albertel 6532:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6533:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6534:     }
                   6535: }
1.567     raeburn  6536: 
                   6537: sub standard_roleprivs {
                   6538:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6539:     if (defined($pr{$trole.':s'})) {
                   6540:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6541:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6542:     }
                   6543:     if ($tdomain ne '') {
                   6544:         if (defined($pr{$trole.':d'})) {
                   6545:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6546:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6547:         }
                   6548:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6549:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6550:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6551:         }
                   6552:     }
                   6553: }
                   6554: 
                   6555: sub set_userprivs {
1.1064    raeburn  6556:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6557:     my $author=0;
                   6558:     my $adv=0;
1.1341    raeburn  6559:     my $rar=0;
1.678     raeburn  6560:     my %grouproles = ();
                   6561:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6562:         my @groupkeys; 
1.1000    raeburn  6563:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6564:             push(@groupkeys,$role);
                   6565:         }
                   6566:         if (ref($groups_roles) eq 'HASH') {
                   6567:             foreach my $key (keys(%{$groups_roles})) {
                   6568:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6569:                     push(@groupkeys,$key);
                   6570:                 }
                   6571:             }
                   6572:         }
                   6573:         if (@groupkeys > 0) {
                   6574:             foreach my $role (@groupkeys) {
                   6575:                 my ($trole,$area,$sec,$extendedarea);
                   6576:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6577:                     $trole = $1;
                   6578:                     $area = $2;
                   6579:                     $sec = $3;
                   6580:                     $extendedarea = $area.$sec;
                   6581:                     if (exists($$allgroups{$area})) {
                   6582:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6583:                             my $spec = $trole.'.'.$extendedarea;
                   6584:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6585:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6586:                         }
1.678     raeburn  6587:                     }
                   6588:                 }
                   6589:             }
                   6590:         }
                   6591:     }
1.800     albertel 6592:     foreach my $group (keys(%grouproles)) {
                   6593:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6594:     }
1.800     albertel 6595:     foreach my $role (keys(%{$allroles})) {
                   6596:         my %thesepriv;
1.941     raeburn  6597:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6598:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6599:             if ($item ne '') {
                   6600:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6601:                 if ($restrictions eq '') {
                   6602:                     $thesepriv{$privilege}='F';
                   6603:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6604:                     $thesepriv{$privilege}.=$restrictions;
                   6605:                 }
                   6606:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6607:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6608:             }
                   6609:         }
                   6610:         my $thesestr='';
1.1104    raeburn  6611:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6612: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6613: 	}
                   6614:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6615:     }
1.1341    raeburn  6616:     return ($author,$adv,$rar);
1.567     raeburn  6617: }
                   6618: 
1.994     raeburn  6619: sub role_status {
1.1104    raeburn  6620:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6621:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6622:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6623:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6624:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6625:             $$where = '/'.$two;
1.994     raeburn  6626:             $$trolecode=$$role.'.'.$$where;
                   6627:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6628:             $$tstatus='is';
1.1104    raeburn  6629:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6630:                 $$tstatus='future';
1.1034    raeburn  6631:                 if ($$tstart<$now) {
                   6632:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6633:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6634:                             my (%allroles,%allgroups,$group_privs,
                   6635:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6636:                             my %userroles = (
                   6637:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6638:                             );
1.1064    raeburn  6639:                             @rolecodes = ('cm'); 
1.1002    raeburn  6640:                             my $spec=$$role.'.'.$$where;
                   6641:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6642:                             if ($$role =~ /^cr\//) {
                   6643:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6644:                                 push(@rolecodes,'cr');
1.1002    raeburn  6645:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6646:                                 push(@rolecodes,$$role);
1.1002    raeburn  6647:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6648:                                                     $env{'user.name'});
1.1064    raeburn  6649:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6650:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6651:                                 $group_privs = &unescape($group_privs);
                   6652:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6653:                                 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  6654:                                 &get_groups_roles($tdomain,$trest,
                   6655:                                                   \%course_roles,\@rolecodes,
                   6656:                                                   \%groups_roles);
1.1002    raeburn  6657:                             } else {
1.1064    raeburn  6658:                                 push(@rolecodes,$$role);
1.1002    raeburn  6659:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6660:                             }
1.1341    raeburn  6661:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6662:                                                                    \%groups_roles);
1.1064    raeburn  6663:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6664:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6665:                         }
                   6666:                     }
1.1034    raeburn  6667:                     $$tstatus = 'is';
1.1002    raeburn  6668:                 }
1.994     raeburn  6669:             }
                   6670:             if ($$tend) {
1.1104    raeburn  6671:                 if ($$tend<$update) {
1.994     raeburn  6672:                     $$tstatus='expired';
                   6673:                 } elsif ($$tend<$now) {
                   6674:                     $$tstatus='will_not';
                   6675:                 }
                   6676:             }
                   6677:         }
                   6678:     }
                   6679: }
                   6680: 
1.1104    raeburn  6681: sub get_groups_roles {
                   6682:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6683:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6684:                   (ref($rolecodes) eq 'ARRAY') && 
                   6685:                   (ref($groups_roles) eq 'HASH')); 
                   6686:     if (keys(%{$cdom_courseroles}) > 0) {
                   6687:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6688:         if ($cdom ne '' && $cnum ne '') {
                   6689:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6690:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6691:                     my $crsrole = $1;
                   6692:                     my $crssec = $2;
                   6693:                     if ($crsrole =~ /^cr/) {
                   6694:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6695:                             push(@{$rolecodes},'cr');
                   6696:                         }
                   6697:                     } else {
                   6698:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6699:                             push(@{$rolecodes},$crsrole);
                   6700:                         }
                   6701:                     }
                   6702:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6703:                     if ($crssec ne '') {
                   6704:                         $rolekey .= "/$crssec";
                   6705:                     }
                   6706:                     $rolekey .= './';
                   6707:                     $groups_roles->{$rolekey} = $rolecodes;
                   6708:                 }
                   6709:             }
                   6710:         }
                   6711:     }
                   6712:     return;
                   6713: }
                   6714: 
                   6715: sub delete_env_groupprivs {
                   6716:     my ($where,$courseroles,$possroles) = @_;
                   6717:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6718:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6719:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6720:         %{$courseroles->{$udom}} =
                   6721:             &get_my_roles('','','userroles',['active'],
                   6722:                           $possroles,[$udom],1);
                   6723:     }
                   6724:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6725:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6726:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6727:             my $area = '/'.$cdom.'/'.$cnum;
                   6728:             my $privkey = "user.priv.$crsrole.$area";
                   6729:             if ($crssec ne '') {
                   6730:                 $privkey .= '/'.$crssec;
                   6731:             }
                   6732:             $privkey .= ".$area/$group";
                   6733:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6734:         }
                   6735:     }
                   6736:     return;
                   6737: }
                   6738: 
1.994     raeburn  6739: sub check_adhoc_privs {
1.1329    raeburn  6740:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6741:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6742:     if ($sec) {
                   6743:         $cckey .= '/'.$sec;
                   6744:     } 
1.1185    raeburn  6745:     my $setprivs;
1.994     raeburn  6746:     if ($env{$cckey}) {
                   6747:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6748:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6749:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6750:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6751:             $setprivs = 1;
1.994     raeburn  6752:         }
                   6753:     } else {
1.1330    raeburn  6754:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6755:         $setprivs = 1;
1.994     raeburn  6756:     }
1.1185    raeburn  6757:     return $setprivs;
1.994     raeburn  6758: }
                   6759: 
                   6760: sub set_adhoc_privileges {
1.1326    raeburn  6761: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6762:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6763:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6764:     if ($sec ne '') {
                   6765:         $area .= '/'.$sec;
                   6766:     }
1.994     raeburn  6767:     my $spec = $role.'.'.$area;
                   6768:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6769:                                   $env{'user.name'},1);
1.1326    raeburn  6770:     my %rolehash = ();
1.1332    raeburn  6771:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6772:         my $rolename = $1;
1.1326    raeburn  6773:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6774:         my %domdef = &get_domain_defaults($dcdom);
                   6775:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6776:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6777:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6778:             }
                   6779:         }
1.1326    raeburn  6780:     } else {
                   6781:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6782:     }
1.1341    raeburn  6783:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6784:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  6785:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402    raeburn  6786:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   6787:             ($caller eq 'tiny')) {
1.1088    raeburn  6788:         &appenv( {'request.role'        => $spec,
                   6789:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6790:                   'request.course.sec'  => $sec,
1.1088    raeburn  6791:                  }
                   6792:                );
                   6793:         my $tadv=0;
                   6794:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6795:         &appenv({'request.role.adv'    => $tadv});
                   6796:     }
1.994     raeburn  6797: }
                   6798: 
1.12      www      6799: # --------------------------------------------------------------- get interface
                   6800: 
                   6801: sub get {
1.131     albertel 6802:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6803:    my $items='';
1.800     albertel 6804:    foreach my $item (@$storearr) {
                   6805:        $items.=&escape($item).'&';
1.191     harris41 6806:    }
1.12      www      6807:    $items=~s/\&$//;
1.620     albertel 6808:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6809:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6810:    my $uhome=&homeserver($uname,$udomain);
                   6811: 
1.133     albertel 6812:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6813:    my @pairs=split(/\&/,$rep);
1.273     albertel 6814:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6815:      return @pairs;
                   6816:    }
1.15      www      6817:    my %returnhash=();
1.42      www      6818:    my $i=0;
1.800     albertel 6819:    foreach my $item (@$storearr) {
                   6820:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6821:       $i++;
1.191     harris41 6822:    }
1.15      www      6823:    return %returnhash;
1.27      www      6824: }
                   6825: 
                   6826: # --------------------------------------------------------------- del interface
                   6827: 
                   6828: sub del {
1.133     albertel 6829:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6830:    my $items='';
1.800     albertel 6831:    foreach my $item (@$storearr) {
                   6832:        $items.=&escape($item).'&';
1.191     harris41 6833:    }
1.984     neumanie 6834: 
1.27      www      6835:    $items=~s/\&$//;
1.620     albertel 6836:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6837:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6838:    my $uhome=&homeserver($uname,$udomain);
                   6839:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6840: }
                   6841: 
                   6842: # -------------------------------------------------------------- dump interface
                   6843: 
1.1180    droeschl 6844: sub unserialize {
                   6845:     my ($rep, $escapedkeys) = @_;
                   6846: 
                   6847:     return {} if $rep =~ /^error/;
                   6848: 
                   6849:     my %returnhash=();
1.1252    raeburn  6850: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6851: 	    my ($key, $value) = split(/=/, $item, 2);
                   6852: 	    $key = unescape($key) unless $escapedkeys;
                   6853: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  6854: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 6855: 	}
                   6856:     #return %returnhash;
                   6857:     return \%returnhash;
                   6858: }        
                   6859: 
                   6860: # see Lond::dump_with_regexp
                   6861: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6862: sub dump {
1.1180    droeschl 6863:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6864:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6865:     if (!$uname) { $uname=$env{'user.name'}; }
                   6866:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6867: 
1.1266    raeburn  6868:     if ($regexp) {
                   6869:         $regexp=&escape($regexp);
                   6870:     } else {
                   6871:         $regexp='.';
                   6872:     }
1.1180    droeschl 6873:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   6874:         # user is hosted on this machine
1.1266    raeburn  6875:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  6876:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 6877:         return %{unserialize($reply, $escapedkeys)};
                   6878:     }
1.1166    raeburn  6879:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6880:     my @pairs=split(/\&/,$rep);
                   6881:     my %returnhash=();
1.1098    foxr     6882:     if (!($rep =~ /^error/ )) {
                   6883: 	foreach my $item (@pairs) {
                   6884: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 6885:         $key = unescape($key) unless $escapedkeys;
                   6886:         #$key = &unescape($key);
1.1098    foxr     6887: 	    next if ($key =~ /^error: 2 /);
                   6888: 	    $returnhash{$key}=&thaw_unescape($value);
                   6889: 	}
1.755     albertel 6890:     }
                   6891:     return %returnhash;
1.407     www      6892: }
                   6893: 
1.1098    foxr     6894: 
1.717     albertel 6895: # --------------------------------------------------------- dumpstore interface
                   6896: 
                   6897: sub dumpstore {
                   6898:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 6899:    # same as dump but keys must be escaped. They may contain colon separated
                   6900:    # lists of values that may themself contain colons (e.g. symbs).
                   6901:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6902: }
                   6903: 
1.407     www      6904: # -------------------------------------------------------------- keys interface
                   6905: 
                   6906: sub getkeys {
                   6907:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6908:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6909:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6910:    my $uhome=&homeserver($uname,$udomain);
                   6911:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6912:    my @keyarray=();
1.800     albertel 6913:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6914:       next if ($key =~ /^error: 2 /);
1.800     albertel 6915:       push(@keyarray,&unescape($key));
1.407     www      6916:    }
                   6917:    return @keyarray;
1.318     matthew  6918: }
                   6919: 
1.319     matthew  6920: # --------------------------------------------------------------- currentdump
                   6921: sub currentdump {
1.328     matthew  6922:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6923:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6924:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6925:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6926:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 6927:    my $rep;
                   6928: 
                   6929:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6930:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6931:                    $courseid)));
                   6932:    } else {
                   6933:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6934:    }
                   6935: 
1.318     matthew  6936:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6937:    #
1.318     matthew  6938:    my %returnhash=();
1.319     matthew  6939:    #
1.1343    raeburn  6940:    if ($rep eq 'unknown_cmd') {
1.319     matthew  6941:        # an old lond will not know currentdump
                   6942:        # Do a dump and make it look like a currentdump
1.822     albertel 6943:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6944:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6945:        my %hash = @tmp;
                   6946:        @tmp=();
1.424     matthew  6947:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6948:    } else {
                   6949:        my @pairs=split(/\&/,$rep);
1.800     albertel 6950:        foreach my $pair (@pairs) {
                   6951:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6952:            my ($symb,$param) = split(/:/,$key);
                   6953:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6954:                                                         &thaw_unescape($value);
1.319     matthew  6955:        }
1.191     harris41 6956:    }
1.12      www      6957:    return %returnhash;
1.424     matthew  6958: }
                   6959: 
                   6960: sub convert_dump_to_currentdump{
                   6961:     my %hash = %{shift()};
                   6962:     my %returnhash;
                   6963:     # Code ripped from lond, essentially.  The only difference
                   6964:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6965:     # we might run in to problems with parameter names =~ /^v\./
                   6966:     while (my ($key,$value) = each(%hash)) {
                   6967:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6968: 	$symb  = &unescape($symb);
                   6969: 	$param = &unescape($param);
1.424     matthew  6970:         next if ($v eq 'version' || $symb eq 'keys');
                   6971:         next if (exists($returnhash{$symb}) &&
                   6972:                  exists($returnhash{$symb}->{$param}) &&
                   6973:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6974:         $returnhash{$symb}->{$param}=$value;
                   6975:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6976:     }
                   6977:     #
                   6978:     # Remove all of the keys in the hashes which keep track of
                   6979:     # the version of the parameter.
                   6980:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6981:         # use a foreach because we are going to delete from the hash.
                   6982:         foreach my $key (keys(%$param_hash)) {
                   6983:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6984:         }
                   6985:     }
                   6986:     return \%returnhash;
1.12      www      6987: }
                   6988: 
1.627     albertel 6989: # ------------------------------------------------------ critical inc interface
                   6990: 
                   6991: sub cinc {
                   6992:     return &inc(@_,'critical');
                   6993: }
                   6994: 
1.449     matthew  6995: # --------------------------------------------------------------- inc interface
                   6996: 
                   6997: sub inc {
1.627     albertel 6998:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6999:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7000:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7001:     my $uhome=&homeserver($uname,$udomain);
                   7002:     my $items='';
                   7003:     if (! ref($store)) {
                   7004:         # got a single value, so use that instead
                   7005:         $items = &escape($store).'=&';
                   7006:     } elsif (ref($store) eq 'SCALAR') {
                   7007:         $items = &escape($$store).'=&';        
                   7008:     } elsif (ref($store) eq 'ARRAY') {
                   7009:         $items = join('=&',map {&escape($_);} @{$store});
                   7010:     } elsif (ref($store) eq 'HASH') {
                   7011:         while (my($key,$value) = each(%{$store})) {
                   7012:             $items.= &escape($key).'='.&escape($value).'&';
                   7013:         }
                   7014:     }
                   7015:     $items=~s/\&$//;
1.627     albertel 7016:     if ($critical) {
                   7017: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7018:     } else {
                   7019: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7020:     }
1.449     matthew  7021: }
                   7022: 
1.12      www      7023: # --------------------------------------------------------------- put interface
                   7024: 
                   7025: sub put {
1.134     albertel 7026:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7027:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7028:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7029:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7030:    my $items='';
1.800     albertel 7031:    foreach my $item (keys(%$storehash)) {
                   7032:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7033:    }
1.12      www      7034:    $items=~s/\&$//;
1.134     albertel 7035:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      7036: }
                   7037: 
1.631     albertel 7038: # ------------------------------------------------------------ newput interface
                   7039: 
                   7040: sub newput {
                   7041:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7042:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7043:    if (!$uname) { $uname=$env{'user.name'}; }
                   7044:    my $uhome=&homeserver($uname,$udomain);
                   7045:    my $items='';
                   7046:    foreach my $key (keys(%$storehash)) {
                   7047:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7048:    }
                   7049:    $items=~s/\&$//;
                   7050:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7051: }
                   7052: 
                   7053: # ---------------------------------------------------------  putstore interface
                   7054: 
1.524     raeburn  7055: sub putstore {
1.1269    raeburn  7056:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7057:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7058:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7059:    my $uhome=&homeserver($uname,$udomain);
                   7060:    my $items='';
1.715     albertel 7061:    foreach my $key (keys(%$storehash)) {
                   7062:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7063:    }
1.715     albertel 7064:    $items=~s/\&$//;
1.716     albertel 7065:    my $esc_symb=&escape($symb);
                   7066:    my $esc_v=&escape($version);
1.715     albertel 7067:    my $reply =
1.716     albertel 7068:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7069: 	      $uhome);
1.1269    raeburn  7070:    if (($tolog) && ($reply eq 'ok')) {
                   7071:        my $namevalue='';
                   7072:        foreach my $key (keys(%{$storehash})) {
                   7073:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7074:        }
                   7075:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   7076:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7077:                      '&version='.$esc_v.
                   7078:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7079:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7080:    }
1.715     albertel 7081:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7082:        # gfall back to way things use to be done
1.715     albertel 7083:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7084: 			    $uname);
1.524     raeburn  7085:    }
1.715     albertel 7086:    return $reply;
                   7087: }
                   7088: 
                   7089: sub old_putstore {
1.716     albertel 7090:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7091:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7092:     if (!$uname) { $uname=$env{'user.name'}; }
                   7093:     my $uhome=&homeserver($uname,$udomain);
                   7094:     my %newstorehash;
1.800     albertel 7095:     foreach my $item (keys(%$storehash)) {
                   7096: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7097: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7098:     }
                   7099:     my $items='';
                   7100:     my %allitems = ();
1.800     albertel 7101:     foreach my $item (keys(%newstorehash)) {
                   7102: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7103: 	    my $key = $1.':keys:'.$2;
                   7104: 	    $allitems{$key} .= $3.':';
                   7105: 	}
1.800     albertel 7106: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7107:     }
1.800     albertel 7108:     foreach my $item (keys(%allitems)) {
                   7109: 	$allitems{$item} =~ s/\:$//;
                   7110: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7111:     }
                   7112:     $items=~s/\&$//;
                   7113:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7114: }
                   7115: 
1.47      www      7116: # ------------------------------------------------------ critical put interface
                   7117: 
                   7118: sub cput {
1.134     albertel 7119:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7120:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7121:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7122:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7123:    my $items='';
1.800     albertel 7124:    foreach my $item (keys(%$storehash)) {
                   7125:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7126:    }
1.47      www      7127:    $items=~s/\&$//;
1.134     albertel 7128:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7129: }
                   7130: 
                   7131: # -------------------------------------------------------------- eget interface
                   7132: 
                   7133: sub eget {
1.133     albertel 7134:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7135:    my $items='';
1.800     albertel 7136:    foreach my $item (@$storearr) {
                   7137:        $items.=&escape($item).'&';
1.191     harris41 7138:    }
1.12      www      7139:    $items=~s/\&$//;
1.620     albertel 7140:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7141:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7142:    my $uhome=&homeserver($uname,$udomain);
                   7143:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7144:    my @pairs=split(/\&/,$rep);
                   7145:    my %returnhash=();
1.42      www      7146:    my $i=0;
1.800     albertel 7147:    foreach my $item (@$storearr) {
                   7148:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7149:       $i++;
1.191     harris41 7150:    }
1.12      www      7151:    return %returnhash;
                   7152: }
                   7153: 
1.667     albertel 7154: # ------------------------------------------------------------ tmpput interface
                   7155: sub tmpput {
1.802     raeburn  7156:     my ($storehash,$server,$context)=@_;
1.667     albertel 7157:     my $items='';
1.800     albertel 7158:     foreach my $item (keys(%$storehash)) {
                   7159: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7160:     }
                   7161:     $items=~s/\&$//;
1.802     raeburn  7162:     if (defined($context)) {
                   7163:         $items .= ':'.&escape($context);
                   7164:     }
1.667     albertel 7165:     return &reply("tmpput:$items",$server);
                   7166: }
                   7167: 
                   7168: # ------------------------------------------------------------ tmpget interface
                   7169: sub tmpget {
1.688     albertel 7170:     my ($token,$server)=@_;
                   7171:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7172:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7173:     my %returnhash;
1.1328    raeburn  7174:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7175:         return %returnhash;
                   7176:     }
1.667     albertel 7177:     foreach my $item (split(/\&/,$rep)) {
                   7178: 	my ($key,$value)=split(/=/,$item);
                   7179: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7180:     }
                   7181:     return %returnhash;
                   7182: }
                   7183: 
1.1113    raeburn  7184: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7185: sub tmpdel {
                   7186:     my ($token,$server)=@_;
                   7187:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7188:     return &reply("tmpdel:$token",$server);
                   7189: }
                   7190: 
1.1198    raeburn  7191: # ------------------------------------------------------------ get_timebased_id 
                   7192: 
                   7193: sub get_timebased_id {
                   7194:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7195:         $maxtries) = @_;
                   7196:     my ($newid,$error,$dellock);
                   7197:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   7198:         return ('','ok','invalid call to get suffix');
                   7199:     }
                   7200: 
                   7201: # set defaults for any optional args for which values were not supplied
                   7202:     if ($who eq '') {
                   7203:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7204:     }
                   7205:     if (!$locktries) {
                   7206:         $locktries = 3;
                   7207:     }
                   7208:     if (!$maxtries) {
                   7209:         $maxtries = 10;
                   7210:     }
                   7211:     
                   7212:     if (($cdom eq '') || ($cnum eq '')) {
                   7213:         if ($env{'request.course.id'}) {
                   7214:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7215:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7216:         }
                   7217:         if (($cdom eq '') || ($cnum eq '')) {
                   7218:             return ('','ok','call to get suffix not in course context');
                   7219:         }
                   7220:     }
                   7221: 
                   7222: # construct locking item
                   7223:     my $lockhash = {
                   7224:                       $prefix."\0".'locked_'.$keyid => $who,
                   7225:                    };
                   7226:     my $tries = 0;
                   7227: 
                   7228: # attempt to get lock on nohist_$namespace file
                   7229:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7230:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7231:         $tries ++;
                   7232:         sleep 1;
                   7233:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7234:     }
                   7235: 
                   7236: # attempt to get unique identifier, based on current timestamp
                   7237:     if ($gotlock eq 'ok') {
                   7238:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7239:         my $id = time;
                   7240:         $newid = $id;
1.1268    raeburn  7241:         if ($idtype eq 'addcode') {
                   7242:             $newid .= &sixnum_code();
                   7243:         }
1.1198    raeburn  7244:         my $idtries = 0;
                   7245:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7246:             if ($idtype eq 'concat') {
                   7247:                 $newid = $id.$idtries;
1.1268    raeburn  7248:             } elsif ($idtype eq 'addcode') {
                   7249:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  7250:             } else {
                   7251:                 $newid ++;
                   7252:             }
                   7253:             $idtries ++;
                   7254:         }
                   7255:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7256:             my %new_item =  (
                   7257:                               $prefix."\0".$newid => $who,
                   7258:                             );
                   7259:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7260:                                                  $cdom,$cnum);
                   7261:             if ($putresult ne 'ok') {
                   7262:                 undef($newid);
                   7263:                 $error = 'error saving new item: '.$putresult;
                   7264:             }
                   7265:         } else {
1.1268    raeburn  7266:              undef($newid);
1.1198    raeburn  7267:              $error = ('error: no unique suffix available for the new item ');
                   7268:         }
                   7269: #  remove lock
                   7270:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7271:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7272:     } else {
                   7273:         $error = "error: could not obtain lockfile\n";
                   7274:         $dellock = 'ok';
1.1276    raeburn  7275:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7276:             $dellock = 'nolock';
                   7277:         }
1.1198    raeburn  7278:     }
                   7279:     return ($newid,$dellock,$error);
                   7280: }
                   7281: 
1.1268    raeburn  7282: sub sixnum_code {
                   7283:     my $code;
                   7284:     for (0..6) {
                   7285:         $code .= int( rand(9) );
                   7286:     }
                   7287:     return $code;
                   7288: }
                   7289: 
1.765     albertel 7290: # -------------------------------------------------- portfolio access checking
                   7291: 
                   7292: sub portfolio_access {
1.1270    raeburn  7293:     my ($requrl,$clientip) = @_;
1.765     albertel 7294:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  7295:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7296:     if ($result) {
                   7297:         my %setters;
                   7298:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7299:             my ($startblock,$endblock) =
                   7300:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7301:             if ($startblock && $endblock) {
                   7302:                 return 'B';
                   7303:             }
                   7304:         } else {
                   7305:             my ($startblock,$endblock) =
                   7306:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7307:             if ($startblock && $endblock) {
                   7308:                 return 'B';
                   7309:             }
                   7310:         }
                   7311:     }
1.765     albertel 7312:     if ($result eq 'ok') {
1.766     albertel 7313:        return 'F';
1.765     albertel 7314:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7315:        return 'A';
1.765     albertel 7316:     }
1.766     albertel 7317:     return '';
1.765     albertel 7318: }
                   7319: 
                   7320: sub get_portfolio_access {
1.1270    raeburn  7321:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7322: 
                   7323:     if (!ref($access_hash)) {
                   7324: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7325: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7326: 						   $file_name);
                   7327: 	$access_hash = $access_controls{$file_name};
                   7328:     }
                   7329: 
1.1270    raeburn  7330:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7331:     my $now = time;
                   7332:     if (ref($access_hash) eq 'HASH') {
                   7333:         foreach my $key (keys(%{$access_hash})) {
                   7334:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7335:             if ($start > $now) {
                   7336:                 next;
                   7337:             }
                   7338:             if ($end && $end<$now) {
                   7339:                 next;
                   7340:             }
                   7341:             if ($scope eq 'public') {
                   7342:                 $public = $key;
                   7343:                 last;
                   7344:             } elsif ($scope eq 'guest') {
                   7345:                 $guest = $key;
                   7346:             } elsif ($scope eq 'domains') {
                   7347:                 push(@domains,$key);
                   7348:             } elsif ($scope eq 'users') {
                   7349:                 push(@users,$key);
                   7350:             } elsif ($scope eq 'course') {
                   7351:                 push(@courses,$key);
                   7352:             } elsif ($scope eq 'group') {
                   7353:                 push(@groups,$key);
1.1270    raeburn  7354:             } elsif ($scope eq 'ip') {
                   7355:                 push(@ips,$key);
1.765     albertel 7356:             }
                   7357:         }
                   7358:         if ($public) {
                   7359:             return 'ok';
1.1270    raeburn  7360:         } elsif (@ips > 0) {
                   7361:             my $allowed;
                   7362:             foreach my $ipkey (@ips) {
                   7363:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7364:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7365:                         $allowed = 1;
                   7366:                         last; 
                   7367:                     }
                   7368:                 }
                   7369:             }
                   7370:             if ($allowed) {
                   7371:                 return 'ok';
                   7372:             }
1.765     albertel 7373:         }
                   7374:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7375:             if ($guest) {
                   7376:                 return $guest;
                   7377:             }
                   7378:         } else {
                   7379:             if (@domains > 0) {
                   7380:                 foreach my $domkey (@domains) {
                   7381:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7382:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7383:                             return 'ok';
                   7384:                         }
                   7385:                     }
                   7386:                 }
                   7387:             }
                   7388:             if (@users > 0) {
                   7389:                 foreach my $userkey (@users) {
1.865     raeburn  7390:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7391:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7392:                             if (ref($item) eq 'HASH') {
                   7393:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7394:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7395:                                     return 'ok';
                   7396:                                 }
                   7397:                             }
                   7398:                         }
                   7399:                     } 
1.765     albertel 7400:                 }
                   7401:             }
                   7402:             my %roleshash;
                   7403:             my @courses_and_groups = @courses;
                   7404:             push(@courses_and_groups,@groups); 
                   7405:             if (@courses_and_groups > 0) {
                   7406:                 my (%allgroups,%allroles); 
                   7407:                 my ($start,$end,$role,$sec,$group);
                   7408:                 foreach my $envkey (%env) {
1.1060    raeburn  7409:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7410:                         my $cid = $2.'_'.$3; 
                   7411:                         if ($1 eq 'gr') {
                   7412:                             $group = $4;
                   7413:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7414:                         } else {
                   7415:                             if ($4 eq '') {
                   7416:                                 $sec = 'none';
                   7417:                             } else {
                   7418:                                 $sec = $4;
                   7419:                             }
                   7420:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7421:                         }
1.811     albertel 7422:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7423:                         my $cid = $2.'_'.$3;
                   7424:                         if ($4 eq '') {
                   7425:                             $sec = 'none';
                   7426:                         } else {
                   7427:                             $sec = $4;
                   7428:                         }
                   7429:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7430:                     }
                   7431:                 }
                   7432:                 if (keys(%allroles) == 0) {
                   7433:                     return;
                   7434:                 }
                   7435:                 foreach my $key (@courses_and_groups) {
                   7436:                     my %content = %{$$access_hash{$key}};
                   7437:                     my $cnum = $content{'number'};
                   7438:                     my $cdom = $content{'domain'};
                   7439:                     my $cid = $cdom.'_'.$cnum;
                   7440:                     if (!exists($allroles{$cid})) {
                   7441:                         next;
                   7442:                     }    
                   7443:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7444:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7445:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7446:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7447:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7448:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7449:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7450:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7451:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7452:                                         if (grep/^all$/,@sections) {
                   7453:                                             return 'ok';
                   7454:                                         } else {
                   7455:                                             if (grep/^$sec$/,@sections) {
                   7456:                                                 return 'ok';
                   7457:                                             }
                   7458:                                         }
                   7459:                                     }
                   7460:                                 }
                   7461:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7462:                                     if (grep/^none$/,@groups) {
                   7463:                                         return 'ok';
                   7464:                                     }
                   7465:                                 } else {
                   7466:                                     if (grep/^all$/,@groups) {
                   7467:                                         return 'ok';
                   7468:                                     } 
                   7469:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7470:                                         if (grep/^$group$/,@groups) {
                   7471:                                             return 'ok';
                   7472:                                         }
                   7473:                                     }
                   7474:                                 } 
                   7475:                             }
                   7476:                         }
                   7477:                     }
                   7478:                 }
                   7479:             }
                   7480:             if ($guest) {
                   7481:                 return $guest;
                   7482:             }
                   7483:         }
                   7484:     }
                   7485:     return;
                   7486: }
                   7487: 
                   7488: sub course_group_datechecker {
                   7489:     my ($dates,$now,$status) = @_;
                   7490:     my ($start,$end) = split(/\./,$dates);
                   7491:     if (!$start && !$end) {
                   7492:         return 'ok';
                   7493:     }
                   7494:     if (grep/^active$/,@{$status}) {
                   7495:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7496:             return 'ok';
                   7497:         }
                   7498:     }
                   7499:     if (grep/^previous$/,@{$status}) {
                   7500:         if ($end > $now ) {
                   7501:             return 'ok';
                   7502:         }
                   7503:     }
                   7504:     if (grep/^future$/,@{$status}) {
                   7505:         if ($start > $now) {
                   7506:             return 'ok';
                   7507:         }
                   7508:     }
                   7509:     return; 
                   7510: }
                   7511: 
                   7512: sub parse_portfolio_url {
                   7513:     my ($url) = @_;
                   7514: 
                   7515:     my ($type,$udom,$unum,$group,$file_name);
                   7516:     
1.823     albertel 7517:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7518: 	$type = 1;
                   7519:         $udom = $1;
                   7520:         $unum = $2;
                   7521:         $file_name = $3;
1.823     albertel 7522:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7523: 	$type = 2;
                   7524:         $udom = $1;
                   7525:         $unum = $2;
                   7526:         $group = $3;
                   7527:         $file_name = $3.'/'.$4;
                   7528:     }
                   7529:     if (wantarray) {
                   7530: 	return ($type,$udom,$unum,$file_name,$group);
                   7531:     }
                   7532:     return $type;
                   7533: }
                   7534: 
                   7535: sub is_portfolio_url {
                   7536:     my ($url) = @_;
                   7537:     return scalar(&parse_portfolio_url($url));
                   7538: }
                   7539: 
1.798     raeburn  7540: sub is_portfolio_file {
                   7541:     my ($file) = @_;
1.820     raeburn  7542:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7543:         return 1;
                   7544:     }
                   7545:     return;
                   7546: }
                   7547: 
1.976     raeburn  7548: sub usertools_access {
1.1084    raeburn  7549:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7550:     my ($access,%tools);
                   7551:     if ($context eq '') {
                   7552:         $context = 'tools';
                   7553:     }
                   7554:     if ($context eq 'requestcourses') {
                   7555:         %tools = (
                   7556:                       official   => 1,
                   7557:                       unofficial => 1,
1.1006    raeburn  7558:                       community  => 1,
1.1246    raeburn  7559:                       textbook   => 1,
1.1305    raeburn  7560:                       placement  => 1,
1.1368    raeburn  7561:                       lti        => 1,
1.985     raeburn  7562:                  );
1.1183    raeburn  7563:     } elsif ($context eq 'requestauthor') {
                   7564:         %tools = (
                   7565:                       requestauthor => 1,
                   7566:                  );
1.985     raeburn  7567:     } else {
                   7568:         %tools = (
                   7569:                       aboutme   => 1,
                   7570:                       blog      => 1,
1.1177    raeburn  7571:                       webdav    => 1,
1.985     raeburn  7572:                       portfolio => 1,
                   7573:                  );
                   7574:     }
1.976     raeburn  7575:     return if (!defined($tools{$tool}));
                   7576: 
1.1242    raeburn  7577:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7578:         $udom = $env{'user.domain'};
                   7579:         $uname = $env{'user.name'};
                   7580:     }
                   7581: 
1.978     raeburn  7582:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7583:         if ($action ne 'reload') {
1.985     raeburn  7584:             if ($context eq 'requestcourses') {
                   7585:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7586:             } elsif ($context eq 'requestauthor') {
                   7587:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7588:             } else {
                   7589:                 return $env{'environment.availabletools.'.$tool};
                   7590:             }
                   7591:         }
1.976     raeburn  7592:     }
                   7593: 
1.1183    raeburn  7594:     my ($toolstatus,$inststatus,$envkey);
                   7595:     if ($context eq 'requestauthor') {
                   7596:         $envkey = $context; 
                   7597:     } else {
                   7598:         $envkey = $context.'.'.$tool;
                   7599:     }
1.976     raeburn  7600: 
1.985     raeburn  7601:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7602:          ($action ne 'reload')) {
1.1183    raeburn  7603:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7604:         $inststatus = $env{'environment.inststatus'};
                   7605:     } else {
1.1084    raeburn  7606:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7607:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7608:             $inststatus = $userenvref->{'inststatus'};
                   7609:         } else {
1.1183    raeburn  7610:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7611:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7612:             $inststatus = $userenv{'inststatus'};
                   7613:         }
1.976     raeburn  7614:     }
                   7615: 
                   7616:     if ($toolstatus ne '') {
                   7617:         if ($toolstatus) {
                   7618:             $access = 1;
                   7619:         } else {
                   7620:             $access = 0;
                   7621:         }
                   7622:         return $access;
                   7623:     }
                   7624: 
1.1084    raeburn  7625:     my ($is_adv,%domdef);
                   7626:     if (ref($is_advref) eq 'HASH') {
                   7627:         $is_adv = $is_advref->{'is_adv'};
                   7628:     } else {
                   7629:         $is_adv = &is_advanced_user($udom,$uname);
                   7630:     }
                   7631:     if (ref($domdefref) eq 'HASH') {
                   7632:         %domdef = %{$domdefref};
                   7633:     } else {
                   7634:         %domdef = &get_domain_defaults($udom);
                   7635:     }
1.976     raeburn  7636:     if (ref($domdef{$tool}) eq 'HASH') {
                   7637:         if ($is_adv) {
                   7638:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7639:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7640:                     $access = 1;
                   7641:                 } else {
                   7642:                     $access = 0;
                   7643:                 }
                   7644:                 return $access;
                   7645:             }
                   7646:         }
                   7647:         if ($inststatus ne '') {
                   7648:             my ($hasaccess,$hasnoaccess);
                   7649:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7650:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7651:                     if ($domdef{$tool}{$affiliation}) {
                   7652:                         $hasaccess = 1;
                   7653:                     } else {
                   7654:                         $hasnoaccess = 1;
                   7655:                     }
                   7656:                 }
                   7657:             }
                   7658:             if ($hasaccess || $hasnoaccess) {
                   7659:                 if ($hasaccess) {
                   7660:                     $access = 1;
                   7661:                 } elsif ($hasnoaccess) {
                   7662:                     $access = 0; 
                   7663:                 }
                   7664:                 return $access;
                   7665:             }
                   7666:         } else {
                   7667:             if ($domdef{$tool}{'default'} ne '') {
                   7668:                 if ($domdef{$tool}{'default'}) {
                   7669:                     $access = 1;
                   7670:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7671:                     $access = 0;
                   7672:                 }
                   7673:                 return $access;
                   7674:             }
                   7675:         }
                   7676:     } else {
1.1177    raeburn  7677:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7678:             $access = 1;
                   7679:         } else {
                   7680:             $access = 0;
                   7681:         }
1.976     raeburn  7682:         return $access;
                   7683:     }
                   7684: }
                   7685: 
1.1050    raeburn  7686: sub is_course_owner {
                   7687:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7688:     if (($udom eq '') || ($uname eq '')) {
                   7689:         $udom = $env{'user.domain'};
                   7690:         $uname = $env{'user.name'};
                   7691:     }
                   7692:     unless (($udom eq '') || ($uname eq '')) {
                   7693:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7694:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7695:                 return 1;
                   7696:             } else {
                   7697:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7698:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7699:                     return 1;
                   7700:                 }
                   7701:             }
                   7702:         }
                   7703:     }
                   7704:     return;
                   7705: }
                   7706: 
1.976     raeburn  7707: sub is_advanced_user {
                   7708:     my ($udom,$uname) = @_;
1.1085    raeburn  7709:     if ($udom ne '' && $uname ne '') {
                   7710:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7711:             if (wantarray) {
                   7712:                 return ($env{'user.adv'},$env{'user.author'});
                   7713:             } else {
                   7714:                 return $env{'user.adv'};
                   7715:             }
1.1085    raeburn  7716:         }
                   7717:     }
1.976     raeburn  7718:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7719:     my %allroles;
1.1128    raeburn  7720:     my ($is_adv,$is_author);
1.976     raeburn  7721:     foreach my $role (keys(%roleshash)) {
                   7722:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7723:         my $area = '/'.$tdomain.'/'.$trest;
                   7724:         if ($sec ne '') {
                   7725:             $area .= '/'.$sec;
                   7726:         }
                   7727:         if (($area ne '') && ($trole ne '')) {
                   7728:             my $spec=$trole.'.'.$area;
                   7729:             if ($trole =~ /^cr\//) {
                   7730:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7731:             } elsif ($trole ne 'gr') {
                   7732:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7733:             }
1.1128    raeburn  7734:             if ($trole eq 'au') {
                   7735:                 $is_author = 1;
                   7736:             }
1.976     raeburn  7737:         }
                   7738:     }
                   7739:     foreach my $role (keys(%allroles)) {
                   7740:         last if ($is_adv);
                   7741:         foreach my $item (split(/:/,$allroles{$role})) {
                   7742:             if ($item ne '') {
                   7743:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7744:                 if ($privilege eq 'adv') {
                   7745:                     $is_adv = 1;
                   7746:                     last;
                   7747:                 }
                   7748:             }
                   7749:         }
                   7750:     }
1.1128    raeburn  7751:     if (wantarray) {
                   7752:         return ($is_adv,$is_author);
                   7753:     }
1.976     raeburn  7754:     return $is_adv;
                   7755: }
1.798     raeburn  7756: 
1.1035    raeburn  7757: sub check_can_request {
1.1368    raeburn  7758:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  7759:     my $canreq = 0;
1.1368    raeburn  7760:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7761:         $uname = $env{'user.name'};
                   7762:         $udom = $env{'user.domain'};
                   7763:     }
1.1035    raeburn  7764:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7765:     my @options = ('approval','validate','autolimit');
                   7766:     my $optregex = join('|',@options);
                   7767:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7768:         foreach my $type (@{$types}) {
1.1368    raeburn  7769:             if (&usertools_access($uname,$udom,$type,undef,
                   7770:                                   'requestcourses')) {
1.1035    raeburn  7771:                 $canreq ++;
1.1036    raeburn  7772:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  7773:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  7774:                 }
1.1368    raeburn  7775:                 if ($dom eq $udom) {
1.1035    raeburn  7776:                     $can_request->{$type} = 1;
                   7777:                 }
                   7778:             }
1.1368    raeburn  7779:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   7780:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  7781:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7782:                 if (@curr > 0) {
1.1036    raeburn  7783:                     foreach my $item (@curr) {
                   7784:                         if (ref($request_domains) eq 'HASH') {
                   7785:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7786:                             if ($otherdom ne '') {
                   7787:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7788:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7789:                                         push(@{$request_domains->{$type}},$otherdom);
                   7790:                                     }
                   7791:                                 } else {
                   7792:                                     push(@{$request_domains->{$type}},$otherdom);
                   7793:                                 }
                   7794:                             }
                   7795:                         }
                   7796:                     }
1.1368    raeburn  7797:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  7798:                         $canreq ++;
1.1035    raeburn  7799:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7800:                             $can_request->{$type} = 1;
                   7801:                         }
                   7802:                     }
                   7803:                 }
                   7804:             }
                   7805:         }
                   7806:     }
                   7807:     return $canreq;
                   7808: }
                   7809: 
1.341     www      7810: # ---------------------------------------------- Custom access rule evaluation
                   7811: 
                   7812: sub customaccess {
                   7813:     my ($priv,$uri)=@_;
1.807     albertel 7814:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7815:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7816:     $udom = &LONCAPA::clean_domain($udom);
                   7817:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7818:     my $access=0;
1.800     albertel 7819:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7820: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7821: 	if ($type eq 'user') {
                   7822: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7823: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7824: 		if ($tdom) {
                   7825: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7826: 		}
1.896     albertel 7827: 		if ($tuname) {
                   7828: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7829: 		}
                   7830: 		$access=($effect eq 'allow');
                   7831: 		last;
                   7832: 	    }
                   7833: 	} else {
                   7834: 	    if ($role) {
                   7835: 		if ($role ne $urole) { next; }
                   7836: 	    }
                   7837: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7838: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7839: 		if ($tdom) {
                   7840: 		    if ($tdom ne $udom) { next; }
                   7841: 		}
                   7842: 		if ($tcrs) {
                   7843: 		    if ($tcrs ne $ucrs) { next; }
                   7844: 		}
                   7845: 		if ($tsec) {
                   7846: 		    if ($tsec ne $usec) { next; }
                   7847: 		}
                   7848: 		$access=($effect eq 'allow');
                   7849: 		last;
                   7850: 	    }
                   7851: 	    if ($realm eq '' && $role eq '') {
                   7852: 		$access=($effect eq 'allow');
                   7853: 	    }
1.402     bowersj2 7854: 	}
1.341     www      7855:     }
                   7856:     return $access;
                   7857: }
                   7858: 
1.103     harris41 7859: # ------------------------------------------------- Check for a user privilege
1.12      www      7860: 
                   7861: sub allowed {
1.1281    raeburn  7862:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7863:     my $ver_orguri=$uri;
1.439     www      7864:     $uri=&deversion($uri);
1.152     www      7865:     my $orguri=$uri;
1.52      www      7866:     $uri=&declutter($uri);
1.809     raeburn  7867: 
1.810     raeburn  7868:     if ($priv eq 'evb') {
                   7869: # Evade communication block restrictions for specified role in a course
                   7870:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7871:             return $1;
                   7872:         } else {
                   7873:             return;
                   7874:         }
                   7875:     }
                   7876: 
1.620     albertel 7877:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7878: # Free bre access to adm and meta resources
1.1343    raeburn  7879:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7880: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7881: 	&& ($priv eq 'bre')) {
1.14      www      7882: 	return 'F';
1.159     www      7883:     }
                   7884: 
1.545     banghart 7885: # Free bre access to user's own portfolio contents
1.714     raeburn  7886:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7887:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7888: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7889:         my %setters;
                   7890:         my ($startblock,$endblock) = 
                   7891:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7892:         if ($startblock && $endblock) {
                   7893:             return 'B';
                   7894:         } else {
                   7895:             return 'F';
                   7896:         }
1.545     banghart 7897:     }
                   7898: 
1.762     raeburn  7899: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7900:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7901:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7902:         if (exists($env{'request.course.id'})) {
                   7903:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7904:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7905:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7906:                 my $courseprivid=$env{'request.course.id'};
                   7907:                 $courseprivid=~s/\_/\//;
                   7908:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7909:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7910:                     return $1; 
1.762     raeburn  7911:                 } else {
                   7912:                     if ($env{'request.course.sec'}) {
                   7913:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7914:                     }
                   7915:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7916:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7917:                         return $2;
                   7918:                     }
1.714     raeburn  7919:                 }
                   7920:             }
                   7921:         }
                   7922:     }
                   7923: 
1.159     www      7924: # Free bre to public access
                   7925: 
                   7926:     if ($priv eq 'bre') {
1.1362    raeburn  7927:         my $copyright;
                   7928:         unless ($uri =~ /ext\.tool/) {
                   7929:             $copyright=&metadata($uri,'copyright');
                   7930:         }
1.620     albertel 7931: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7932:            return 'F'; 
                   7933:         }
1.238     www      7934:         if ($copyright eq 'priv') {
                   7935:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7936: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7937: 		return '';
                   7938:             }
                   7939:         }
                   7940:         if ($copyright eq 'domain') {
                   7941:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7942: 	    unless (($env{'user.domain'} eq $1) ||
                   7943:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7944: 		return '';
                   7945:             }
1.262     matthew  7946:         }
1.620     albertel 7947:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7948:             # Library role, so allow browsing of resources in this domain.
                   7949:             return 'F';
1.238     www      7950:         }
1.341     www      7951:         if ($copyright eq 'custom') {
                   7952: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7953:         }
1.14      www      7954:     }
1.264     matthew  7955:     # Domain coordinator is trying to create a course
1.620     albertel 7956:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7957:         # uri is the requested domain in this case.
                   7958:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7959:         # a role of dc for the domain in question.
1.620     albertel 7960:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7961:     }
1.29      www      7962: 
1.52      www      7963:     my $thisallowed='';
                   7964:     my $statecond=0;
                   7965:     my $courseprivid='';
                   7966: 
1.1039    raeburn  7967:     my $ownaccess;
1.1043    raeburn  7968:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7969:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7970:         if ($uri eq '') {
                   7971:             $ownaccess = 1;
                   7972:         } else {
                   7973:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7974:                 my $udom = $env{'user.domain'};
                   7975:                 my $uname = $env{'user.name'};
                   7976:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7977:                     $ownaccess = 1;
1.1040    raeburn  7978:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7979:                     unless ($uri =~ m{\.\./}) {
                   7980:                         $ownaccess = 1;
                   7981:                     }
                   7982:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7983:                     my $now = time;
                   7984:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7985:                         my $adom = $1;
                   7986:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7987:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7988:                                 my ($start,$end) = split('.',$env{$key});
                   7989:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7990:                                     $ownaccess = 1;
                   7991:                                     last;
                   7992:                                 }
                   7993:                             }
                   7994:                         }
                   7995:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7996:                         my $adom = $1;
                   7997:                         my $aname = $2;
1.1042    raeburn  7998:                         foreach my $role ('ca','aa') { 
                   7999:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8000:                                 my ($start,$end) =
                   8001:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   8002:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   8003:                                     $ownaccess = 1;
                   8004:                                     last;
                   8005:                                 }
1.1039    raeburn  8006:                             }
                   8007:                         }
                   8008:                     }
                   8009:                 }
                   8010:             }
                   8011:         }
                   8012:     }
                   8013: 
1.52      www      8014: # Course
                   8015: 
1.620     albertel 8016:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8017:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8018:             $thisallowed.=$1;
                   8019:         }
1.52      www      8020:     }
1.29      www      8021: 
1.52      www      8022: # Domain
                   8023: 
1.620     albertel 8024:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8025:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8026:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8027:             $thisallowed.=$1;
                   8028:         }
1.12      www      8029:     }
1.52      www      8030: 
1.1141    raeburn  8031: # User who is not author or co-author might still be able to edit
                   8032: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8033:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8034:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8035:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8036:             $thisallowed.=$1;
                   8037:         }
                   8038:     }
                   8039: 
1.52      www      8040: # Course: uri itself is a course
1.66      www      8041:     my $courseuri=$uri;
                   8042:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8043:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8044: 
1.620     albertel 8045:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8046:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8047:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8048:             $thisallowed.=$1;
                   8049:         }
1.12      www      8050:     }
1.29      www      8051: 
1.665     albertel 8052: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8053: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8054:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8055: 	$thisallowed='';
1.671     raeburn  8056:         my ($match)=&is_on_map($uri);
                   8057:         if ($match) {
                   8058:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8059:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  8060:                 my $value = $1;
1.1402    raeburn  8061:                 my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8062:                 if ($deeplinkblock) {
                   8063:                     $thisallowed='D';
                   8064:                 } elsif ($noblockcheck) {
1.1281    raeburn  8065:                     $thisallowed.=$value;
1.1162    raeburn  8066:                 } else {
1.1281    raeburn  8067:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   8068:                     if (@blockers > 0) {
                   8069:                         $thisallowed = 'B';
                   8070:                     } else {
                   8071:                         $thisallowed.=$value;
                   8072:                     }
1.1162    raeburn  8073:                 }
1.671     raeburn  8074:             }
                   8075:         } else {
1.705     albertel 8076:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8077:             if ($refuri) {
                   8078:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8079:                     $thisallowed='F';
1.671     raeburn  8080:                 } else {
                   8081:                     $refuri=&declutter($refuri);
                   8082:                     my ($match) = &is_on_map($refuri);
                   8083:                     if ($match) {
1.1402    raeburn  8084:                         my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8085:                         if ($deeplinkblock) {
                   8086:                             $thisallowed='D';
                   8087:                         } elsif ($noblockcheck) {
1.1281    raeburn  8088:                             $thisallowed='F';
1.1162    raeburn  8089:                         } else {
1.1281    raeburn  8090:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   8091:                             if (@blockers > 0) {
                   8092:                                 $thisallowed = 'B';
                   8093:                             } else {
                   8094:                                 $thisallowed='F';
                   8095:                             }
1.1162    raeburn  8096:                         }
1.671     raeburn  8097:                     }
1.669     raeburn  8098:                 }
1.671     raeburn  8099:             }
                   8100:         }
1.314     www      8101:     }
1.492     albertel 8102: 
1.766     albertel 8103:     if ($priv eq 'bre'
                   8104: 	&& $thisallowed ne 'F' 
                   8105: 	&& $thisallowed ne '2'
                   8106: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  8107: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8108:     }
1.1250    raeburn  8109: 
1.52      www      8110: # Full access at system, domain or course-wide level? Exit.
1.29      www      8111:     if ($thisallowed=~/F/) {
                   8112: 	return 'F';
                   8113:     }
                   8114: 
1.52      www      8115: # If this is generating or modifying users, exit with special codes
1.29      www      8116: 
1.643     www      8117:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8118: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8119: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8120: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8121: 	    unless ($auname) { return $thisallowed; }
                   8122: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8123: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8124: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8125: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8126: 	}
1.52      www      8127: 	return $thisallowed;
                   8128:     }
                   8129: #
1.103     harris41 8130: # Gathered so far: system, domain and course wide privileges
1.52      www      8131: #
                   8132: # Course: See if uri or referer is an individual resource that is part of 
                   8133: # the course
                   8134: 
1.620     albertel 8135:     if ($env{'request.course.id'}) {
1.232     www      8136: 
1.620     albertel 8137:        $courseprivid=$env{'request.course.id'};
                   8138:        if ($env{'request.course.sec'}) {
                   8139:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8140:        }
                   8141:        $courseprivid=~s/\_/\//;
                   8142:        my $checkreferer=1;
1.232     www      8143:        my ($match,$cond)=&is_on_map($uri);
                   8144:        if ($match) {
                   8145:            $statecond=$cond;
1.620     albertel 8146:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8147:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8148:                my $value = $1;
                   8149:                if ($priv eq 'bre') {
1.1281    raeburn  8150:                    if ($noblockcheck) {
                   8151:                        $thisallowed.=$value;
1.1162    raeburn  8152:                    } else {
1.1281    raeburn  8153:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   8154:                        if (@blockers > 0) {
                   8155:                            $thisallowed = 'B';
                   8156:                        } else {
                   8157:                            $thisallowed.=$value;
                   8158:                        }
1.1162    raeburn  8159:                    }
                   8160:                } else {
                   8161:                    $thisallowed.=$value;
                   8162:                }
1.52      www      8163:                $checkreferer=0;
                   8164:            }
1.29      www      8165:        }
1.83      www      8166:        
1.148     www      8167:        if ($checkreferer) {
1.620     albertel 8168: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8169:             unless ($refuri) {
1.800     albertel 8170:                 foreach my $key (keys(%env)) {
                   8171: 		    if ($key=~/^httpref\..*\*/) {
                   8172: 			my $pattern=$key;
1.156     www      8173:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8174:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8175:                         $pattern=~s/\//\\\//g;
1.152     www      8176:                         if ($orguri=~/$pattern/) {
1.800     albertel 8177: 			    $refuri=$env{$key};
1.148     www      8178:                         }
                   8179:                     }
1.191     harris41 8180:                 }
1.148     www      8181:             }
1.232     www      8182: 
1.148     www      8183:          if ($refuri) { 
1.152     www      8184: 	  $refuri=&declutter($refuri);
1.232     www      8185:           my ($match,$cond)=&is_on_map($refuri);
                   8186:             if ($match) {
                   8187:               my $refstatecond=$cond;
1.620     albertel 8188:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8189:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8190:                   my $value = $1;
                   8191:                   if ($priv eq 'bre') {
1.1402    raeburn  8192:                       my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8193:                       if ($deeplinkblock) {
                   8194:                           $thisallowed = 'D';
                   8195:                       } elsif ($noblockcheck) {
1.1281    raeburn  8196:                           $thisallowed.=$value;
1.1162    raeburn  8197:                       } else {
1.1281    raeburn  8198:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   8199:                           if (@blockers > 0) {
                   8200:                               $thisallowed = 'B';
                   8201:                           } else {
                   8202:                               $thisallowed.=$value;
                   8203:                           }
1.1162    raeburn  8204:                       }
                   8205:                   } else {
                   8206:                       $thisallowed.=$value;
                   8207:                   }
1.53      www      8208:                   $uri=$refuri;
                   8209:                   $statecond=$refstatecond;
1.52      www      8210:               }
                   8211:           }
1.148     www      8212:         }
1.29      www      8213:        }
1.52      www      8214:    }
1.29      www      8215: 
1.52      www      8216: #
1.103     harris41 8217: # Gathered now: all privileges that could apply, and condition number
1.52      www      8218: # 
                   8219: #
                   8220: # Full or no access?
                   8221: #
1.29      www      8222: 
1.52      www      8223:     if ($thisallowed=~/F/) {
                   8224: 	return 'F';
                   8225:     }
1.29      www      8226: 
1.52      www      8227:     unless ($thisallowed) {
                   8228:         return '';
                   8229:     }
1.29      www      8230: 
1.52      www      8231: # Restrictions exist, deal with them
                   8232: #
                   8233: #   C:according to course preferences
                   8234: #   R:according to resource settings
                   8235: #   L:unless locked
                   8236: #   X:according to user session state
                   8237: #
                   8238: 
                   8239: # Possibly locked functionality, check all courses
1.54      www      8240: # Locks might take effect only after 10 minutes cache expiration for other
                   8241: # courses, and 2 minutes for current course
1.52      www      8242: 
                   8243:     my $envkey;
                   8244:     if ($thisallowed=~/L/) {
1.1000    raeburn  8245:         foreach $envkey (keys(%env)) {
1.54      www      8246:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8247:                my $courseid=$2;
                   8248:                my $roleid=$1.'.'.$2;
1.92      www      8249:                $courseid=~s/^\///;
1.54      www      8250:                my $expiretime=600;
1.620     albertel 8251:                if ($env{'request.role'} eq $roleid) {
1.54      www      8252: 		  $expiretime=120;
                   8253:                }
                   8254: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8255:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8256:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8257: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8258:                }
1.620     albertel 8259:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8260:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8261: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8262:                        &log($env{'user.domain'},$env{'user.name'},
                   8263:                             $env{'user.home'},
1.57      www      8264:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8265:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8266:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8267: 		       return '';
                   8268:                    }
                   8269:                }
1.620     albertel 8270:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8271:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8272: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8273:                        &log($env{'user.domain'},$env{'user.name'},
                   8274:                             $env{'user.home'},
1.57      www      8275:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8276:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8277:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8278: 		       return '';
                   8279:                    }
                   8280:                }
                   8281: 	   }
1.29      www      8282:        }
1.52      www      8283:     }
                   8284:    
                   8285: #
                   8286: # Rest of the restrictions depend on selected course
                   8287: #
                   8288: 
1.620     albertel 8289:     unless ($env{'request.course.id'}) {
1.766     albertel 8290: 	if ($thisallowed eq 'A') {
                   8291: 	    return 'A';
1.814     raeburn  8292:         } elsif ($thisallowed eq 'B') {
                   8293:             return 'B';
1.766     albertel 8294: 	} else {
                   8295: 	    return '1';
                   8296: 	}
1.52      www      8297:     }
1.29      www      8298: 
1.52      www      8299: #
                   8300: # Now user is definitely in a course
                   8301: #
1.53      www      8302: 
                   8303: 
                   8304: # Course preferences
                   8305: 
                   8306:    if ($thisallowed=~/C/) {
1.620     albertel 8307:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8308:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8309:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8310: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  8311: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8312: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8313: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8314: 			$env{'request.course.id'});
                   8315: 	   }
1.237     www      8316:            return '';
                   8317:        }
                   8318: 
1.620     albertel 8319:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8320: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  8321: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8322: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8323: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8324: 			$env{'request.course.id'});
                   8325: 	   }
1.54      www      8326:            return '';
                   8327:        }
1.53      www      8328:    }
                   8329: 
                   8330: # Resource preferences
                   8331: 
                   8332:    if ($thisallowed=~/R/) {
1.620     albertel 8333:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8334:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8335: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8336: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8337: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8338: 	   }
                   8339: 	   return '';
1.54      www      8340:        }
1.53      www      8341:    }
1.30      www      8342: 
1.246     www      8343: # Restricted by state or randomout?
1.30      www      8344: 
1.52      www      8345:    if ($thisallowed=~/X/) {
1.620     albertel 8346:       if ($env{'acc.randomout'}) {
1.579     albertel 8347: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8348:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8349:             return ''; 
                   8350:          }
1.247     www      8351:       }
                   8352:       if (&condval($statecond)) {
1.52      www      8353: 	 return '2';
                   8354:       } else {
                   8355:          return '';
                   8356:       }
                   8357:    }
1.30      www      8358: 
1.766     albertel 8359:     if ($thisallowed eq 'A') {
                   8360: 	return 'A';
1.814     raeburn  8361:     } elsif ($thisallowed eq 'B') {
                   8362:         return 'B';
1.1402    raeburn  8363:     } elsif ($thisallowed eq 'D') {
                   8364:         return 'D';
1.766     albertel 8365:     }
1.52      www      8366:    return 'F';
1.232     www      8367: }
1.1162    raeburn  8368: 
1.1192    raeburn  8369: # ------------------------------------------- Check construction space access
                   8370: 
                   8371: sub constructaccess {
                   8372:     my ($url,$setpriv)=@_;
                   8373: 
                   8374: # We do not allow editing of previous versions of files
                   8375:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8376: 
                   8377: # Get username and domain from URL
                   8378:     my ($ownername,$ownerdomain,$ownerhome);
                   8379: 
                   8380:     ($ownerdomain,$ownername) =
1.1325    raeburn  8381:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  8382: 
                   8383: # The URL does not really point to any authorspace, forget it
                   8384:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8385: 
                   8386: # Now we need to see if the user has access to the authorspace of
                   8387: # $ownername at $ownerdomain
                   8388: 
                   8389:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8390: # Real author for this?
                   8391:        $ownerhome = $env{'user.home'};
                   8392:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8393:           return ($ownername,$ownerdomain,$ownerhome);
                   8394:        }
                   8395:     } else {
                   8396: # Co-author for this?
                   8397:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8398:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8399:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8400:             return ($ownername,$ownerdomain,$ownerhome);
                   8401:         }
1.1312    raeburn  8402:         if ($env{'request.course.id'}) {
                   8403:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   8404:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   8405:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   8406:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   8407:                     return ($ownername,$ownerdomain,$ownerhome);
                   8408:                 }
                   8409:             }
                   8410:         }
1.1192    raeburn  8411:     }
                   8412: 
                   8413: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8414: # we might as well leave
                   8415:    unless ($setpriv) { return ''; }
                   8416: 
                   8417: # Backdoor access?
                   8418:     my $allowed=&allowed('eco',$ownerdomain);
                   8419: # Nope
                   8420:     unless ($allowed) { return ''; }
                   8421: # Looks like we may have access, but could be locked by the owner of the construction space
                   8422:     if ($allowed eq 'U') {
                   8423:         my %blocked=&get('environment',['domcoord.author'],
                   8424:                          $ownerdomain,$ownername);
                   8425: # Is blocked by owner
                   8426:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8427:     }
                   8428:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8429: # Grant temporary access
                   8430:         my $then=$env{'user.login.time'};
1.1209    raeburn  8431:         my $update=$env{'user.update.time'};
1.1192    raeburn  8432:         if (!$update) { $update = $then; }
                   8433:         my $refresh=$env{'user.refresh.time'};
                   8434:         if (!$refresh) { $refresh = $update; }
                   8435:         my $now = time;
                   8436:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8437:                            $now,'ca','constructaccess');
                   8438:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8439:         return($ownername,$ownerdomain,$ownerhome);
                   8440:     }
                   8441: # No business here
                   8442:     return '';
                   8443: }
                   8444: 
1.1282    raeburn  8445: # ----------------------------------------------------------- Content Blocking
                   8446: 
                   8447: {
                   8448: # Caches for faster Course Contents display where content blocking
                   8449: # is in operation (i.e., interval param set) for timed quiz.
                   8450: #
                   8451: # User for whom data are being temporarily cached.
                   8452: my $cacheduser='';
                   8453: # Cached blockers for this user (a hash of blocking items). 
                   8454: my %cachedblockers=();
                   8455: # When the data were last cached.
                   8456: my $cachedlast='';
                   8457: 
                   8458: sub load_all_blockers {
                   8459:     my ($uname,$udom,$blocks)=@_;
                   8460:     if (($uname ne '') && ($udom ne '')) { 
                   8461:         if (($cacheduser eq $uname.':'.$udom) &&
                   8462:             (abs($cachedlast-time)<5)) {
                   8463:             return;
                   8464:         }
                   8465:     }
                   8466:     $cachedlast=time;
                   8467:     $cacheduser=$uname.':'.$udom;
                   8468:     %cachedblockers = &get_commblock_resources($blocks);
                   8469: }
                   8470: 
1.1162    raeburn  8471: sub get_comm_blocks {
                   8472:     my ($cdom,$cnum) = @_;
                   8473:     if ($cdom eq '' || $cnum eq '') {
                   8474:         return unless ($env{'request.course.id'});
                   8475:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8476:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8477:     }
                   8478:     my %commblocks;
                   8479:     my $hashid=$cdom.'_'.$cnum;
                   8480:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8481:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8482:         %commblocks = %{$blocksref};
                   8483:     } else {
                   8484:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8485:         my $cachetime = 600;
                   8486:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8487:     }
                   8488:     return %commblocks;
                   8489: }
                   8490: 
1.1282    raeburn  8491: sub get_commblock_resources {
                   8492:     my ($blocks) = @_;
                   8493:     my %blockers = ();
                   8494:     return %blockers unless ($env{'request.course.id'});
                   8495:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8496:     my %commblocks;
                   8497:     if (ref($blocks) eq 'HASH') {
                   8498:         %commblocks = %{$blocks};
                   8499:     } else {
                   8500:         %commblocks = &get_comm_blocks();
                   8501:     }
1.1282    raeburn  8502:     return %blockers unless (keys(%commblocks) > 0); 
                   8503:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8504:     return %blockers unless (ref($navmap));
1.1162    raeburn  8505:     my $now = time;
                   8506:     foreach my $block (keys(%commblocks)) {
                   8507:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8508:             my ($start,$end) = ($1,$2);
                   8509:             if ($start <= $now && $end >= $now) {
                   8510:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8511:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8512:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8513:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8514:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8515:                             }
                   8516:                         }
                   8517:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8518:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8519:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8520:                             }
                   8521:                         }
                   8522:                     }
                   8523:                 }
                   8524:             }
                   8525:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8526:             my $item = $1;
1.1163    raeburn  8527:             my @to_test;
1.1162    raeburn  8528:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8529:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  8530:                     my @interval;
                   8531:                     my $type = 'map';
                   8532:                     if ($item eq 'course') {
                   8533:                         $type = 'course';
                   8534:                         @interval=&EXT("resource.0.interval");
                   8535:                     } else {
                   8536:                         if ($item =~ /___\d+___/) {
                   8537:                             $type = 'resource';
                   8538:                             @interval=&EXT("resource.0.interval",$item);
                   8539:                             if (ref($navmap)) {                        
                   8540:                                 my $res = $navmap->getBySymb($item); 
                   8541:                                 push(@to_test,$res);
                   8542:                             }
1.1162    raeburn  8543:                         } else {
1.1282    raeburn  8544:                             my $mapsymb = &symbread($item,1);
                   8545:                             if ($mapsymb) {
                   8546:                                 if (ref($navmap)) {
                   8547:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8548:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8549:                                     foreach my $res (@to_test) {
                   8550:                                         my $symb = $res->symb();
                   8551:                                         next if ($symb eq $mapsymb);
                   8552:                                         if ($symb ne '') {
                   8553:                                             @interval=&EXT("resource.0.interval",$symb);
                   8554:                                             if ($interval[1] eq 'map') {
                   8555:                                                 last;
1.1162    raeburn  8556:                                             }
                   8557:                                         }
                   8558:                                     }
                   8559:                                 }
                   8560:                             }
                   8561:                         }
1.1282    raeburn  8562:                     }
1.1310    raeburn  8563:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8564:                         my $timelimit = $1; 
1.1282    raeburn  8565:                         my $first_access;
                   8566:                         if ($type eq 'resource') {
                   8567:                             $first_access=&get_first_access($interval[1],$item);
                   8568:                         } elsif ($type eq 'map') {
                   8569:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8570:                         } else {
                   8571:                             $first_access=&get_first_access($interval[1]);
                   8572:                         }
                   8573:                         if ($first_access) {
1.1292    raeburn  8574:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8575:                             if ($timesup > $now) {
                   8576:                                 my $activeblock;
                   8577:                                 foreach my $res (@to_test) {
1.1283    raeburn  8578:                                     if ($res->answerable()) {
1.1282    raeburn  8579:                                         $activeblock = 1;
                   8580:                                         last;
                   8581:                                     }
                   8582:                                 }
                   8583:                                 if ($activeblock) {
                   8584:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8585:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8586:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8587:                                          }
                   8588:                                     }
                   8589:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8590:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8591:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8592:                                         }
1.1162    raeburn  8593:                                     }
                   8594:                                 }
                   8595:                             }
                   8596:                         }
                   8597:                     }
                   8598:                 }
                   8599:             }
                   8600:         }
                   8601:     }
1.1282    raeburn  8602:     return %blockers;
1.1162    raeburn  8603: }
                   8604: 
1.1282    raeburn  8605: sub has_comm_blocking {
                   8606:     my ($priv,$symb,$uri,$blocks) = @_;
                   8607:     my @blockers;
                   8608:     return unless ($env{'request.course.id'});
                   8609:     return unless ($priv eq 'bre');
                   8610:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8611:     return if ($env{'request.state'} eq 'construct');
                   8612:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8613:     return unless (keys(%cachedblockers) > 0);
                   8614:     my (%possibles,@symbs);
                   8615:     if (!$symb) {
                   8616:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8617:     }
1.1282    raeburn  8618:     if ($symb) {
                   8619:         @symbs = ($symb);
                   8620:     } elsif (keys(%possibles)) { 
                   8621:         @symbs = keys(%possibles);
                   8622:     }
                   8623:     my $noblock;
                   8624:     foreach my $symb (@symbs) {
                   8625:         last if ($noblock);
                   8626:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8627:         foreach my $block (keys(%cachedblockers)) {
                   8628:             if ($block =~ /^firstaccess____(.+)$/) {
                   8629:                 my $item = $1;
                   8630:                 if (($item eq $map) || ($item eq $symb)) {
                   8631:                     $noblock = 1;
                   8632:                     last;
                   8633:                 }
                   8634:             }
                   8635:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8636:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8637:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8638:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8639:                             push(@blockers,$block);
                   8640:                         }
                   8641:                     }
                   8642:                 }
1.1162    raeburn  8643:             }
1.1282    raeburn  8644:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8645:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8646:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8647:                         push(@blockers,$block);
                   8648:                     }
                   8649:                 }
1.1162    raeburn  8650:             }
                   8651:         }
                   8652:     }
1.1282    raeburn  8653:     return if ($noblock);
                   8654:     return @blockers;
                   8655: }
1.1162    raeburn  8656: }
                   8657: 
1.1402    raeburn  8658: sub deeplink_check {
                   8659:     my ($priv,$symb,$uri) = @_;
                   8660:     return unless ($env{'request.course.id'});
                   8661:     return unless ($priv eq 'bre');
                   8662:     return if ($env{'request.state'} eq 'construct');
                   8663:     return if ($env{'request.role.adv'});
                   8664:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8665:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8666:     my (%possibles,@symbs);
                   8667:     if (!$symb) {
                   8668:         $symb = &symbread($uri,1,1,1,\%possibles);
                   8669:     }
                   8670:     if ($symb) {
                   8671:         @symbs = ($symb);
                   8672:     } elsif (keys(%possibles)) {
                   8673:         @symbs = keys(%possibles);
                   8674:     }
                   8675: 
                   8676:     my ($login,$switchrole,$allow);
                   8677:     if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   8678:         my $key = $1;
                   8679:         my $tinyurl;
                   8680:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   8681:         if (defined($cached)) {
                   8682:              $tinyurl = $result;
                   8683:         } else {
                   8684:              my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   8685:              my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   8686:              if ($currtiny{$key} ne '') {
                   8687:                  $tinyurl = $currtiny{$key};
                   8688:                  &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
                   8689:              }
                   8690:         }
                   8691:         if ($tinyurl ne '') {
                   8692:             my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
                   8693:             if ($cnumreq eq $cnum) {
                   8694:                 $login = $posslogin;
                   8695:             } else {
                   8696:                 $switchrole = 1;
                   8697:             }
                   8698:         }
                   8699:     }
                   8700:     foreach my $symb (@symbs) {
                   8701:         last if ($allow);
                   8702:         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   8703:         if ($deeplink eq '') {
                   8704:             $allow = 1;
                   8705:         } else {
                   8706:             my ($listed,$scope,$access) = split(/,/,$deeplink);
                   8707:             if ($access eq 'any') {
                   8708:                 $allow = 1;
                   8709:             } elsif ($login) {
                   8710:                 if ($access eq 'only') {
                   8711:                     if ($scope eq 'res') {
                   8712:                         if ($symb eq $login) {
                   8713:                             $allow = 1;
                   8714:                         }
                   8715:                     } elsif ($scope eq 'map') {
                   8716: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
                   8717:                     } elsif ($scope eq 'rec') {
                   8718: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
                   8719:                     }
                   8720:                 } else {
                   8721:                     my ($acctype,$item) = split(/:/,$access);
                   8722:                     if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
                   8723:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
                   8724:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
                   8725:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
                   8726:                                 $allow = 1;
                   8727:                             }
                   8728:                         }
                   8729:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   8730:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   8731:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
                   8732:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
                   8733:                                 $allow = 1;
                   8734:                             }
                   8735:                         }
                   8736:                     }
                   8737:                 }
                   8738:             }
                   8739:         }
                   8740:     }
                   8741:     return if ($allow);
                   8742:     return 1;
                   8743: }
                   8744: 
1.1282    raeburn  8745: # -------------------------------- Deversion and split uri into path an filename   
                   8746: 
1.1133    foxr     8747: #
1.1282    raeburn  8748: #   Removes the version from a URI and
1.1133    foxr     8749: #   splits it in to its filename and path to the filename.
                   8750: #   Seems like File::Basename could have done this more clearly.
                   8751: #   Parameters:
                   8752: #      $uri   - input URI
                   8753: #   Returns:
                   8754: #     Two element list consisting of 
                   8755: #     $pathname  - the URI up to and excluding the trailing /
                   8756: #     $filename  - The part of the URI following the last /
                   8757: #  NOTE:
                   8758: #    Another realization of this is simply:
                   8759: #    use File::Basename;
                   8760: #    ...
                   8761: #    $uri = shift;
                   8762: #    $filename = basename($uri);
                   8763: #    $path     = dirname($uri);
                   8764: #    return ($filename, $path);
                   8765: #
                   8766: #     The implementation below is probably faster however.
                   8767: #
1.710     albertel 8768: sub split_uri_for_cond {
                   8769:     my $uri=&deversion(&declutter(shift));
                   8770:     my @uriparts=split(/\//,$uri);
                   8771:     my $filename=pop(@uriparts);
                   8772:     my $pathname=join('/',@uriparts);
                   8773:     return ($pathname,$filename);
                   8774: }
1.232     www      8775: # --------------------------------------------------- Is a resource on the map?
                   8776: 
                   8777: sub is_on_map {
1.710     albertel 8778:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8779:     #Trying to find the conditional for the file
1.620     albertel 8780:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8781: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8782:     if ($match) {
1.289     bowersj2 8783: 	return (1,$1);
                   8784:     } else {
1.434     www      8785: 	return (0,0);
1.289     bowersj2 8786:     }
1.12      www      8787: }
                   8788: 
1.427     www      8789: # --------------------------------------------------------- Get symb from alias
                   8790: 
                   8791: sub get_symb_from_alias {
                   8792:     my $symb=shift;
                   8793:     my ($map,$resid,$url)=&decode_symb($symb);
                   8794: # Already is a symb
                   8795:     if ($url) { return $symb; }
                   8796: # Must be an alias
                   8797:     my $aliassymb='';
                   8798:     my %bighash;
1.620     albertel 8799:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8800:                             &GDBM_READER(),0640)) {
                   8801:         my $rid=$bighash{'mapalias_'.$symb};
                   8802: 	if ($rid) {
                   8803: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8804: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8805: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8806: 	}
                   8807:         untie %bighash;
                   8808:     }
                   8809:     return $aliassymb;
                   8810: }
                   8811: 
1.12      www      8812: # ----------------------------------------------------------------- Define Role
                   8813: 
                   8814: sub definerole {
                   8815:   if (allowed('mcr','/')) {
1.1326    raeburn  8816:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8817:     foreach my $role (split(':',$sysrole)) {
                   8818: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8819:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8820:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8821: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8822:                return "refused:s:$crole&$cqual"; 
                   8823:             }
                   8824:         }
1.191     harris41 8825:     }
1.800     albertel 8826:     foreach my $role (split(':',$domrole)) {
                   8827: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8828:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8829:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8830: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8831:                return "refused:d:$crole&$cqual"; 
                   8832:             }
                   8833:         }
1.191     harris41 8834:     }
1.800     albertel 8835:     foreach my $role (split(':',$courole)) {
                   8836: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8837:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8838:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8839: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8840:                return "refused:c:$crole&$cqual"; 
                   8841:             }
                   8842:         }
1.191     harris41 8843:     }
1.1326    raeburn  8844:     my $uhome;
                   8845:     if (($uname ne '') && ($udom ne '')) {
                   8846:         $uhome = &homeserver($uname,$udom);
                   8847:         return $uhome if ($uhome eq 'no_host');
                   8848:     } else {
                   8849:         $uname = $env{'user.name'};
                   8850:         $udom = $env{'user.domain'};
                   8851:         $uhome = $env{'user.home'};
                   8852:     }
1.620     albertel 8853:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  8854:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8855:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  8856:     return reply($command,$uhome);
1.12      www      8857:   } else {
                   8858:     return 'refused';
                   8859:   }
1.105     harris41 8860: }
                   8861: 
                   8862: # ---------------- Make a metadata query against the network of library servers
                   8863: 
                   8864: sub metadata_query {
1.1237    raeburn  8865:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8866:     my %rhash;
1.845     albertel 8867:     my %libserv = &all_library();
1.244     matthew  8868:     my @server_list = (defined($server_array) ? @$server_array
                   8869:                                               : keys(%libserv) );
                   8870:     for my $server (@server_list) {
1.1237    raeburn  8871:         my $domains = ''; 
                   8872:         if (ref($domains_hash) eq 'HASH') {
                   8873:             $domains = $domains_hash->{$server}; 
                   8874:         }
1.118     harris41 8875: 	unless ($custom or $customshow) {
1.1237    raeburn  8876: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8877: 	    $rhash{$server}=$reply;
                   8878: 	}
                   8879: 	else {
                   8880: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  8881: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8882: 			     $server);
                   8883: 	    $rhash{$server}=$reply;
                   8884: 	}
1.112     harris41 8885:     }
1.118     harris41 8886:     return \%rhash;
1.240     www      8887: }
                   8888: 
                   8889: # ----------------------------------------- Send log queries and wait for reply
                   8890: 
                   8891: sub log_query {
                   8892:     my ($uname,$udom,$query,%filters)=@_;
                   8893:     my $uhome=&homeserver($uname,$udom);
                   8894:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8895:     my $uhost=&hostname($uhome);
1.800     albertel 8896:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8897:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8898:                        $uhome);
1.479     albertel 8899:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8900:     return get_query_reply($queryid);
                   8901: }
                   8902: 
1.818     raeburn  8903: # -------------------------- Update MySQL table for portfolio file
                   8904: 
                   8905: sub update_portfolio_table {
1.821     raeburn  8906:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8907:     if ($group ne '') {
                   8908:         $file_name =~s /^\Q$group\E//;
                   8909:     }
1.818     raeburn  8910:     my $homeserver = &homeserver($uname,$udom);
                   8911:     my $queryid=
1.821     raeburn  8912:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8913:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8914:     my $reply = &get_query_reply($queryid);
                   8915:     return $reply;
                   8916: }
                   8917: 
1.899     raeburn  8918: # -------------------------- Update MySQL allusers table
                   8919: 
                   8920: sub update_allusers_table {
                   8921:     my ($uname,$udom,$names) = @_;
                   8922:     my $homeserver = &homeserver($uname,$udom);
                   8923:     my $queryid=
                   8924:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8925:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8926:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8927:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8928:                'generation='.&escape($names->{'generation'}).'%%'.
                   8929:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8930:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8931:     return;
1.899     raeburn  8932: }
                   8933: 
1.508     raeburn  8934: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8935: 
                   8936: sub fetch_enrollment_query {
1.511     raeburn  8937:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  8938:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8939:     my $maxtries = 1;
1.508     raeburn  8940:     if ($context eq 'automated') {
                   8941:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  8942:         $sleep = 2;
                   8943:         $loopmax = 100;
1.547     raeburn  8944:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8945:     } else {
                   8946:         $homeserver = &homeserver($cnum,$dom);
                   8947:     }
1.838     albertel 8948:     my $host=&hostname($homeserver);
1.506     raeburn  8949:     my $cmd = '';
1.1000    raeburn  8950:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8951:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8952:     }
                   8953:     $cmd =~ s/%%$//;
                   8954:     $cmd = &escape($cmd);
                   8955:     my $query = 'fetchenrollment';
1.620     albertel 8956:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8957:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8958:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8959:         return 'error: '.$queryid;
                   8960:     }
1.1317    raeburn  8961:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8962:     my $tries = 1;
                   8963:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  8964:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8965:         $tries ++;
                   8966:     }
1.526     raeburn  8967:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8968:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8969:     } else {
1.901     albertel 8970:         my @responses = split(/:/,$reply);
1.1322    raeburn  8971:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8972:             foreach my $line (@responses) {
                   8973:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8974:                 $$replyref{$key} = $value;
                   8975:             }
                   8976:         } else {
1.1117    foxr     8977:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8978:             foreach my $line (@responses) {
                   8979:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8980:                 $$replyref{$key} = $value;
                   8981:                 if ($value > 0) {
1.800     albertel 8982:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8983:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8984:                         my $destname = $pathname.'/'.$filename;
                   8985:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8986:                         if ($xml_classlist =~ /^error/) {
                   8987:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8988:                         } else {
1.1359    raeburn  8989:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8990:                                 print FILE &unescape($xml_classlist);
                   8991:                                 close(FILE);
1.526     raeburn  8992:                             } else {
                   8993:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8994:                             }
                   8995:                         }
                   8996:                     }
                   8997:                 }
                   8998:             }
                   8999:         }
                   9000:         return 'ok';
                   9001:     }
                   9002:     return 'error';
                   9003: }
                   9004: 
1.242     www      9005: sub get_query_reply {
1.1317    raeburn  9006:     my ($queryid,$sleep,$loopmax) = @_;;
                   9007:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9008:         $sleep = 0.2;
                   9009:     }
                   9010:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9011:         $loopmax = 100;
                   9012:     }
1.1117    foxr     9013:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9014:     my $reply='';
1.1317    raeburn  9015:     for (1..$loopmax) {
                   9016: 	sleep($sleep);
1.240     www      9017:         if (-e $replyfile.'.end') {
1.1359    raeburn  9018: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9019: 		$reply = join('',<$fh>);
                   9020: 		close($fh);
1.240     www      9021: 	   } else { return 'error: reply_file_error'; }
1.242     www      9022:            return &unescape($reply);
                   9023: 	}
1.240     www      9024:     }
1.242     www      9025:     return 'timeout:'.$queryid;
1.240     www      9026: }
                   9027: 
                   9028: sub courselog_query {
1.241     www      9029: #
                   9030: # possible filters:
                   9031: # url: url or symb
                   9032: # username
                   9033: # domain
                   9034: # action: view, submit, grade
                   9035: # start: timestamp
                   9036: # end: timestamp
                   9037: #
1.240     www      9038:     my (%filters)=@_;
1.620     albertel 9039:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9040:     if ($filters{'url'}) {
                   9041: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9042:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9043:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9044:     }
1.620     albertel 9045:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9046:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9047:     return &log_query($cname,$cdom,'courselog',%filters);
                   9048: }
                   9049: 
                   9050: sub userlog_query {
1.858     raeburn  9051: #
                   9052: # possible filters:
                   9053: # action: log check role
                   9054: # start: timestamp
                   9055: # end: timestamp
                   9056: #
1.240     www      9057:     my ($uname,$udom,%filters)=@_;
                   9058:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9059: }
                   9060: 
1.506     raeburn  9061: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9062: 
                   9063: sub auto_run {
1.508     raeburn  9064:     my ($cnum,$cdom) = @_;
1.876     raeburn  9065:     my $response = 0;
                   9066:     my $settings;
                   9067:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9068:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9069:         $settings = $domconfig{'autoenroll'};
                   9070:         if ($settings->{'run'} eq '1') {
                   9071:             $response = 1;
                   9072:         }
                   9073:     } else {
1.934     raeburn  9074:         my $homeserver;
                   9075:         if (&is_course($cdom,$cnum)) {
                   9076:             $homeserver = &homeserver($cnum,$cdom);
                   9077:         } else {
                   9078:             $homeserver = &domain($cdom,'primary');
                   9079:         }
                   9080:         if ($homeserver ne 'no_host') {
                   9081:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9082:         }
1.876     raeburn  9083:     }
1.506     raeburn  9084:     return $response;
                   9085: }
1.776     albertel 9086: 
1.506     raeburn  9087: sub auto_get_sections {
1.508     raeburn  9088:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9089:     my $homeserver;
                   9090:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9091:         $homeserver = &homeserver($cnum,$cdom);
                   9092:     }
                   9093:     if (!defined($homeserver)) { 
                   9094:         if ($cdom =~ /^$match_domain$/) {
                   9095:             $homeserver = &domain($cdom,'primary');
                   9096:         }
                   9097:     }
                   9098:     my @secs;
                   9099:     if (defined($homeserver)) {
                   9100:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9101:         unless ($response eq 'refused') {
                   9102:             @secs = split(/:/,$response);
                   9103:         }
1.506     raeburn  9104:     }
                   9105:     return @secs;
                   9106: }
1.776     albertel 9107: 
1.506     raeburn  9108: sub auto_new_course {
1.1099    raeburn  9109:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9110:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9111:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9112:     return $response;
                   9113: }
1.776     albertel 9114: 
1.506     raeburn  9115: sub auto_validate_courseID {
1.508     raeburn  9116:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9117:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9118:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9119:     return $response;
                   9120: }
1.776     albertel 9121: 
1.1007    raeburn  9122: sub auto_validate_instcode {
1.1020    raeburn  9123:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9124:     my ($homeserver,$response);
                   9125:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9126:         $homeserver = &homeserver($cnum,$cdom);
                   9127:     }
                   9128:     if (!defined($homeserver)) {
                   9129:         if ($cdom =~ /^$match_domain$/) {
                   9130:             $homeserver = &domain($cdom,'primary');
                   9131:         }
                   9132:     }
1.1065    raeburn  9133:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9134:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  9135:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9136:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9137: }
                   9138: 
1.506     raeburn  9139: sub auto_create_password {
1.873     raeburn  9140:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9141:     my ($homeserver,$response);
1.506     raeburn  9142:     my $create_passwd = 0;
                   9143:     my $authchk = '';
1.873     raeburn  9144:     if ($udom =~ /^$match_domain$/) {
                   9145:         $homeserver = &domain($udom,'primary');
                   9146:     }
                   9147:     if ($homeserver eq '') {
                   9148:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9149:             $homeserver = &homeserver($cnum,$cdom);
                   9150:         }
                   9151:     }
                   9152:     if ($homeserver eq '') {
                   9153:         $authchk = 'nodomain';
1.506     raeburn  9154:     } else {
1.873     raeburn  9155:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9156:         if ($response eq 'refused') {
                   9157:             $authchk = 'refused';
                   9158:         } else {
1.901     albertel 9159:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9160:         }
1.506     raeburn  9161:     }
                   9162:     return ($authparam,$create_passwd,$authchk);
                   9163: }
                   9164: 
1.706     raeburn  9165: sub auto_photo_permission {
                   9166:     my ($cnum,$cdom,$students) = @_;
                   9167:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9168:     my ($outcome,$perm_reqd,$conditions) = 
                   9169: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9170:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9171: 	return (undef,undef);
                   9172:     }
1.706     raeburn  9173:     return ($outcome,$perm_reqd,$conditions);
                   9174: }
                   9175: 
                   9176: sub auto_checkphotos {
                   9177:     my ($uname,$udom,$pid) = @_;
                   9178:     my $homeserver = &homeserver($uname,$udom);
                   9179:     my ($result,$resulttype);
                   9180:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9181: 				   &escape($uname).':'.&escape($pid),
                   9182: 				   $homeserver));
1.709     albertel 9183:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9184: 	return (undef,undef);
                   9185:     }
1.706     raeburn  9186:     if ($outcome) {
                   9187:         ($result,$resulttype) = split(/:/,$outcome);
                   9188:     } 
                   9189:     return ($result,$resulttype);
                   9190: }
                   9191: 
                   9192: sub auto_photochoice {
                   9193:     my ($cnum,$cdom) = @_;
                   9194:     my $homeserver = &homeserver($cnum,$cdom);
                   9195:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9196: 						       &escape($cdom),
                   9197: 						       $homeserver)));
1.709     albertel 9198:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9199: 	return (undef,undef);
                   9200:     }
1.706     raeburn  9201:     return ($update,$comment);
                   9202: }
                   9203: 
                   9204: sub auto_photoupdate {
                   9205:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9206:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9207:     my $host=&hostname($homeserver);
1.706     raeburn  9208:     my $cmd = '';
                   9209:     my $maxtries = 1;
1.800     albertel 9210:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9211:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9212:     }
                   9213:     $cmd =~ s/%%$//;
                   9214:     $cmd = &escape($cmd);
                   9215:     my $query = 'institutionalphotos';
                   9216:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9217:     unless ($queryid=~/^\Q$host\E\_/) {
                   9218:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9219:         return 'error: '.$queryid;
                   9220:     }
                   9221:     my $reply = &get_query_reply($queryid);
                   9222:     my $tries = 1;
                   9223:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9224:         $reply = &get_query_reply($queryid);
                   9225:         $tries ++;
                   9226:     }
                   9227:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9228:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9229:     } else {
                   9230:         my @responses = split(/:/,$reply);
                   9231:         my $outcome = shift(@responses); 
                   9232:         foreach my $item (@responses) {
                   9233:             my ($key,$value) = split(/=/,$item);
                   9234:             $$photo{$key} = $value;
                   9235:         }
                   9236:         return $outcome;
                   9237:     }
                   9238:     return 'error';
                   9239: }
                   9240: 
1.521     raeburn  9241: sub auto_instcode_format {
1.793     albertel 9242:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9243: 	$cat_order) = @_;
1.521     raeburn  9244:     my $courses = '';
1.772     raeburn  9245:     my @homeservers;
1.521     raeburn  9246:     if ($caller eq 'global') {
1.841     albertel 9247: 	my %servers = &get_servers($codedom,'library');
                   9248: 	foreach my $tryserver (keys(%servers)) {
                   9249: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9250: 		push(@homeservers,$tryserver);
                   9251: 	    }
1.584     raeburn  9252:         }
1.1022    raeburn  9253:     } elsif ($caller eq 'requests') {
                   9254:         if ($codedom =~ /^$match_domain$/) {
                   9255:             my $chome = &domain($codedom,'primary');
                   9256:             unless ($chome eq 'no_host') {
                   9257:                 push(@homeservers,$chome);
                   9258:             }
                   9259:         }
1.521     raeburn  9260:     } else {
1.772     raeburn  9261:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9262:     }
1.793     albertel 9263:     foreach my $code (keys(%{$instcodes})) {
                   9264:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9265:     }
                   9266:     chop($courses);
1.772     raeburn  9267:     my $ok_response = 0;
                   9268:     my $response;
                   9269:     while (@homeservers > 0 && $ok_response == 0) {
                   9270:         my $server = shift(@homeservers); 
                   9271:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9272:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9273:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9274: 		split(/:/,$response);
1.772     raeburn  9275:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9276:             push(@{$codetitles},&str2array($codetitles_str));
                   9277:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9278:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9279:             $ok_response = 1;
                   9280:         }
                   9281:     }
                   9282:     if ($ok_response) {
1.521     raeburn  9283:         return 'ok';
1.772     raeburn  9284:     } else {
                   9285:         return $response;
1.521     raeburn  9286:     }
                   9287: }
                   9288: 
1.792     raeburn  9289: sub auto_instcode_defaults {
                   9290:     my ($domain,$returnhash,$code_order) = @_;
                   9291:     my @homeservers;
1.841     albertel 9292: 
                   9293:     my %servers = &get_servers($domain,'library');
                   9294:     foreach my $tryserver (keys(%servers)) {
                   9295: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9296: 	    push(@homeservers,$tryserver);
                   9297: 	}
1.792     raeburn  9298:     }
1.841     albertel 9299: 
1.792     raeburn  9300:     my $response;
1.841     albertel 9301:     foreach my $server (@homeservers) {
1.792     raeburn  9302:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9303:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9304: 	
                   9305: 	foreach my $pair (split(/\&/,$response)) {
                   9306: 	    my ($name,$value)=split(/\=/,$pair);
                   9307: 	    if ($name eq 'code_order') {
                   9308: 		@{$code_order} = split(/\&/,&unescape($value));
                   9309: 	    } else {
                   9310: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9311: 	    }
                   9312: 	}
                   9313: 	return 'ok';
1.792     raeburn  9314:     }
1.841     albertel 9315: 
                   9316:     return $response;
1.1003    raeburn  9317: }
                   9318: 
                   9319: sub auto_possible_instcodes {
1.1007    raeburn  9320:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9321:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9322:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9323:         return;
                   9324:     }
1.1003    raeburn  9325:     my (@homeservers,$uhome);
                   9326:     if (defined(&domain($domain,'primary'))) {
                   9327:         $uhome=&domain($domain,'primary');
                   9328:         push(@homeservers,&domain($domain,'primary'));
                   9329:     } else {
                   9330:         my %servers = &get_servers($domain,'library');
                   9331:         foreach my $tryserver (keys(%servers)) {
                   9332:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9333:                 push(@homeservers,$tryserver);
                   9334:             }
                   9335:         }
                   9336:     }
                   9337:     my $response;
                   9338:     foreach my $server (@homeservers) {
                   9339:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9340:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9341:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9342:             split(':',$response);
                   9343:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9344:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9345:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9346:             my ($name,$value)=split('=',$item);
                   9347:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9348:         }
                   9349:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9350:             my ($name,$value)=split('=',$item);
                   9351:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9352:         }
                   9353:         return 'ok';
                   9354:     }
                   9355:     return $response;
                   9356: }
1.792     raeburn  9357: 
1.1010    raeburn  9358: sub auto_courserequest_checks {
                   9359:     my ($dom) = @_;
1.1020    raeburn  9360:     my ($homeserver,%validations);
                   9361:     if ($dom =~ /^$match_domain$/) {
                   9362:         $homeserver = &domain($dom,'primary');
                   9363:     }
                   9364:     unless ($homeserver eq 'no_host') {
                   9365:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9366:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9367:             my @items = split(/&/,$response);
                   9368:             foreach my $item (@items) {
                   9369:                 my ($key,$value) = split('=',$item);
                   9370:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9371:             }
                   9372:         }
                   9373:     }
1.1010    raeburn  9374:     return %validations; 
                   9375: }
                   9376: 
1.1020    raeburn  9377: sub auto_courserequest_validation {
1.1255    raeburn  9378:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9379:     my ($homeserver,$response);
                   9380:     if ($dom =~ /^$match_domain$/) {
                   9381:         $homeserver = &domain($dom,'primary');
                   9382:     }
1.1255    raeburn  9383:     unless ($homeserver eq 'no_host') {
                   9384:         my $customdata;
                   9385:         if (ref($custominfo) eq 'HASH') {
                   9386:             $customdata = &freeze_escape($custominfo);
                   9387:         }
1.1020    raeburn  9388:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9389:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  9390:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9391:                                     $customdata,$homeserver));
1.1020    raeburn  9392:     }
                   9393:     return $response;
                   9394: }
                   9395: 
1.777     albertel 9396: sub auto_validate_class_sec {
1.918     raeburn  9397:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9398:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9399:     my $ownerlist;
                   9400:     if (ref($owners) eq 'ARRAY') {
                   9401:         $ownerlist = join(',',@{$owners});
                   9402:     } else {
                   9403:         $ownerlist = $owners;
                   9404:     }
1.773     raeburn  9405:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9406:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9407:     return $response;
                   9408: }
                   9409: 
1.1367    raeburn  9410: sub auto_validate_instclasses {
                   9411:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9412:     my ($homeserver,%validations);
                   9413:     $homeserver = &homeserver($cnum,$cdom);
                   9414:     unless ($homeserver eq 'no_host') {
                   9415:         my $ownerlist;
                   9416:         if (ref($owners) eq 'ARRAY') {
                   9417:             $ownerlist = join(',',@{$owners});
                   9418:         } else {
                   9419:             $ownerlist = $owners;
                   9420:         }
                   9421:         if (ref($classesref) eq 'HASH') {
                   9422:             my $classes = &freeze_escape($classesref);
                   9423:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9424:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9425:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9426:                 my @items = split(/&/,$response);
                   9427:                 foreach my $item (@items) {
                   9428:                     my ($key,$value) = split('=',$item);
                   9429:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9430:                 }
                   9431:             }
                   9432:         }
                   9433:     }
                   9434:     return %validations;
                   9435: }
                   9436: 
1.1248    raeburn  9437: sub auto_crsreq_update {
                   9438:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  9439:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  9440:     my ($homeserver,%crsreqresponse);
                   9441:     if ($cdom =~ /^$match_domain$/) {
                   9442:         $homeserver = &domain($cdom,'primary');
                   9443:     }
                   9444:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9445:         my $info;
                   9446:         if (ref($inbound) eq 'HASH') {
                   9447:             $info = &freeze_escape($inbound);
                   9448:         }
                   9449:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9450:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9451:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  9452:                             &escape($title).':'.&escape($code).':'.
                   9453:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   9454:                             $homeserver);
1.1248    raeburn  9455:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9456:             my @items = split(/&/,$response);
                   9457:             foreach my $item (@items) {
                   9458:                 my ($key,$value) = split('=',$item);
                   9459:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9460:             }
                   9461:         }
                   9462:     }
                   9463:     return \%crsreqresponse;
                   9464: }
                   9465: 
1.1305    raeburn  9466: sub auto_export_grades {
1.1309    raeburn  9467:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9468:     my ($homeserver,%exportresponse);
                   9469:     if ($cdom =~ /^$match_domain$/) {
                   9470:         $homeserver = &domain($cdom,'primary');
                   9471:     }
                   9472:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9473:         my $info;
                   9474:         if (ref($inforef) eq 'HASH') {
                   9475:             $info = &freeze_escape($inforef);
                   9476:         }
                   9477:         if (ref($gradesref) eq 'HASH') {
                   9478:             my $grades = &freeze_escape($gradesref);
                   9479:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9480:                                 $info.':'.$grades,$homeserver);
                   9481:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9482:                 my @items = split(/&/,$response);
                   9483:                 foreach my $item (@items) {
                   9484:                     my ($key,$value) = split('=',$item);
                   9485:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9486:                 }
                   9487:             }
                   9488:         }
                   9489:     }
                   9490:     return \%exportresponse;
1.1305    raeburn  9491: }
                   9492: 
1.1287    raeburn  9493: sub check_instcode_cloning {
                   9494:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9495:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9496:         return;
                   9497:     }
                   9498:     my $canclone;
                   9499:     if (@{$code_order} > 0) {
                   9500:         my $instcoderegexp ='^';
                   9501:         my @clonecodes = split(/\&/,$cloner);
                   9502:         foreach my $item (@{$code_order}) {
                   9503:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9504:                 foreach my $pair (@clonecodes) {
                   9505:                     my ($key,$val) = split(/\=/,$pair,2);
                   9506:                     $val = &unescape($val);
                   9507:                     if ($key eq $item) {
                   9508:                         $instcoderegexp .= '('.$val.')';
                   9509:                         last;
                   9510:                     }
                   9511:                 }
                   9512:             } else {
                   9513:                 $instcoderegexp .= $codedefaults->{$item};
                   9514:             }
                   9515:         }
                   9516:         $instcoderegexp .= '$';
                   9517:         my (@from,@to);
                   9518:         eval {
                   9519:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9520:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9521:         };
                   9522:         if ((@from > 0) && (@to > 0)) {
                   9523:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9524:             if (!@diffs) {
                   9525:                 $canclone = 1;
                   9526:             }
                   9527:         }
                   9528:     }
                   9529:     return $canclone;
                   9530: }
                   9531: 
                   9532: sub default_instcode_cloning {
                   9533:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9534:     my (%codedefaults,@code_order,$canclone);
                   9535:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9536:         %codedefaults = %{$codedefaultsref};
                   9537:         @code_order = @{$codeorderref};
                   9538:     } elsif ($clonedom) {
                   9539:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9540:     }
                   9541:     if (($domdefclone) && (@code_order)) {
                   9542:         my @clonecodes = split(/\+/,$domdefclone);
                   9543:         my $instcoderegexp ='^';
                   9544:         foreach my $item (@code_order) {
                   9545:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9546:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9547:             } else {
                   9548:                 $instcoderegexp .= $codedefaults{$item};
                   9549:             }
                   9550:         }
                   9551:         $instcoderegexp .= '$';
                   9552:         my (@from,@to);
                   9553:         eval {
                   9554:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9555:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9556:         };
                   9557:         if ((@from > 0) && (@to > 0)) {
                   9558:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9559:             if (!@diffs) {
                   9560:                 $canclone = 1;
                   9561:             }
                   9562:         }
                   9563:     }
                   9564:     return $canclone;
                   9565: }
                   9566: 
1.679     raeburn  9567: # ------------------------------------------------------- Course Group routines
                   9568: 
                   9569: sub get_coursegroups {
1.809     raeburn  9570:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9571:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9572: }
                   9573: 
1.679     raeburn  9574: sub modify_coursegroup {
                   9575:     my ($cdom,$cnum,$groupsettings) = @_;
                   9576:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9577: }
                   9578: 
1.809     raeburn  9579: sub toggle_coursegroup_status {
                   9580:     my ($cdom,$cnum,$group,$action) = @_;
                   9581:     my ($from_namespace,$to_namespace);
                   9582:     if ($action eq 'delete') {
                   9583:         $from_namespace = 'coursegroups';
                   9584:         $to_namespace = 'deleted_groups';
                   9585:     } else {
                   9586:         $from_namespace = 'deleted_groups';
                   9587:         $to_namespace = 'coursegroups';
                   9588:     }
                   9589:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9590:     if (my $tmp = &error(%curr_group)) {
                   9591:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9592:         return ('read error',$tmp);
                   9593:     } else {
                   9594:         my %savedsettings = %curr_group; 
1.809     raeburn  9595:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9596:         my $deloutcome;
                   9597:         if ($result eq 'ok') {
1.809     raeburn  9598:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9599:         } else {
                   9600:             return ('write error',$result);
                   9601:         }
                   9602:         if ($deloutcome eq 'ok') {
                   9603:             return 'ok';
                   9604:         } else {
                   9605:             return ('delete error',$deloutcome);
                   9606:         }
                   9607:     }
                   9608: }
                   9609: 
1.679     raeburn  9610: sub modify_group_roles {
1.957     raeburn  9611:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9612:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9613:     my $role = 'gr/'.&escape($userprivs);
                   9614:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9615:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9616:     if ($result eq 'ok') {
                   9617:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9618:     }
1.679     raeburn  9619:     return $result;
                   9620: }
                   9621: 
                   9622: sub modify_coursegroup_membership {
                   9623:     my ($cdom,$cnum,$membership) = @_;
                   9624:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9625:     return $result;
                   9626: }
                   9627: 
1.682     raeburn  9628: sub get_active_groups {
                   9629:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9630:     my $now = time;
                   9631:     my %groups = ();
                   9632:     foreach my $key (keys(%env)) {
1.811     albertel 9633:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9634:             my ($start,$end) = split(/\./,$env{$key});
                   9635:             if (($end!=0) && ($end<$now)) { next; }
                   9636:             if (($start!=0) && ($start>$now)) { next; }
                   9637:             if ($1 eq $cdom && $2 eq $cnum) {
                   9638:                 $groups{$3} = $env{$key} ;
                   9639:             }
                   9640:         }
                   9641:     }
                   9642:     return %groups;
                   9643: }
                   9644: 
1.683     raeburn  9645: sub get_group_membership {
                   9646:     my ($cdom,$cnum,$group) = @_;
                   9647:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9648: }
                   9649: 
                   9650: sub get_users_groups {
                   9651:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9652:     my @usersgroups;
1.683     raeburn  9653:     my $cachetime=1800;
                   9654: 
                   9655:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9656:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9657:     if (defined($cached)) {
1.734     albertel 9658:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9659:     } else {  
                   9660:         $grouplist = '';
1.816     raeburn  9661:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9662:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9663:         my $access_end = $env{'course.'.$courseid.
                   9664:                               '.default_enrollment_end_date'};
                   9665:         my $now = time;
                   9666:         foreach my $key (keys(%roleshash)) {
                   9667:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9668:                 my $group = $1;
                   9669:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9670:                     my $start = $2;
                   9671:                     my $end = $1;
                   9672:                     if ($start == -1) { next; } # deleted from group
                   9673:                     if (($start!=0) && ($start>$now)) { next; }
                   9674:                     if (($end!=0) && ($end<$now)) {
                   9675:                         if ($access_end && $access_end < $now) {
                   9676:                             if ($access_end - $end < 86400) {
                   9677:                                 push(@usersgroups,$group);
1.733     raeburn  9678:                             }
                   9679:                         }
1.817     raeburn  9680:                         next;
1.733     raeburn  9681:                     }
1.817     raeburn  9682:                     push(@usersgroups,$group);
1.683     raeburn  9683:                 }
                   9684:             }
                   9685:         }
1.817     raeburn  9686:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9687:         $grouplist = join(':',@usersgroups);
                   9688:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9689:     }
1.733     raeburn  9690:     return @usersgroups;
1.683     raeburn  9691: }
                   9692: 
                   9693: sub devalidate_getgroups_cache {
                   9694:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9695:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9696: 
1.683     raeburn  9697:     my $hashid="$udom:$uname:$courseid";
                   9698:     &devalidate_cache_new('getgroups',$hashid);
                   9699: }
                   9700: 
1.12      www      9701: # ------------------------------------------------------------------ Plain Text
                   9702: 
                   9703: sub plaintext {
1.988     raeburn  9704:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9705:     if ($short =~ m{^cr/}) {
1.758     albertel 9706: 	return (split('/',$short))[-1];
                   9707:     }
1.742     raeburn  9708:     if (!defined($cid)) {
                   9709:         $cid = $env{'request.course.id'};
                   9710:     }
                   9711:     my %rolenames = (
1.1008    raeburn  9712:                       Course    => 'std',
                   9713:                       Community => 'alt1',
1.1305    raeburn  9714:                       Placement => 'std',
1.742     raeburn  9715:                     );
1.1037    raeburn  9716:     if ($cid ne '') {
                   9717:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9718:             unless ($forcedefault) {
                   9719:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9720:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9721:                 return &Apache::lonlocal::mt($roletext);
                   9722:             }
                   9723:         }
                   9724:     }
                   9725:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9726:         (defined($rolenames{$type})) && 
                   9727:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9728:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9729:     } elsif ($cid ne '') {
                   9730:         my $crstype = $env{'course.'.$cid.'.type'};
                   9731:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9732:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9733:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9734:         }
1.742     raeburn  9735:     }
1.1037    raeburn  9736:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9737: }
                   9738: 
                   9739: # ----------------------------------------------------------------- Assign Role
                   9740: 
                   9741: sub assignrole {
1.957     raeburn  9742:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9743:         $context)=@_;
1.21      www      9744:     my $mrole;
                   9745:     if ($role =~ /^cr\//) {
1.393     www      9746:         my $cwosec=$url;
1.811     albertel 9747:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9748: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9749:            my $refused = 1;
                   9750:            if ($context eq 'requestcourses') {
                   9751:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9752:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9753:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9754:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9755:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9756:                            if ($crsenv{'internal.courseowner'} eq
                   9757:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9758:                                $refused = '';
                   9759:                            }
                   9760:                        }
                   9761:                    }
                   9762:                }
                   9763:            }
                   9764:            if ($refused) {
                   9765:                &logthis('Refused custom assignrole: '.
                   9766:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9767:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9768:                return 'refused';
                   9769:            }
1.104     www      9770:         }
1.21      www      9771:         $mrole='cr';
1.678     raeburn  9772:     } elsif ($role =~ /^gr\//) {
                   9773:         my $cwogrp=$url;
1.811     albertel 9774:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9775:         unless (&allowed('mdg',$cwogrp)) {
                   9776:             &logthis('Refused group assignrole: '.
                   9777:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9778:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9779:             return 'refused';
                   9780:         }
                   9781:         $mrole='gr';
1.21      www      9782:     } else {
1.82      www      9783:         my $cwosec=$url;
1.811     albertel 9784:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9785:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9786:             my $refused;
                   9787:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9788:                 if (!(&allowed('c'.$role,$url))) {
                   9789:                     $refused = 1;
                   9790:                 }
                   9791:             } else {
                   9792:                 $refused = 1;
                   9793:             }
1.947     raeburn  9794:             if ($refused) {
1.1045    raeburn  9795:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377    raeburn  9796:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  9797:                     my %crsenv;
                   9798:                     if ($role eq 'cc' || $role eq 'co') {
                   9799:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9800:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9801:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9802:                                 if ($crsenv{'internal.courseowner'} eq 
                   9803:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9804:                                     $refused = '';
                   9805:                                 }
                   9806:                             }
                   9807:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9808:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9809:                                 if ($crsenv{'internal.courseowner'} eq 
                   9810:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9811:                                     $refused = '';
                   9812:                                 }
                   9813:                             }
                   9814:                         }
                   9815:                     }
1.1368    raeburn  9816:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   9817:                     if ($role eq 'st') {
                   9818:                         $refused = '';
1.1377    raeburn  9819:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  9820:                         $refused = '';
                   9821:                     }
1.1017    raeburn  9822:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9823:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9824:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9825:                         my $wrongcc;
                   9826:                         if ($cnum =~ /^$match_community$/) {
                   9827:                             $wrongcc = 1 if ($role eq 'cc');
                   9828:                         } else {
                   9829:                             $wrongcc = 1 if ($role eq 'co');
                   9830:                         }
                   9831:                         unless ($wrongcc) {
                   9832:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9833:                             if ($crsenv{'internal.courseowner'} eq 
                   9834:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9835:                                 $refused = '';
                   9836:                             }
1.1017    raeburn  9837:                         }
                   9838:                     }
1.1183    raeburn  9839:                 } elsif ($context eq 'requestauthor') {
                   9840:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   9841:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9842:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9843:                             $refused = '';
                   9844:                         } else {
                   9845:                             my %domdefaults = &get_domain_defaults($udom);
                   9846:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9847:                                 my $checkbystatus;
                   9848:                                 if ($env{'user.adv'}) { 
                   9849:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9850:                                     if ($disposition eq 'automatic') {
                   9851:                                         $refused = '';
                   9852:                                     } elsif ($disposition eq '') {
                   9853:                                         $checkbystatus = 1;
                   9854:                                     } 
                   9855:                                 } else {
                   9856:                                     $checkbystatus = 1;
                   9857:                                 }
                   9858:                                 if ($checkbystatus) {
                   9859:                                     if ($env{'environment.inststatus'}) {
                   9860:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9861:                                         foreach my $type (@inststatuses) {
                   9862:                                             if (($type ne '') &&
                   9863:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9864:                                                 $refused = '';
                   9865:                                             }
                   9866:                                         }
                   9867:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9868:                                         $refused = '';
                   9869:                                     }
                   9870:                                 }
                   9871:                             }
                   9872:                         }
                   9873:                     }
1.1017    raeburn  9874:                 }
                   9875:                 if ($refused) {
1.947     raeburn  9876:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9877:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9878: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9879:                     return 'refused';
                   9880:                 }
1.932     raeburn  9881:             }
1.1131    raeburn  9882:         } elsif ($role eq 'au') {
                   9883:             if ($url ne '/'.$udom.'/') {
                   9884:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9885:                          ' to assign author role for '.$uname.':'.$udom.
                   9886:                          ' in domain: '.$url.' refused (wrong domain).');
                   9887:                 return 'refused';
                   9888:             }
1.104     www      9889:         }
1.21      www      9890:         $mrole=$role;
                   9891:     }
1.620     albertel 9892:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9893:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9894:     if ($end) { $command.='_'.$end; }
1.21      www      9895:     if ($start) {
                   9896: 	if ($end) { 
1.81      www      9897:            $command.='_'.$start; 
1.21      www      9898:         } else {
1.81      www      9899:            $command.='_0_'.$start;
1.21      www      9900:         }
                   9901:     }
1.739     raeburn  9902:     my $origstart = $start;
                   9903:     my $origend = $end;
1.957     raeburn  9904:     my $delflag;
1.357     www      9905: # actually delete
                   9906:     if ($deleteflag) {
1.373     www      9907: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9908: # modify command to delete the role
1.620     albertel 9909:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9910:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9911: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9912: # set start and finish to negative values for userrolelog
                   9913:            $start=-1;
                   9914:            $end=-1;
1.957     raeburn  9915:            $delflag = 1;
1.357     www      9916:         }
                   9917:     }
                   9918: # send command
1.349     www      9919:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9920: # log new user role if status is ok
1.349     www      9921:     if ($answer eq 'ok') {
1.663     raeburn  9922: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  9923:         if (($role eq 'cc') || ($role eq 'in') ||
                   9924:             ($role eq 'ep') || ($role eq 'ad') ||
                   9925:             ($role eq 'ta') || ($role eq 'st') ||
                   9926:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9927:             ($role eq 'co')) {
1.1200    raeburn  9928: # for course roles, perform group memberships changes triggered by role change.
                   9929:             unless ($role =~ /^gr/) {
                   9930:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9931:                                                  $origstart,$selfenroll,$context);
                   9932:             }
1.1184    raeburn  9933:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9934:                            $selfenroll,$context);
                   9935:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  9936:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9937:                  ($role eq 'da')) {
1.1184    raeburn  9938:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9939:                            $context);
                   9940:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9941:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9942:                              $context); 
                   9943:         }
1.1053    raeburn  9944:         if ($role eq 'cc') {
                   9945:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9946:         }
1.349     www      9947:     }
                   9948:     return $answer;
1.169     harris41 9949: }
                   9950: 
1.1053    raeburn  9951: sub autoupdate_coowners {
                   9952:     my ($url,$end,$start,$uname,$udom) = @_;
                   9953:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9954:     if (($cdom ne '') && ($cnum ne '')) {
                   9955:         my $now = time;
                   9956:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9957:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9958:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9959:             my $instcode = $coursehash{'internal.coursecode'};
                   9960:             if ($instcode ne '') {
1.1056    raeburn  9961:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9962:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9963:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9964:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9965:                         if ($result eq 'valid') {
                   9966:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9967:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9968:                                     push(@newcoowners,$coowner);
                   9969:                                 }
                   9970:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9971:                                     push(@newcoowners,$uname.':'.$udom);
                   9972:                                 }
                   9973:                                 @newcoowners = sort(@newcoowners);
                   9974:                             } else {
                   9975:                                 push(@newcoowners,$uname.':'.$udom);
                   9976:                             }
                   9977:                         } else {
                   9978:                             if ($coursehash{'internal.co-owners'}) {
                   9979:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9980:                                     unless ($coowner eq $uname.':'.$udom) {
                   9981:                                         push(@newcoowners,$coowner);
                   9982:                                     }
                   9983:                                 }
                   9984:                                 unless (@newcoowners > 0) {
                   9985:                                     $delcoowners = 1;
                   9986:                                     $coowners = '';
                   9987:                                 }
                   9988:                             }
                   9989:                         }
                   9990:                         if (@newcoowners || $delcoowners) {
                   9991:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9992:                                             $delcoowners,@newcoowners);
                   9993:                         }
                   9994:                     }
                   9995:                 }
                   9996:             }
                   9997:         }
                   9998:     }
                   9999: }
                   10000: 
                   10001: sub store_coowners {
                   10002:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10003:     my $cid = $cdom.'_'.$cnum;
                   10004:     my ($coowners,$delresult,$putresult);
                   10005:     if (@newcoowners) {
                   10006:         $coowners = join(',',@newcoowners);
                   10007:         my %coownershash = (
                   10008:                             'internal.co-owners' => $coowners,
                   10009:                            );
                   10010:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10011:         if ($putresult eq 'ok') {
                   10012:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10013:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10014:             }
                   10015:         }
                   10016:     }
                   10017:     if ($delcoowners) {
                   10018:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10019:         if ($delresult eq 'ok') {
                   10020:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10021:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10022:             }
                   10023:         }
                   10024:     }
                   10025:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10026:         my %crsinfo =
                   10027:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10028:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10029:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10030:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10031:         }
                   10032:     }
                   10033: }
                   10034: 
1.169     harris41 10035: # -------------------------------------------------- Modify user authentication
1.197     www      10036: # Overrides without validation
                   10037: 
1.169     harris41 10038: sub modifyuserauth {
                   10039:     my ($udom,$uname,$umode,$upass)=@_;
                   10040:     my $uhome=&homeserver($uname,$udom);
1.197     www      10041:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   10042:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10043:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10044:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10045:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10046: 		     &escape($upass),$uhome);
1.620     albertel 10047:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10048:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   10049:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   10050:     &log($udom,,$uname,$uhome,
1.620     albertel 10051:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10052:                                      $env{'user.name'}.', '.$umode.
1.197     www      10053:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 10054:     unless ($reply eq 'ok') {
1.197     www      10055:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10056: 	return 'error: '.$reply;
                   10057:     }   
1.170     harris41 10058:     return 'ok';
1.80      www      10059: }
                   10060: 
1.81      www      10061: # --------------------------------------------------------------- Modify a user
1.80      www      10062: 
1.81      www      10063: sub modifyuser {
1.206     matthew  10064:     my ($udom,    $uname, $uid,
                   10065:         $umode,   $upass, $first,
                   10066:         $middle,  $last,  $gene,
1.1058    raeburn  10067:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10068:     $udom= &LONCAPA::clean_domain($udom);
                   10069:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10070:     my $showcandelete = 'none';
                   10071:     if (ref($candelete) eq 'ARRAY') {
                   10072:         if (@{$candelete} > 0) {
                   10073:             $showcandelete = join(', ',@{$candelete});
                   10074:         }
                   10075:     }
1.81      www      10076:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10077:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10078: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10079:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10080:                                      ' desiredhome not specified'). 
1.620     albertel 10081:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10082:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10083:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10084:     my $newuser;
                   10085:     if ($uhome eq 'no_host') {
                   10086:         $newuser = 1;
1.1368    raeburn  10087:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   10088:                 ($umode eq 'lti')) {
                   10089:             return 'error: more information needed to create new user';
                   10090:         }
1.1075    raeburn  10091:     }
1.80      www      10092: # ----------------------------------------------------------------- Create User
1.406     albertel 10093:     if (($uhome eq 'no_host') && 
1.1368    raeburn  10094: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      10095:         my $unhome='';
1.844     albertel 10096:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10097:             $unhome = $desiredhome;
1.620     albertel 10098: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10099: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10100:         } else { # load balancing routine for determining $unhome
1.81      www      10101:             my $loadm=10000000;
1.841     albertel 10102: 	    my %servers = &get_servers($udom,'library');
                   10103: 	    foreach my $tryserver (keys(%servers)) {
                   10104: 		my $answer=reply('load',$tryserver);
                   10105: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10106: 		    $loadm=$answer;
                   10107: 		    $unhome=$tryserver;
                   10108: 		}
1.80      www      10109: 	    }
                   10110:         }
                   10111:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10112: 	    return 'error: unable to find a home server for '.$uname.
                   10113:                    ' in domain '.$udom;
1.80      www      10114:         }
                   10115:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10116:                          &escape($upass),$unhome);
                   10117: 	unless ($reply eq 'ok') {
                   10118:             return 'error: '.$reply;
                   10119:         }   
1.230     stredwic 10120:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10121:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10122: 	    return 'error: unable verify users home machine.';
1.80      www      10123:         }
1.209     matthew  10124:     }   # End of creation of new user
1.80      www      10125: # ---------------------------------------------------------------------- Add ID
                   10126:     if ($uid) {
                   10127:        $uid=~tr/A-Z/a-z/;
                   10128:        my %uidhash=&idrget($udom,$uname);
1.196     www      10129:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10130:          && (!$forceid)) {
1.80      www      10131: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10132: 	      return 'error: user id "'.$uid.'" does not match '.
                   10133:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10134:           }
                   10135:        } else {
1.1300    raeburn  10136: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      10137:        }
                   10138:     }
                   10139: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10140:     my @tmp=&get('environment',
1.899     raeburn  10141: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10142:                     'permanentemail','inststatus'],
1.134     albertel 10143: 		   $udom,$uname);
1.1075    raeburn  10144:     my (%names,%oldnames);
1.313     matthew  10145:     if ($tmp[0] =~ m/^error:.*/) { 
                   10146:         %names=(); 
                   10147:     } else {
                   10148:         %names = @tmp;
1.1075    raeburn  10149:         %oldnames = %names;
1.313     matthew  10150:     }
1.388     www      10151: #
1.1058    raeburn  10152: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10153: # of users did not contain them), do not overwrite existing values
                   10154: # unless field is in $candelete array ref.  
                   10155: #
                   10156: 
                   10157:     my @fields = ('firstname','middlename','lastname','generation',
                   10158:                   'permanentemail','id');
                   10159:     my %newvalues;
                   10160:     if (ref($candelete) eq 'ARRAY') {
                   10161:         foreach my $field (@fields) {
                   10162:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10163:                 if ($field eq 'firstname') {
                   10164:                     $names{$field} = $first;
                   10165:                 } elsif ($field eq 'middlename') {
                   10166:                     $names{$field} = $middle;
                   10167:                 } elsif ($field eq 'lastname') {
                   10168:                     $names{$field} = $last;
                   10169:                 } elsif ($field eq 'generation') { 
                   10170:                     $names{$field} = $gene;
                   10171:                 } elsif ($field eq 'permanentemail') {
                   10172:                     $names{$field} = $email;
                   10173:                 } elsif ($field eq 'id') {
                   10174:                     $names{$field}  = $uid;
                   10175:                 }
                   10176:             }
                   10177:         }
                   10178:     }
1.388     www      10179:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10180:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10181:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10182:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10183:     if ($email) {
                   10184:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10185:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10186:     }
1.899     raeburn  10187:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10188:     if (defined($inststatus)) {
                   10189:         $names{'inststatus'} = '';
                   10190:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10191:         if (ref($usertypes) eq 'HASH') {
                   10192:             my @okstatuses; 
                   10193:             foreach my $item (split(/:/,$inststatus)) {
                   10194:                 if (defined($usertypes->{$item})) {
                   10195:                     push(@okstatuses,$item);  
                   10196:                 }
                   10197:             }
                   10198:             if (@okstatuses) {
                   10199:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10200:             }
                   10201:         }
                   10202:     }
1.1075    raeburn  10203:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10204:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10205:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10206:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10207:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10208:     } else {
                   10209:         $logmsg .= ' during self creation';
                   10210:     }
1.1075    raeburn  10211:     my $changed;
                   10212:     if ($newuser) {
                   10213:         $changed = 1;
                   10214:     } else {
                   10215:         foreach my $field (@fields) {
                   10216:             if ($names{$field} ne $oldnames{$field}) {
                   10217:                 $changed = 1;
                   10218:                 last;
                   10219:             }
                   10220:         }
                   10221:     }
                   10222:     unless ($changed) {
                   10223:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10224:         &logthis($logmsg);
                   10225:         return 'ok';
                   10226:     }
                   10227:     my $reply = &put('environment', \%names, $udom,$uname);
                   10228:     if ($reply ne 'ok') { 
                   10229:         return 'error: '.$reply;
                   10230:     }
1.1087    raeburn  10231:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10232:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10233:     }
1.1075    raeburn  10234:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10235:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10236:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10237:     &logthis($logmsg);
1.134     albertel 10238:     return 'ok';
1.80      www      10239: }
                   10240: 
1.81      www      10241: # -------------------------------------------------------------- Modify student
1.80      www      10242: 
1.81      www      10243: sub modifystudent {
                   10244:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10245:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  10246:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10247:     if (!$cid) {
1.620     albertel 10248: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10249: 	    return 'not_in_class';
                   10250: 	}
1.80      www      10251:     }
                   10252: # --------------------------------------------------------------- Make the user
1.81      www      10253:     my $reply=&modifyuser
1.209     matthew  10254: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10255:          $desiredhome,$email,$inststatus);
1.80      www      10256:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10257:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  10258:     # student's environment
1.297     matthew  10259:     $uid = undef if (!$forceid);
1.455     albertel 10260:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  10261:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  10262:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10263:     return $reply;
                   10264: }
                   10265: 
                   10266: sub modify_student_enrollment {
1.1216    raeburn  10267:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  10268:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10269:     my ($cdom,$cnum,$chome);
                   10270:     if (!$cid) {
1.620     albertel 10271: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10272: 	    return 'not_in_class';
                   10273: 	}
1.620     albertel 10274: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10275: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10276:     } else {
                   10277: 	($cdom,$cnum)=split(/_/,$cid);
                   10278:     }
1.620     albertel 10279:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10280:     if (!$chome) {
1.457     raeburn  10281: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10282:     }
1.455     albertel 10283:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10284:     # Make sure the user exists
1.81      www      10285:     my $uhome=&homeserver($uname,$udom);
                   10286:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10287: 	return 'error: no such user';
                   10288:     }
1.297     matthew  10289:     # Get student data if we were not given enough information
                   10290:     if (!defined($first)  || $first  eq '' || 
                   10291:         !defined($last)   || $last   eq '' || 
                   10292:         !defined($uid)    || $uid    eq '' || 
                   10293:         !defined($middle) || $middle eq '' || 
                   10294:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10295:         # They did not supply us with enough data to enroll the student, so
                   10296:         # we need to pick up more information.
1.297     matthew  10297:         my %tmp = &get('environment',
1.294     matthew  10298:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10299:                        ,$udom,$uname);
                   10300: 
1.800     albertel 10301:         #foreach my $key (keys(%tmp)) {
                   10302:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10303:         #}
1.294     matthew  10304:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10305:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10306:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10307:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10308:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10309:     }
1.556     albertel 10310:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10311:     my $user = "$uname:$udom";
                   10312:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10313:     my $reply=cput('classlist',
1.1148    raeburn  10314: 		   {$user => 
1.1314    raeburn  10315: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10316: 		   $cdom,$cnum);
1.1148    raeburn  10317:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10318:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10319:     } else { 
1.81      www      10320: 	return 'error: '.$reply;
                   10321:     }
1.297     matthew  10322:     # Add student role to user
1.83      www      10323:     my $uurl='/'.$cid;
1.81      www      10324:     $uurl=~s/\_/\//g;
                   10325:     if ($usec) {
                   10326: 	$uurl.='/'.$usec;
                   10327:     }
1.1148    raeburn  10328:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10329:                              $selfenroll,$context);
                   10330:     if ($result ne 'ok') {
                   10331:         if ($old_entry{$user} ne '') {
                   10332:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10333:         } else {
                   10334:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10335:         }
                   10336:     }
                   10337:     return $result; 
1.21      www      10338: }
                   10339: 
1.556     albertel 10340: sub format_name {
                   10341:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10342:     my $name;
                   10343:     if ($first ne 'lastname') {
                   10344: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10345:     } else {
                   10346: 	if ($lastname=~/\S/) {
                   10347: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10348: 	    $name=~s/\s+,/,/;
                   10349: 	} else {
                   10350: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10351: 	}
                   10352:     }
                   10353:     $name=~s/^\s+//;
                   10354:     $name=~s/\s+$//;
                   10355:     $name=~s/\s+/ /g;
                   10356:     return $name;
                   10357: }
                   10358: 
1.84      www      10359: # ------------------------------------------------- Write to course preferences
                   10360: 
                   10361: sub writecoursepref {
                   10362:     my ($courseid,%prefs)=@_;
                   10363:     $courseid=~s/^\///;
                   10364:     $courseid=~s/\_/\//g;
                   10365:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10366:     my $chome=homeserver($cnum,$cdomain);
                   10367:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10368: 	return 'error: no such course';
                   10369:     }
                   10370:     my $cstring='';
1.800     albertel 10371:     foreach my $pref (keys(%prefs)) {
                   10372: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10373:     }
1.84      www      10374:     $cstring=~s/\&$//;
                   10375:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10376: }
                   10377: 
                   10378: # ---------------------------------------------------------- Make/modify course
                   10379: 
                   10380: sub createcourse {
1.741     raeburn  10381:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10382:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10383:     $url=&declutter($url);
                   10384:     my $cid='';
1.1028    raeburn  10385:     if ($context eq 'requestcourses') {
                   10386:         my $can_create = 0;
                   10387:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10388:         if ($udom eq $ownerdom) {
                   10389:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10390:                                   $context)) {
                   10391:                 $can_create = 1;
                   10392:             }
                   10393:         } else {
                   10394:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10395:                                            $category);
                   10396:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10397:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10398:                 if (@curr > 0) {
                   10399:                     my @options = qw(approval validate autolimit);
                   10400:                     my $optregex = join('|',@options);
                   10401:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10402:                         $can_create = 1;
                   10403:                     }
                   10404:                 }
                   10405:             }
                   10406:         }
                   10407:         if ($can_create) {
                   10408:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10409:                 unless (&allowed('ccc',$udom)) {
                   10410:                     return 'refused'; 
                   10411:                 }
1.1017    raeburn  10412:             }
                   10413:         } else {
                   10414:             return 'refused';
                   10415:         }
1.1028    raeburn  10416:     } elsif (!&allowed('ccc',$udom)) {
                   10417:         return 'refused';
1.84      www      10418:     }
1.1011    raeburn  10419: # --------------------------------------------------------------- Get Unique ID
                   10420:     my $uname;
                   10421:     if ($cnum =~ /^$match_courseid$/) {
                   10422:         my $chome=&homeserver($cnum,$udom,'true');
                   10423:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10424:             $uname = $cnum;
                   10425:         } else {
1.1038    raeburn  10426:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10427:         }
                   10428:     } else {
1.1038    raeburn  10429:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10430:     }
                   10431:     return $uname if ($uname =~ /^error/);
                   10432: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10433:     if (!defined($course_server)) {
                   10434:         if (defined(&domain($udom,'primary'))) {
                   10435:             $course_server = &domain($udom,'primary');
                   10436:         } else {
                   10437:             $course_server = $env{'user.home'}; 
                   10438:         }
                   10439:     }
                   10440:     my %host_servers =
                   10441:         &Apache::lonnet::get_servers($udom,'library');
                   10442:     unless ($host_servers{$course_server}) {
                   10443:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10444:     }
1.84      www      10445: # ------------------------------------------------------------- Make the course
                   10446:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10447:                       $course_server);
1.84      www      10448:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10449:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10450:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10451: 	return 'error: no such course';
                   10452:     }
1.271     www      10453: # ----------------------------------------------------------------- Course made
1.516     raeburn  10454: # log existence
1.1029    raeburn  10455:     my $now = time;
1.918     raeburn  10456:     my $newcourse = {
                   10457:                     $udom.'_'.$uname => {
1.921     raeburn  10458:                                      description => $description,
                   10459:                                      inst_code   => $inst_code,
                   10460:                                      owner       => $course_owner,
                   10461:                                      type        => $crstype,
1.1029    raeburn  10462:                                      creator     => $env{'user.name'}.':'.
                   10463:                                                     $env{'user.domain'},
                   10464:                                      created     => $now,
                   10465:                                      context     => $context,
1.918     raeburn  10466:                                                 },
                   10467:                     };
1.921     raeburn  10468:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10469: # set toplevel url
1.271     www      10470:     my $topurl=$url;
                   10471:     unless ($nonstandard) {
                   10472: # ------------------------------------------ For standard courses, make top url
                   10473:         my $mapurl=&clutter($url);
1.278     www      10474:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10475:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10476: <map>
                   10477: <resource id="1" type="start"></resource>
                   10478: <resource id="2" src="$mapurl"></resource>
                   10479: <resource id="3" type="finish"></resource>
                   10480: <link index="1" from="1" to="2"></link>
                   10481: <link index="2" from="2" to="3"></link>
                   10482: </map>
                   10483: ENDINITMAP
                   10484:         $topurl=&declutter(
1.638     albertel 10485:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10486:                           );
                   10487:     }
                   10488: # ----------------------------------------------------------- Write preferences
1.84      www      10489:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10490:                      ('description'              => $description,
                   10491:                       'url'                      => $topurl,
                   10492:                       'internal.creator'         => $env{'user.name'}.':'.
                   10493:                                                     $env{'user.domain'},
                   10494:                       'internal.created'         => $now,
                   10495:                       'internal.creationcontext' => $context)
                   10496:                     );
1.84      www      10497:     return '/'.$udom.'/'.$uname;
                   10498: }
                   10499: 
1.1011    raeburn  10500: # ------------------------------------------------------------------- Create ID
                   10501: sub generate_coursenum {
1.1038    raeburn  10502:     my ($udom,$crstype) = @_;
1.1011    raeburn  10503:     my $domdesc = &domain($udom);
                   10504:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10505:     my $first;
                   10506:     if ($crstype eq 'Community') {
                   10507:         $first = '0';
                   10508:     } else {
                   10509:         $first = int(1+rand(9)); 
                   10510:     } 
                   10511:     my $uname=$first.
1.1011    raeburn  10512:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10513:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10514:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10515: # ----------------------------------------------- Make sure that does not exist
                   10516:     my $uhome=&homeserver($uname,$udom,'true');
                   10517:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10518:         if ($crstype eq 'Community') {
                   10519:             $first = '0';
                   10520:         } else {
                   10521:             $first = int(1+rand(9));
                   10522:         }
                   10523:         $uname=$first.
1.1011    raeburn  10524:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10525:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10526:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10527:         $uhome=&homeserver($uname,$udom,'true');
                   10528:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10529:             return 'error: unable to generate unique course-ID';
                   10530:         }
                   10531:     }
                   10532:     return $uname;
                   10533: }
                   10534: 
1.813     albertel 10535: sub is_course {
1.1167    droeschl 10536:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10537:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   10538: 
1.1381    raeburn  10539:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10540:     my $uhome=&homeserver($cnum,$cdom);
                   10541:     my $iscourse;
                   10542:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  10543:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  10544:     } else {
                   10545:         my $hashid = $cdom.':'.$cnum;
                   10546:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10547:         unless (defined($cached)) {
                   10548:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10549:                                         $cnum,undef,undef,'.');
                   10550:             $iscourse = 0;
                   10551:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10552:                 $iscourse = 1;
                   10553:             }
                   10554:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10555:         }
                   10556:     }
                   10557:     return unless ($iscourse);
1.1167    droeschl 10558:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10559: }
                   10560: 
1.1015    raeburn  10561: sub store_userdata {
                   10562:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10563:     my $result;
1.1016    raeburn  10564:     if ($datakey ne '') {
1.1013    raeburn  10565:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10566:             if ($udom eq '' || $uname eq '') {
                   10567:                 $udom = $env{'user.domain'};
                   10568:                 $uname = $env{'user.name'};
                   10569:             }
                   10570:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10571:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10572:                 $result = 'error: no_host';
                   10573:             } else {
                   10574:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10575:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10576: 
                   10577:                 my $namevalue='';
                   10578:                 foreach my $key (keys(%{$storehash})) {
                   10579:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10580:                 }
                   10581:                 $namevalue=~s/\&$//;
1.1224    raeburn  10582:                 unless ($namespace eq 'courserequests') {
                   10583:                     $datakey = &escape($datakey);
                   10584:                 }
1.1105    raeburn  10585:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10586:                                   $namevalue,$uhome);
1.1013    raeburn  10587:             }
                   10588:         } else {
                   10589:             $result = 'error: data to store was not a hash reference'; 
                   10590:         }
                   10591:     } else {
                   10592:         $result= 'error: invalid requestkey'; 
                   10593:     }
                   10594:     return $result;
                   10595: }
                   10596: 
1.21      www      10597: # ---------------------------------------------------------- Assign Custom Role
                   10598: 
                   10599: sub assigncustomrole {
1.957     raeburn  10600:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10601:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10602:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10603: }
                   10604: 
                   10605: # ----------------------------------------------------------------- Revoke Role
                   10606: 
                   10607: sub revokerole {
1.957     raeburn  10608:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10609:     my $now=time;
1.965     raeburn  10610:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10611: }
                   10612: 
                   10613: # ---------------------------------------------------------- Revoke Custom Role
                   10614: 
                   10615: sub revokecustomrole {
1.957     raeburn  10616:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10617:     my $now=time;
1.357     www      10618:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10619:            $deleteflag,$selfenroll,$context);
1.17      www      10620: }
                   10621: 
1.533     banghart 10622: # ------------------------------------------------------------ Disk usage
1.535     albertel 10623: sub diskusage {
1.955     raeburn  10624:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10625:     $directorypath =~ s/\/$//;
                   10626:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10627:                        .&escape($getpropath).':'.&escape($uname).':'
                   10628:                        .&escape($udom),homeserver($uname,$udom));
                   10629:     if ($listing eq 'unknown_cmd') {
                   10630:         if ($getpropath) {
                   10631:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10632:         }
                   10633:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10634:     }
1.514     albertel 10635:     return $listing;
1.512     banghart 10636: }
                   10637: 
1.566     banghart 10638: sub is_locked {
1.1096    raeburn  10639:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10640:     my @check;
                   10641:     my $is_locked;
1.1093    raeburn  10642:     push (@check,$file_name);
1.613     albertel 10643:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10644: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10645:     my ($tmp)=keys(%locked);
                   10646:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10647:     
1.566     banghart 10648:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10649:         $is_locked = 'false';
                   10650:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10651:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10652:                $is_locked = 'true';
1.1096    raeburn  10653:                if (ref($which) eq 'ARRAY') {
                   10654:                    push(@{$which},$entry);
                   10655:                } else {
                   10656:                    last;
                   10657:                }
1.745     raeburn  10658:            }
                   10659:        }
1.566     banghart 10660:     } else {
                   10661:         $is_locked = 'false';
                   10662:     }
1.1093    raeburn  10663:     return $is_locked;
1.566     banghart 10664: }
                   10665: 
1.759     albertel 10666: sub declutter_portfile {
                   10667:     my ($file) = @_;
1.833     albertel 10668:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10669:     return $file;
                   10670: }
                   10671: 
1.559     banghart 10672: # ------------------------------------------------------------- Mark as Read Only
                   10673: 
                   10674: sub mark_as_readonly {
                   10675:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10676:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10677:     my ($tmp)=keys(%current_permissions);
                   10678:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10679:     foreach my $file (@{$files}) {
1.759     albertel 10680: 	$file = &declutter_portfile($file);
1.561     banghart 10681:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10682:     }
1.613     albertel 10683:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10684:     return;
                   10685: }
                   10686: 
1.572     banghart 10687: # ------------------------------------------------------------Save Selected Files
                   10688: 
                   10689: sub save_selected_files {
                   10690:     my ($user, $path, @files) = @_;
                   10691:     my $filename = $user."savedfiles";
1.573     banghart 10692:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  10693:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10694:     foreach my $file (@files) {
1.620     albertel 10695:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10696:     }
                   10697:     foreach my $file (@other_files) {
1.574     banghart 10698:         print (OUT $file."\n");
1.572     banghart 10699:     }
1.574     banghart 10700:     close (OUT);
1.572     banghart 10701:     return 'ok';
                   10702: }
                   10703: 
1.574     banghart 10704: sub clear_selected_files {
                   10705:     my ($user) = @_;
                   10706:     my $filename = $user."savedfiles";
1.1359    raeburn  10707:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10708:     print (OUT undef);
                   10709:     close (OUT);
                   10710:     return ("ok");    
                   10711: }
                   10712: 
1.572     banghart 10713: sub files_in_path {
                   10714:     my ($user, $path) = @_;
                   10715:     my $filename = $user."savedfiles";
                   10716:     my %return_files;
1.1359    raeburn  10717:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10718:     while (my $line_in = <IN>) {
1.574     banghart 10719:         chomp ($line_in);
                   10720:         my @paths_and_file = split (m!/!, $line_in);
                   10721:         my $file_part = pop (@paths_and_file);
                   10722:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10723:         $path_part.='/';
                   10724:         my $path_and_file = $path_part.$file_part;
                   10725:         if ($path_part eq $path) {
                   10726:             $return_files{$file_part}= 'selected';
                   10727:         }
                   10728:     }
1.574     banghart 10729:     close (IN);
                   10730:     return (\%return_files);
1.572     banghart 10731: }
                   10732: 
                   10733: # called in portfolio select mode, to show files selected NOT in current directory
                   10734: sub files_not_in_path {
                   10735:     my ($user, $path) = @_;
                   10736:     my $filename = $user."savedfiles";
                   10737:     my @return_files;
                   10738:     my $path_part;
1.1359    raeburn  10739:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10740:     while (my $line = <IN>) {
1.572     banghart 10741:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10742:         my @paths_and_file = split(m|/|, $line);
                   10743:         my $file_part = pop(@paths_and_file);
                   10744:         chomp($file_part);
                   10745:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10746:         $path_part .= '/';
                   10747:         my $path_and_file = $path_part.$file_part;
                   10748:         if ($path_part ne $path) {
1.800     albertel 10749:             push(@return_files, ($path_and_file));
1.572     banghart 10750:         }
                   10751:     }
1.800     albertel 10752:     close(OUT);
1.574     banghart 10753:     return (@return_files);
1.572     banghart 10754: }
                   10755: 
1.1273    raeburn  10756: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   10757:  
                   10758: sub portfiles_versioning {
                   10759:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   10760:     my $portfolio_root = '/userfiles/portfolio';
                   10761:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   10762:     foreach my $file (@{$portfiles}) {
                   10763:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   10764:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   10765:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   10766:         my $getpropath = 1;
                   10767:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   10768:                                              $stu_name,$getpropath);
                   10769:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   10770:         my $new_answer = 
                   10771:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   10772:         if ($new_answer ne 'problem getting file') {
                   10773:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   10774:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   10775:                               [$symb,$env{'request.course.id'},'graded']);
                   10776:         }
                   10777:     }
                   10778: }
                   10779: 
                   10780: sub get_next_version {
                   10781:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   10782:     my $version;
                   10783:     if (ref($dir_list) eq 'ARRAY') {
                   10784:         foreach my $row (@{$dir_list}) {
                   10785:             my ($file) = split(/\&/,$row,2);
                   10786:             my ($file_name,$file_version,$file_ext) =
                   10787:                 &file_name_version_ext($file);
                   10788:             if (($file_name eq $answer_name) &&
                   10789:                 ($file_ext eq $answer_ext)) {
                   10790:                      # gets here if filename and extension match,
                   10791:                      # regardless of version
                   10792:                 if ($file_version ne '') {
                   10793:                     # a versioned file is found  so save it for later
                   10794:                     if ($file_version > $version) {
                   10795:                         $version = $file_version;
                   10796:                     }
                   10797:                 }
                   10798:             }
                   10799:         }
                   10800:     }
                   10801:     $version ++;
                   10802:     return($version);
                   10803: }
                   10804: 
                   10805: sub version_selected_portfile {
                   10806:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   10807:     my ($answer_name,$answer_ver,$answer_ext) =
                   10808:         &file_name_version_ext($file_name);
                   10809:     my $new_answer;
                   10810:     $env{'form.copy'} =
                   10811:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   10812:     if($env{'form.copy'} eq '-1') {
                   10813:         $new_answer = 'problem getting file';
                   10814:     } else {
                   10815:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   10816:         my $copy_result = 
                   10817:             &finishuserfileupload($stu_name,$domain,'copy',
                   10818:                                   '/portfolio'.$directory.$new_answer);
                   10819:     }
                   10820:     undef($env{'form.copy'});
                   10821:     return ($new_answer);
                   10822: }
                   10823: 
                   10824: sub file_name_version_ext {
                   10825:     my ($file)=@_;
                   10826:     my @file_parts = split(/\./, $file);
                   10827:     my ($name,$version,$ext);
                   10828:     if (@file_parts > 1) {
                   10829:         $ext=pop(@file_parts);
                   10830:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   10831:             $version=pop(@file_parts);
                   10832:         }
                   10833:         $name=join('.',@file_parts);
                   10834:     } else {
                   10835:         $name=join('.',@file_parts);
                   10836:     }
                   10837:     return($name,$version,$ext);
                   10838: }
                   10839: 
1.745     raeburn  10840: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10841: 
1.745     raeburn  10842: sub get_portfile_permissions {
                   10843:     my ($domain,$user) = @_;
1.613     albertel 10844:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10845:     my ($tmp)=keys(%current_permissions);
                   10846:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10847:     return \%current_permissions;
                   10848: }
                   10849: 
                   10850: #---------------------------------------------Get portfolio file access controls
                   10851: 
1.749     raeburn  10852: sub get_access_controls {
1.745     raeburn  10853:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10854:     my %access;
                   10855:     my $real_file = $file;
                   10856:     $file =~ s/\.meta$//;
1.745     raeburn  10857:     if (defined($file)) {
1.749     raeburn  10858:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10859:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10860:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10861:             }
                   10862:         }
1.745     raeburn  10863:     } else {
1.749     raeburn  10864:         foreach my $key (keys(%{$current_permissions})) {
                   10865:             if ($key =~ /\0accesscontrol$/) {
                   10866:                 if (defined($group)) {
                   10867:                     if ($key !~ m-^\Q$group\E/-) {
                   10868:                         next;
                   10869:                     }
                   10870:                 }
                   10871:                 my ($fullpath) = split(/\0/,$key);
                   10872:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10873:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10874:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10875:                     }
                   10876:                 }
                   10877:             }
                   10878:         }
                   10879:     }
                   10880:     return %access;
                   10881: }
                   10882: 
                   10883: sub modify_access_controls {
                   10884:     my ($file_name,$changes,$domain,$user)=@_;
                   10885:     my ($outcome,$deloutcome);
                   10886:     my %store_permissions;
                   10887:     my %new_values;
                   10888:     my %new_control;
                   10889:     my %translation;
                   10890:     my @deletions = ();
                   10891:     my $now = time;
                   10892:     if (exists($$changes{'activate'})) {
                   10893:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10894:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10895:             my $numnew = scalar(@newitems);
                   10896:             for (my $i=0; $i<$numnew; $i++) {
                   10897:                 my $newkey = $newitems[$i];
                   10898:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10899:                 if ($newkey =~ /^\d+:/) { 
                   10900:                     $newkey =~ s/^(\d+)/$newid/;
                   10901:                     $translation{$1} = $newid;
                   10902:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10903:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10904:                     $translation{$1} = $newid;
                   10905:                 }
1.749     raeburn  10906:                 $new_values{$file_name."\0".$newkey} = 
                   10907:                                           $$changes{'activate'}{$newitems[$i]};
                   10908:                 $new_control{$newkey} = $now;
                   10909:             }
                   10910:         }
                   10911:     }
                   10912:     my %todelete;
                   10913:     my %changed_items;
                   10914:     foreach my $action ('delete','update') {
                   10915:         if (exists($$changes{$action})) {
                   10916:             if (ref($$changes{$action}) eq 'HASH') {
                   10917:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10918:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10919:                     if ($action eq 'delete') { 
                   10920:                         $todelete{$itemnum} = 1;
                   10921:                     } else {
                   10922:                         $changed_items{$itemnum} = $key;
                   10923:                     }
                   10924:                 }
1.745     raeburn  10925:             }
                   10926:         }
1.749     raeburn  10927:     }
                   10928:     # get lock on access controls for file.
                   10929:     my $lockhash = {
                   10930:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10931:                                                        ':'.$env{'user.domain'},
                   10932:                    }; 
                   10933:     my $tries = 0;
                   10934:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10935:    
1.1288    damieng  10936:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10937:         $tries ++;
1.1289    damieng  10938:         sleep(0.1);
1.749     raeburn  10939:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10940:     }
                   10941:     if ($gotlock eq 'ok') {
                   10942:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10943:         my ($tmp)=keys(%curr_permissions);
                   10944:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10945:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10946:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10947:             if (ref($curr_controls) eq 'HASH') {
                   10948:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10949:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10950:                     if (defined($todelete{$itemnum})) {
                   10951:                         push(@deletions,$file_name."\0".$control_item);
                   10952:                     } else {
                   10953:                         if (defined($changed_items{$itemnum})) {
                   10954:                             $new_control{$changed_items{$itemnum}} = $now;
                   10955:                             push(@deletions,$file_name."\0".$control_item);
                   10956:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10957:                         } else {
                   10958:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10959:                         }
                   10960:                     }
1.745     raeburn  10961:                 }
                   10962:             }
                   10963:         }
1.970     raeburn  10964:         my ($group);
                   10965:         if (&is_course($domain,$user)) {
                   10966:             ($group,my $file) = split(/\//,$file_name,2);
                   10967:         }
1.749     raeburn  10968:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10969:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10970:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10971:         #  remove lock
                   10972:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10973:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10974:         my $sqlresult =
1.970     raeburn  10975:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10976:                                     $group);
1.749     raeburn  10977:     } else {
                   10978:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10979:     }
1.749     raeburn  10980:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10981: }
                   10982: 
1.827     raeburn  10983: sub make_public_indefinitely {
1.1271    raeburn  10984:     my (@requrl) = @_;
                   10985:     return &automated_portfile_access('public',\@requrl);
                   10986: }
                   10987: 
                   10988: sub automated_portfile_access {
                   10989:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  10990:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   10991:         return 'invalid';
                   10992:     }
1.1271    raeburn  10993:     my %urls;
                   10994:     if (ref($addsref) eq 'ARRAY') {
                   10995:         foreach my $requrl (@{$addsref}) {
                   10996:             if (&is_portfolio_url($requrl)) {
                   10997:                 unless (exists($urls{$requrl})) {
                   10998:                     $urls{$requrl} = 'add';
                   10999:                 }
                   11000:             }
                   11001:         }
                   11002:     }
                   11003:     if (ref($delsref) eq 'ARRAY') {
                   11004:         foreach my $requrl (@{$delsref}) { 
                   11005:             if (&is_portfolio_url($requrl)) {
                   11006:                 unless (exists($urls{$requrl})) {
                   11007:                     $urls{$requrl} = 'delete'; 
                   11008:                 }
                   11009:             }
                   11010:         }
                   11011:     }
                   11012:     unless (keys(%urls)) {
                   11013:         return 'invalid';
                   11014:     }
                   11015:     my $ip;
                   11016:     if ($accesstype eq 'ip') {
                   11017:         if (ref($info) eq 'HASH') {
                   11018:             if ($info->{'ip'} ne '') {
                   11019:                 $ip = $info->{'ip'};
                   11020:             }
                   11021:         }
                   11022:         if ($ip eq '') {
                   11023:             return 'invalid';
                   11024:         }
                   11025:     }
                   11026:     my $errors;
1.827     raeburn  11027:     my $now = time;
1.1271    raeburn  11028:     my %current_perms;
                   11029:     foreach my $requrl (sort(keys(%urls))) {
                   11030:         my $action;
                   11031:         if ($urls{$requrl} eq 'add') {
                   11032:             $action = 'activate';
                   11033:         } else {
                   11034:             $action = 'none';
                   11035:         }
                   11036:         my $aclnum = 0;
1.827     raeburn  11037:         my (undef,$udom,$unum,$file_name,$group) =
                   11038:             &parse_portfolio_url($requrl);
1.1271    raeburn  11039:         unless (exists($current_perms{$unum.':'.$udom})) {
                   11040:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   11041:         }
                   11042:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  11043:                                                    $group,$file_name);
                   11044:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11045:             my ($num,$scope,$end,$start) = 
                   11046:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  11047:             if ($scope eq $accesstype) {
                   11048:                 if (($start <= $now) && ($end == 0)) {
                   11049:                     if ($accesstype eq 'ip') {
                   11050:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   11051:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   11052:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   11053:                                     if ($urls{$requrl} eq 'add') {
                   11054:                                         $action = 'none';
                   11055:                                         last;
                   11056:                                     } else {
                   11057:                                         $action = 'delete';
                   11058:                                         $aclnum = $num;
                   11059:                                         last;
                   11060:                                     }
                   11061:                                 }
                   11062:                             }
                   11063:                         }
                   11064:                     } elsif ($accesstype eq 'public') {
                   11065:                         if ($urls{$requrl} eq 'add') {
                   11066:                             $action = 'none';
                   11067:                             last;
                   11068:                         } else {
                   11069:                             $action = 'delete';
                   11070:                             $aclnum = $num;
                   11071:                             last;
                   11072:                         }
                   11073:                     }
                   11074:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  11075:                     $action = 'update';
                   11076:                     $aclnum = $num;
1.1271    raeburn  11077:                     last;
1.827     raeburn  11078:                 }
                   11079:             }
                   11080:         }
                   11081:         if ($action eq 'none') {
1.1271    raeburn  11082:             next;
1.827     raeburn  11083:         } else {
                   11084:             my %changes;
                   11085:             my $newend = 0;
                   11086:             my $newstart = $now;
1.1271    raeburn  11087:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  11088:             $changes{$action}{$newkey} = {
1.1271    raeburn  11089:                 type => $accesstype,
1.827     raeburn  11090:                 time => {
                   11091:                     start => $newstart,
                   11092:                     end   => $newend,
                   11093:                 },
                   11094:             };
1.1271    raeburn  11095:             if ($accesstype eq 'ip') {
                   11096:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   11097:             }
1.827     raeburn  11098:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11099:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  11100:             unless ($outcome eq 'ok') {
                   11101:                 $errors .= $outcome.' ';
                   11102:             }
1.827     raeburn  11103:         }
1.1271    raeburn  11104:     }
                   11105:     if ($errors) {
                   11106:         $errors =~ s/\s$//;
                   11107:         return $errors;
1.827     raeburn  11108:     } else {
1.1271    raeburn  11109:         return 'ok';
1.827     raeburn  11110:     }
                   11111: }
                   11112: 
1.745     raeburn  11113: #------------------------------------------------------Get Marked as Read Only
                   11114: 
                   11115: sub get_marked_as_readonly {
                   11116:     my ($domain,$user,$what,$group) = @_;
                   11117:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11118:     my @readonly_files;
1.629     banghart 11119:     my $cmp1=$what;
                   11120:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11121:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11122:         if (defined($group)) {
                   11123:             if ($file_name !~ m-^\Q$group\E/-) {
                   11124:                 next;
                   11125:             }
                   11126:         }
1.561     banghart 11127:         if (ref($value) eq "ARRAY"){
                   11128:             foreach my $stored_what (@{$value}) {
1.629     banghart 11129:                 my $cmp2=$stored_what;
1.759     albertel 11130:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11131:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11132:                 }
1.629     banghart 11133:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11134:                     push(@readonly_files, $file_name);
1.745     raeburn  11135:                     last;
1.563     banghart 11136:                 } elsif (!defined($what)) {
                   11137:                     push(@readonly_files, $file_name);
1.745     raeburn  11138:                     last;
1.561     banghart 11139:                 }
                   11140:             }
1.745     raeburn  11141:         }
1.561     banghart 11142:     }
                   11143:     return @readonly_files;
                   11144: }
1.577     banghart 11145: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11146: 
1.577     banghart 11147: sub get_marked_as_readonly_hash {
1.745     raeburn  11148:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11149:     my %readonly_files;
1.745     raeburn  11150:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11151:         if (defined($group)) {
                   11152:             if ($file_name !~ m-^\Q$group\E/-) {
                   11153:                 next;
                   11154:             }
                   11155:         }
1.577     banghart 11156:         if (ref($value) eq "ARRAY"){
                   11157:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11158:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11159:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11160:                         if ($lock_descriptor eq 'graded') {
                   11161:                             $readonly_files{$file_name} = 'graded';
                   11162:                         } elsif ($lock_descriptor eq 'handback') {
                   11163:                             $readonly_files{$file_name} = 'handback';
                   11164:                         } else {
                   11165:                             if (!exists($readonly_files{$file_name})) {
                   11166:                                 $readonly_files{$file_name} = 'locked';
                   11167:                             }
                   11168:                         }
1.745     raeburn  11169:                     }
1.750     banghart 11170:                 } 
1.577     banghart 11171:             }
                   11172:         } 
                   11173:     }
                   11174:     return %readonly_files;
                   11175: }
1.559     banghart 11176: # ------------------------------------------------------------ Unmark as Read Only
                   11177: 
                   11178: sub unmark_as_readonly {
1.629     banghart 11179:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11180:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11181:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11182:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11183:     my $symb_crs = $what;
                   11184:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11185:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11186:     my ($tmp)=keys(%current_permissions);
                   11187:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11188:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11189:     foreach my $file (@readonly_files) {
1.759     albertel 11190: 	my $clean_file = &declutter_portfile($file);
                   11191: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11192: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11193:         my @new_locks;
                   11194:         my @del_keys;
                   11195:         if (ref($current_locks) eq "ARRAY"){
                   11196:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11197:                 my $compare=$locker;
1.749     raeburn  11198:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11199:                     $compare=join('',@{$locker});
1.746     raeburn  11200:                     if ($compare ne $symb_crs) {
                   11201:                         push(@new_locks, $locker);
                   11202:                     }
1.563     banghart 11203:                 }
                   11204:             }
1.650     albertel 11205:             if (scalar(@new_locks) > 0) {
1.563     banghart 11206:                 $current_permissions{$file} = \@new_locks;
                   11207:             } else {
                   11208:                 push(@del_keys, $file);
1.613     albertel 11209:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11210:                 delete($current_permissions{$file});
1.563     banghart 11211:             }
                   11212:         }
1.561     banghart 11213:     }
1.613     albertel 11214:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11215:     return;
                   11216: }
1.512     banghart 11217: 
1.17      www      11218: # ------------------------------------------------------------ Directory lister
                   11219: 
                   11220: sub dirlist {
1.955     raeburn  11221:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11222:     $uri=~s/^\///;
                   11223:     $uri=~s/\/$//;
1.253     stredwic 11224:     my ($udom, $uname);
1.955     raeburn  11225:     if ($getuserdir) {
1.253     stredwic 11226:         $udom = $userdomain;
                   11227:         $uname = $username;
1.955     raeburn  11228:     } else {
                   11229:         (undef,$udom,$uname)=split(/\//,$uri);
                   11230:         if(defined($userdomain)) {
                   11231:             $udom = $userdomain;
                   11232:         }
                   11233:         if(defined($username)) {
                   11234:             $uname = $username;
                   11235:         }
1.253     stredwic 11236:     }
1.955     raeburn  11237:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11238: 
1.955     raeburn  11239:     $dirRoot = $perlvar{'lonDocRoot'};
                   11240:     if (defined($getpropath)) {
                   11241:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11242:         $dirRoot =~ s/\/$//;
1.955     raeburn  11243:     } elsif (defined($getuserdir)) {
                   11244:         my $subdir=$uname.'__';
                   11245:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11246:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11247:                    ."/$udom/$subdir/$uname";
                   11248:     } elsif (defined($alternateRoot)) {
                   11249:         $dirRoot = $alternateRoot;
1.751     banghart 11250:     }
1.253     stredwic 11251: 
                   11252:     if($udom) {
                   11253:         if($uname) {
1.1135    raeburn  11254:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11255:             if ($uhome eq 'no_host') {
                   11256:                 return ([],'no_host');
                   11257:             }
1.955     raeburn  11258:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11259:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11260:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11261:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11262:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11263:             } else {
                   11264:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11265:             }
1.605     matthew  11266:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11267:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11268:                 @listing_results = split(/:/,$listing);
                   11269:             } else {
                   11270:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11271:             }
1.1135    raeburn  11272:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11273:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11274:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11275:                 return ([],$listing);
                   11276:             } else {
                   11277:                 return (\@listing_results);
1.1135    raeburn  11278:             }
1.955     raeburn  11279:         } elsif(!$alternateRoot) {
1.1136    raeburn  11280:             my (%allusers,%listerror);
1.841     albertel 11281: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11282:  	    foreach my $tryserver (keys(%servers)) {
                   11283:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11284:                                   &escape($udom),$tryserver);
                   11285:                 if ($listing eq 'unknown_cmd') {
                   11286: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11287: 				      $udom, $tryserver);
                   11288:                 } else {
                   11289:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11290:                 }
1.841     albertel 11291: 		if ($listing eq 'unknown_cmd') {
                   11292: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11293: 				      $udom, $tryserver);
                   11294: 		    @listing_results = split(/:/,$listing);
                   11295: 		} else {
                   11296: 		    @listing_results =
                   11297: 			map { &unescape($_); } split(/:/,$listing);
                   11298: 		}
1.1136    raeburn  11299:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11300:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11301:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11302:                     $listerror{$tryserver} = $listing;
                   11303:                 } else {
1.841     albertel 11304: 		    foreach my $line (@listing_results) {
                   11305: 			my ($entry) = split(/&/,$line,2);
                   11306: 			$allusers{$entry} = 1;
                   11307: 		    }
                   11308: 		}
1.253     stredwic 11309:             }
1.1136    raeburn  11310:             my @alluserslist=();
1.800     albertel 11311:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11312:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11313:             }
1.1318    droeschl 11314: 
                   11315:             if (!%listerror) {
                   11316:                 # no errors
                   11317:                 return (\@alluserslist);
                   11318:             } elsif (scalar(keys(%servers)) == 1) {
                   11319:                 # one library server, one error 
                   11320:                 my ($key) = keys(%listerror);
                   11321:                 return (\@alluserslist, $listerror{$key});
                   11322:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11323:                 # con_lost indicates that we might miss data from at least one
                   11324:                 # library server
                   11325:                 return (\@alluserslist, 'con_lost');
                   11326:             } else {
                   11327:                 # multiple library servers and no con_lost -> data should be
                   11328:                 # complete. 
                   11329:                 return (\@alluserslist);
                   11330:             }
                   11331: 
1.253     stredwic 11332:         } else {
1.1136    raeburn  11333:             return ([],'missing username');
1.253     stredwic 11334:         }
1.955     raeburn  11335:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11336:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11337:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11338:         return (\@all_domains);
1.955     raeburn  11339:     } else {
1.1136    raeburn  11340:         return ([],'missing domain');
1.275     stredwic 11341:     }
                   11342: }
                   11343: 
                   11344: # --------------------------------------------- GetFileTimestamp
                   11345: # This function utilizes dirlist and returns the date stamp for
                   11346: # when it was last modified.  It will also return an error of -1
                   11347: # if an error occurs
                   11348: 
                   11349: sub GetFileTimestamp {
1.955     raeburn  11350:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11351:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11352:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11353:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11354:                                     undef,$getuserdir);
                   11355:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11356:         return -1;
                   11357:     }
                   11358:     if (ref($fileref) eq 'ARRAY') {
                   11359:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11360:         # @stats contains first the filename, then the stat output
                   11361:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11362:     } else {
                   11363:         return -1;
1.253     stredwic 11364:     }
1.26      www      11365: }
                   11366: 
1.712     albertel 11367: sub stat_file {
                   11368:     my ($uri) = @_;
1.787     albertel 11369:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11370: 
1.955     raeburn  11371:     my ($udom,$uname,$file);
1.712     albertel 11372:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11373: 	($udom,$uname,$file) =
1.811     albertel 11374: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11375: 	$file = 'userfiles/'.$file;
                   11376:     }
                   11377:     if ($uri =~ m-^/res/-) {
                   11378: 	($udom,$uname) = 
1.807     albertel 11379: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11380: 	$file = $uri;
                   11381:     }
                   11382: 
                   11383:     if (!$udom || !$uname || !$file) {
                   11384: 	# unable to handle the uri
                   11385: 	return ();
                   11386:     }
1.956     raeburn  11387:     my $getpropath;
                   11388:     if ($file =~ /^userfiles\//) {
                   11389:         $getpropath = 1;
                   11390:     }
1.1136    raeburn  11391:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11392:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11393:         return ();
                   11394:     } else {
                   11395:         if (ref($listref) eq 'ARRAY') {
                   11396:             my @stats = split('&',$listref->[0]);
                   11397: 	    shift(@stats); #filename is first
                   11398: 	    return @stats;
                   11399:         }
1.712     albertel 11400:     }
                   11401:     return ();
                   11402: }
                   11403: 
1.1313    raeburn  11404: # --------------------------------------------------------- recursedirs
                   11405: # Recursive function to traverse either a specific user's Authoring Space
                   11406: # or corresponding Published Resource Space, and populate the hash ref:
                   11407: # $dirhashref with URLs of all directories, and if $filehashref hash
                   11408: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   11409: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   11410: # files in Authoring Space.
                   11411: #
                   11412: # Inputs:
                   11413: #
                   11414: # $is_home - true if current server is home server for user's space
                   11415: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   11416: # $docroot - Document root (i.e., /home/httpd/html
                   11417: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   11418: # $relpath - Current path (relative to top level).
                   11419: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   11420: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   11421: #
                   11422: # Returns: nothing
                   11423: #
                   11424: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   11425: #
                   11426: # Currently used by interface/londocs.pm to create linked select boxes for
                   11427: # directory and filename to import a Course "Author" resource into a course, and
                   11428: # also to create linked select boxes for Authoring Space and Directory to choose
                   11429: # save location for creation of a new "standard" problem from the Course Editor.
                   11430: #
                   11431: 
                   11432: sub recursedirs {
                   11433:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   11434:     return unless (ref($dirhashref) eq 'HASH');
                   11435:     my $currpath = $docroot.$toppath;
                   11436:     if ($relpath) {
                   11437:         $currpath .= "/$relpath";
                   11438:     }
                   11439:     my $savefile;
                   11440:     if (ref($filehashref)) {
                   11441:         $savefile = 1;
                   11442:     }
                   11443:     if ($is_home) {
                   11444:         if (opendir(my $dirh,$currpath)) {
                   11445:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   11446:                 next if ($item eq '');
                   11447:                 if (-d "$currpath/$item") {
                   11448:                     my $newpath;
                   11449:                     if ($relpath) {
                   11450:                         $newpath = "$relpath/$item";
                   11451:                     } else {
                   11452:                         $newpath = $item;
                   11453:                     }
                   11454:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11455:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11456:                 } elsif ($savefile) {
                   11457:                     if ($context eq 'priv') {
                   11458:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11459:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11460:                         }
                   11461:                     } else {
                   11462:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   11463:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11464:                         }
                   11465:                     }
                   11466:                 }
                   11467:             }
                   11468:             closedir($dirh);
                   11469:         }
                   11470:     } else {
                   11471:         my ($dirlistref,$listerror) =
                   11472:             &dirlist($toppath.$relpath);
                   11473:         my @dir_lines;
                   11474:         my $dirptr=16384;
                   11475:         if (ref($dirlistref) eq 'ARRAY') {
                   11476:             foreach my $dir_line (sort
                   11477:                               {
                   11478:                                   my ($afile)=split('&',$a,2);
                   11479:                                   my ($bfile)=split('&',$b,2);
                   11480:                                   return (lc($afile) cmp lc($bfile));
                   11481:                               } (@{$dirlistref})) {
                   11482:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   11483:                     split(/\&/,$dir_line,16);
                   11484:                 $item =~ s/\s+$//;
                   11485:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   11486:                 if ($dirptr&$testdir) {
                   11487:                     my $newpath;
                   11488:                     if ($relpath) {
                   11489:                         $newpath = "$relpath/$item";
                   11490:                     } else {
                   11491:                         $relpath = '/';
                   11492:                         $newpath = $item;
                   11493:                     }
                   11494:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11495:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11496:                 } elsif ($savefile) {
                   11497:                     if ($context eq 'priv') {
                   11498:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11499:                             $filehashref->{$relpath}{$item} = 1;
                   11500:                         }
                   11501:                     } else {
                   11502:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   11503:                             $filehashref->{$relpath}{$item} = 1;
                   11504:                         }
                   11505:                     }
                   11506:                 }
                   11507:             }
                   11508:         }
                   11509:     }
                   11510:     return;
                   11511: }
                   11512: 
1.26      www      11513: # -------------------------------------------------------- Value of a Condition
                   11514: 
1.713     albertel 11515: # gets the value of a specific preevaluated condition
                   11516: #    stored in the string  $env{user.state.<cid>}
                   11517: # or looks up a condition reference in the bighash and if if hasn't
                   11518: # already been evaluated recurses into docondval to get the value of
                   11519: # the condition, then memoizing it to 
                   11520: #   $env{user.state.<cid>.<condition>}
1.40      www      11521: sub directcondval {
                   11522:     my $number=shift;
1.620     albertel 11523:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11524: 	&Apache::lonuserstate::evalstate();
                   11525:     }
1.713     albertel 11526:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11527: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11528:     } elsif ($number =~ /^_/) {
                   11529: 	my $sub_condition;
                   11530: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11531: 		&GDBM_READER(),0640)) {
                   11532: 	    $sub_condition=$bighash{'conditions'.$number};
                   11533: 	    untie(%bighash);
                   11534: 	}
                   11535: 	my $value = &docondval($sub_condition);
1.949     raeburn  11536: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11537: 	return $value;
                   11538:     }
1.620     albertel 11539:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11540:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11541:     } else {
                   11542:        return 2;
                   11543:     }
                   11544: }
                   11545: 
1.713     albertel 11546: # get the collection of conditions for this resource
1.26      www      11547: sub condval {
                   11548:     my $condidx=shift;
1.54      www      11549:     my $allpathcond='';
1.713     albertel 11550:     foreach my $cond (split(/\|/,$condidx)) {
                   11551: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11552: 	    $allpathcond.=
                   11553: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11554: 	}
1.191     harris41 11555:     }
1.54      www      11556:     $allpathcond=~s/\|$//;
1.713     albertel 11557:     return &docondval($allpathcond);
                   11558: }
                   11559: 
                   11560: #evaluates an expression of conditions
                   11561: sub docondval {
                   11562:     my ($allpathcond) = @_;
                   11563:     my $result=0;
                   11564:     if ($env{'request.course.id'}
                   11565: 	&& defined($allpathcond)) {
                   11566: 	my $operand='|';
                   11567: 	my @stack;
                   11568: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11569: 	    if ($chunk eq '(') {
                   11570: 		push @stack,($operand,$result);
                   11571: 	    } elsif ($chunk eq ')') {
                   11572: 		my $before=pop @stack;
                   11573: 		if (pop @stack eq '&') {
                   11574: 		    $result=$result>$before?$before:$result;
                   11575: 		} else {
                   11576: 		    $result=$result>$before?$result:$before;
                   11577: 		}
                   11578: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11579: 		$operand=$chunk;
                   11580: 	    } else {
                   11581: 		my $new=directcondval($chunk);
                   11582: 		if ($operand eq '&') {
                   11583: 		    $result=$result>$new?$new:$result;
                   11584: 		} else {
                   11585: 		    $result=$result>$new?$result:$new;
                   11586: 		}
                   11587: 	    }
                   11588: 	}
1.26      www      11589:     }
                   11590:     return $result;
1.421     albertel 11591: }
                   11592: 
                   11593: # ---------------------------------------------------- Devalidate courseresdata
                   11594: 
                   11595: sub devalidatecourseresdata {
                   11596:     my ($coursenum,$coursedomain)=@_;
                   11597:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11598:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11599: }
                   11600: 
1.763     www      11601: 
1.200     www      11602: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11603: #
                   11604: #  Parameters:
                   11605: #      $coursenum    - Number of the course.
                   11606: #      $coursedomain - Domain at which the course was created.
                   11607: #  Returns:
                   11608: #     A hash of the course parameters along (I think) with timestamps
                   11609: #     and version info.
1.877     foxr     11610: 
1.624     albertel 11611: sub get_courseresdata {
                   11612:     my ($coursenum,$coursedomain)=@_;
1.200     www      11613:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11614:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11615:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11616:     my %dumpreply;
1.417     albertel 11617:     unless (defined($cached)) {
1.624     albertel 11618: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11619: 	$result=\%dumpreply;
1.251     albertel 11620: 	my ($tmp) = keys(%dumpreply);
                   11621: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11622: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11623: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11624: 	    return $tmp;
1.416     albertel 11625: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11626: 	    $result=undef;
1.599     albertel 11627: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11628: 	}
                   11629:     }
1.624     albertel 11630:     return $result;
                   11631: }
                   11632: 
1.633     albertel 11633: sub devalidateuserresdata {
                   11634:     my ($uname,$udom)=@_;
                   11635:     my $hashid="$udom:$uname";
                   11636:     &devalidate_cache_new('userres',$hashid);
                   11637: }
                   11638: 
1.624     albertel 11639: sub get_userresdata {
                   11640:     my ($uname,$udom)=@_;
                   11641:     #most student don\'t have any data set, check if there is some data
                   11642:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11643: 
                   11644:     my $hashid="$udom:$uname";
                   11645:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11646:     if (!defined($cached)) {
                   11647: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11648: 	$result=\%resourcedata;
                   11649: 	&do_cache_new('userres',$hashid,$result,600);
                   11650:     }
                   11651:     my ($tmp)=keys(%$result);
                   11652:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11653: 	return $result;
                   11654:     }
                   11655:     #error 2 occurs when the .db doesn't exist
                   11656:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  11657:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11658: 	    &logthis("<font color=\"blue\">WARNING:".
                   11659: 		     " Trying to get resource data for ".
                   11660: 		     $uname." at ".$udom.": ".
                   11661: 		     $tmp."</font>");
                   11662:         }
1.624     albertel 11663:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11664: 	#&EXT_cache_set($udom,$uname);
                   11665: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11666: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11667:     }
                   11668:     return $tmp;
                   11669: }
1.879     foxr     11670: #----------------------------------------------- resdata - return resource data
                   11671: #  Purpose:
                   11672: #    Return resource data for either users or for a course.
                   11673: #  Parameters:
                   11674: #     $name      - Course/user name.
                   11675: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  11676: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  11677: #     $mapp      - decluttered URL of enclosing map  
                   11678: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   11679: #     $recurseup - Ref to array of map URLs, starting with map containing
                   11680: #                  $mapp up through hierarchy of nested maps to top level map.  
                   11681: #     $courseid  - CourseID (first part of param identifier).
                   11682: #     $modifier  - Middle part of param identifier.
                   11683: #     $what      - Last part of param identifier.
1.879     foxr     11684: #     @which     - Array of names of resources desired.
                   11685: #  Returns:
                   11686: #     The value of the first reasource in @which that is found in the
                   11687: #     resource hash.
                   11688: #  Exceptional Conditions:
                   11689: #     If the $type passed in is not valid (not the string 'course' or 
                   11690: #     'user', an undefined  reference is returned.
                   11691: #     If none of the resources are found, an undef is returned
1.624     albertel 11692: sub resdata {
1.1301    raeburn  11693:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   11694:         $modifier,$what,@which)=@_;
1.624     albertel 11695:     my $result;
                   11696:     if ($type eq 'course') {
                   11697: 	$result=&get_courseresdata($name,$domain);
                   11698:     } elsif ($type eq 'user') {
                   11699: 	$result=&get_userresdata($name,$domain);
                   11700:     }
                   11701:     if (!ref($result)) { return $result; }    
1.251     albertel 11702:     foreach my $item (@which) {
1.1301    raeburn  11703:         if ($item->[1] eq 'course') {
                   11704:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   11705:                 unless ($$recursed) {
1.1302    raeburn  11706:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  11707:                     $$recursed = 1;
                   11708:                 }
                   11709:                 foreach my $item (@${recurseup}) {
                   11710:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   11711:                     last if (defined($result->{$norecursechk}));
                   11712:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   11713:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   11714:                 }
                   11715:             }
                   11716:         }
                   11717:         if (defined($result->{$item->[0]})) {
1.927     albertel 11718: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11719: 	}
1.250     albertel 11720:     }
1.291     albertel 11721:     return undef;
1.200     www      11722: }
                   11723: 
1.1360    raeburn  11724: sub get_domain_lti {
                   11725:     my ($cdom,$context) = @_;
                   11726:     my ($name,%lti);
                   11727:     if ($context eq 'consumer') {
                   11728:         $name = 'ltitools';
                   11729:     } elsif ($context eq 'provider') {
                   11730:         $name = 'lti';
                   11731:     } else {
                   11732:         return %lti;
                   11733:     }
                   11734:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  11735:     if (defined($cached)) {
                   11736:         if (ref($result) eq 'HASH') {
1.1360    raeburn  11737:             %lti = %{$result};
1.1298    raeburn  11738:         }
                   11739:     } else {
1.1360    raeburn  11740:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11741:         if (ref($domconfig{$name}) eq 'HASH') {
                   11742:             %lti = %{$domconfig{$name}};
                   11743:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   11744:             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11745:                 foreach my $id (keys(%lti)) {
                   11746:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  11747:                         foreach my $item ('key','secret') {
1.1360    raeburn  11748:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  11749:                         }
                   11750:                     }
                   11751:                 }
                   11752:             }
1.1298    raeburn  11753:         }
                   11754:         my $cachetime = 24*60*60;
1.1360    raeburn  11755:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  11756:     }
1.1360    raeburn  11757:     return %lti;
1.1298    raeburn  11758: }
                   11759: 
1.1236    raeburn  11760: sub get_numsuppfiles {
                   11761:     my ($cnum,$cdom,$ignorecache)=@_;
                   11762:     my $hashid=$cnum.':'.$cdom;
                   11763:     my ($suppcount,$cached);
                   11764:     unless ($ignorecache) {
                   11765:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11766:     }
                   11767:     unless (defined($cached)) {
                   11768:         my $chome=&homeserver($cnum,$cdom);
                   11769:         unless ($chome eq 'no_host') {
1.1366    raeburn  11770:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  11771:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  11772:             ($suppcount,$supptools,$errors) =
                   11773:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   11774:                                                          $supptools,$errors);
1.1236    raeburn  11775:         }
                   11776:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11777:     }
                   11778:     return $suppcount;
                   11779: }
                   11780: 
1.379     matthew  11781: #
                   11782: # EXT resource caching routines
                   11783: #
                   11784: 
1.1302    raeburn  11785: {
                   11786: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11787: #
                   11788: # The course for which we cache
                   11789: my $cachedmapkey='';
                   11790: # The cached recursive maps for this course
                   11791: my %cachedmaps=();
                   11792: # When this was last done
                   11793: my $cachedmaptime='';
                   11794: 
1.379     matthew  11795: sub clear_EXT_cache_status {
1.383     albertel 11796:     &delenv('cache.EXT.');
1.379     matthew  11797: }
                   11798: 
                   11799: sub EXT_cache_status {
                   11800:     my ($target_domain,$target_user) = @_;
1.383     albertel 11801:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11802:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11803:         # We know already the user has no data
                   11804:         return 1;
                   11805:     } else {
                   11806:         return 0;
                   11807:     }
                   11808: }
                   11809: 
                   11810: sub EXT_cache_set {
                   11811:     my ($target_domain,$target_user) = @_;
1.383     albertel 11812:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11813:     #&appenv({$cachename => time});
1.379     matthew  11814: }
                   11815: 
1.28      www      11816: # --------------------------------------------------------- Value of a Variable
1.58      www      11817: sub EXT {
1.715     albertel 11818: 
1.1228    raeburn  11819:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11820:     unless ($varname) { return ''; }
1.218     albertel 11821:     #get real user name/domain, courseid and symb
                   11822:     my $courseid;
1.359     albertel 11823:     my $publicuser;
1.427     www      11824:     if ($symbparm) {
                   11825: 	$symbparm=&get_symb_from_alias($symbparm);
                   11826:     }
1.218     albertel 11827:     if (!($uname && $udom)) {
1.790     albertel 11828:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11829:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11830:     } else {
1.620     albertel 11831: 	$courseid=$env{'request.course.id'};
1.218     albertel 11832:     }
1.48      www      11833:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11834:     my $rest;
1.320     albertel 11835:     if (defined($therest[0])) {
1.48      www      11836:        $rest=join('.',@therest);
                   11837:     } else {
                   11838:        $rest='';
                   11839:     }
1.320     albertel 11840: 
1.57      www      11841:     my $qualifierrest=$qualifier;
                   11842:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11843:     my $spacequalifierrest=$space;
                   11844:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11845:     if ($realm eq 'user') {
1.48      www      11846: # --------------------------------------------------------------- user.resource
                   11847: 	if ($space eq 'resource') {
1.651     albertel 11848: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11849: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11850: 		 &&
1.744     albertel 11851: 		 ($symbparm eq &symbread()) ) {	
                   11852: 		# if we are in the middle of processing the resource the
                   11853: 		# get the value we are planning on committing
                   11854:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11855:                     return $Apache::lonhomework::results{$qualifierrest};
                   11856:                 } else {
                   11857:                     return $Apache::lonhomework::history{$qualifierrest};
                   11858:                 }
1.335     albertel 11859: 	    } else {
1.359     albertel 11860: 		my %restored;
1.620     albertel 11861: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11862: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11863: 		} else {
                   11864: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11865: 		}
1.335     albertel 11866: 		return $restored{$qualifierrest};
                   11867: 	    }
1.48      www      11868: # ----------------------------------------------------------------- user.access
                   11869:         } elsif ($space eq 'access') {
1.218     albertel 11870: 	    # FIXME - not supporting calls for a specific user
1.48      www      11871:             return &allowed($qualifier,$rest);
                   11872: # ------------------------------------------ user.preferences, user.environment
                   11873:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11874: 	    if (($uname eq $env{'user.name'}) &&
                   11875: 		($udom eq $env{'user.domain'})) {
                   11876: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11877: 	    } else {
1.359     albertel 11878: 		my %returnhash;
                   11879: 		if (!$publicuser) {
                   11880: 		    %returnhash=&userenvironment($udom,$uname,
                   11881: 						 $qualifierrest);
                   11882: 		}
1.218     albertel 11883: 		return $returnhash{$qualifierrest};
                   11884: 	    }
1.48      www      11885: # ----------------------------------------------------------------- user.course
                   11886:         } elsif ($space eq 'course') {
1.218     albertel 11887: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11888:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11889: # ------------------------------------------------------------------- user.role
                   11890:         } elsif ($space eq 'role') {
1.218     albertel 11891: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11892:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11893:             if ($qualifier eq 'value') {
                   11894: 		return $role;
                   11895:             } elsif ($qualifier eq 'extent') {
                   11896:                 return $where;
                   11897:             }
                   11898: # ----------------------------------------------------------------- user.domain
                   11899:         } elsif ($space eq 'domain') {
1.218     albertel 11900:             return $udom;
1.48      www      11901: # ------------------------------------------------------------------- user.name
                   11902:         } elsif ($space eq 'name') {
1.218     albertel 11903:             return $uname;
1.48      www      11904: # ---------------------------------------------------- Any other user namespace
1.29      www      11905:         } else {
1.359     albertel 11906: 	    my %reply;
                   11907: 	    if (!$publicuser) {
                   11908: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11909: 	    }
                   11910: 	    return $reply{$qualifierrest};
1.48      www      11911:         }
1.236     www      11912:     } elsif ($realm eq 'query') {
                   11913: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11914:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11915: 						[$spacequalifierrest]);
1.620     albertel 11916: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11917:    } elsif ($realm eq 'request') {
1.48      www      11918: # ------------------------------------------------------------- request.browser
                   11919:         if ($space eq 'browser') {
1.1145    bisitz   11920:             return $env{'browser.'.$qualifier};
1.57      www      11921: # ------------------------------------------------------------ request.filename
                   11922:         } else {
1.620     albertel 11923:             return $env{'request.'.$spacequalifierrest};
1.29      www      11924:         }
1.28      www      11925:     } elsif ($realm eq 'course') {
1.48      www      11926: # ---------------------------------------------------------- course.description
1.620     albertel 11927:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11928:     } elsif ($realm eq 'resource') {
1.165     www      11929: 
1.620     albertel 11930: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11931: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11932: 	}
1.693     albertel 11933: 
1.1232    raeburn  11934:         if ($qualifier eq '') {
                   11935: 	    if ($space eq 'title') {
                   11936: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11937: 	        return &gettitle($symbparm);
                   11938: 	    }
1.693     albertel 11939: 	
1.1232    raeburn  11940: 	    if ($space eq 'map') {
                   11941: 	        my ($map) = &decode_symb($symbparm);
                   11942: 	        return &symbread($map);
                   11943: 	    }
                   11944:             if ($space eq 'maptitle') {
                   11945:                 my ($map) = &decode_symb($symbparm);
                   11946:                 return &gettitle($map);
                   11947:             }
                   11948: 	    if ($space eq 'filename') {
                   11949: 	        if ($symbparm) {
                   11950: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11951: 	        }
                   11952: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11953: 	    }
1.1232    raeburn  11954: 
1.1233    raeburn  11955:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11956:                 if ($space eq 'visibleparts') {
                   11957:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11958:                     my $item;
                   11959:                     if (ref($navmap)) {
                   11960:                         my $res = $navmap->getBySymb($symbparm);
                   11961:                         my $parts = $res->parts();
                   11962:                         if (ref($parts) eq 'ARRAY') {
                   11963:                             $item = join(',',@{$parts});
                   11964:                         }
                   11965:                         undef($navmap);
1.1232    raeburn  11966:                     }
1.1233    raeburn  11967:                     return $item;
1.1232    raeburn  11968:                 }
                   11969:             }
                   11970:         }
1.693     albertel 11971: 
1.1301    raeburn  11972: 	my ($section, $group, @groups, @recurseup, $recursed);
                   11973: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  11974:         if (($courseid eq '') && ($cid)) {
                   11975:             $courseid = $cid;
                   11976:         }
                   11977: 	if (($symbparm && $courseid) && 
                   11978: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      11979: 
1.218     albertel 11980: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11981: 
1.60      www      11982: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11983: 	    my $symbp=$symbparm;
1.1301    raeburn  11984: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11985: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  11986:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 11987: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 11988: 	    if (($env{'user.name'} eq $uname) &&
                   11989: 		($env{'user.domain'} eq $udom)) {
                   11990: 		$section=$env{'request.course.sec'};
1.733     raeburn  11991:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11992:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11993: 	    } else {
1.539     albertel 11994: 		if (! defined($usection)) {
1.551     albertel 11995: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11996: 		} else {
                   11997: 		    $section = $usection;
                   11998: 		}
1.733     raeburn  11999:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12000: 	    }
                   12001: 
                   12002: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12003: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  12004:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 12005: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12006: 
1.593     albertel 12007: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12008: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  12009:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 12010: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12011: 
1.60      www      12012: # ----------------------------------------------------------- first, check user
1.624     albertel 12013: 
1.1301    raeburn  12014: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   12015:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 12016: 				       ([$courselevelr,'resource'],
                   12017: 					[$courselevelm,'map'     ],
1.1301    raeburn  12018:                                         [$courseleveli,'map'     ],
1.927     albertel 12019: 					[$courselevel, 'course'  ]));
1.931     albertel 12020: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12021: 
1.594     albertel 12022: # ------------------------------------------------ second, check some of course
1.684     raeburn  12023:             my $coursereply;
1.691     raeburn  12024:             if (@groups > 0) {
                   12025:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  12026:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   12027:                                        $mapp,\$recursed,\@recurseup);
                   12028:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  12029:             }
1.96      www      12030: 
1.684     raeburn  12031: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12032: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12033: 				  'course',$mapp,\$recursed,\@recurseup,
                   12034:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 12035: 				  ([$seclevelr,   'resource'],
                   12036: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  12037:                                    [$secleveli,   'map'     ],
1.927     albertel 12038: 				   [$seclevel,    'course'  ],
                   12039: 				   [$courselevelr,'resource']));
                   12040: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12041: 
1.60      www      12042: # ------------------------------------------------------ third, check map parms
1.218     albertel 12043: 	    my %parmhash=();
                   12044: 	    my $thisparm='';
                   12045: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12046: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12047: 		    &GDBM_READER(),0640)) {
1.218     albertel 12048: 		$thisparm=$parmhash{$symbparm};
                   12049: 		untie(%parmhash);
                   12050: 	    }
1.927     albertel 12051: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12052: 	}
1.594     albertel 12053: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  12054:  
                   12055:         my $what = $spacequalifierrest;
                   12056: 	$what=~s/\./\_/;
1.282     albertel 12057: 	my $filename;
                   12058: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12059: 	if ($symbparm) {
1.409     www      12060: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12061: 	} else {
1.620     albertel 12062: 	    $filename=$env{'request.filename'};
1.282     albertel 12063: 	}
1.1362    raeburn  12064:         my $toolsymb;
                   12065:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   12066:             $toolsymb = $symbparm;
                   12067:         }
                   12068: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 12069: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  12070: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 12071: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12072: 
1.1301    raeburn  12073: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 12074: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12075: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12076: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12077: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12078: 				     'course',$mapp,\$recursed,\@recurseup,
                   12079:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 12080: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  12081:                                       [$courseleveli,'map'   ],
1.927     albertel 12082: 				      [$courselevel, 'course']));
                   12083: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12084: 	}
1.145     www      12085: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12086: 	unless ($space eq '0') {
1.336     albertel 12087: 	    my @parts=split(/_/,$space);
                   12088: 	    my $id=pop(@parts);
                   12089: 	    my $part=join('_',@parts);
                   12090: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12091: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12092: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12093: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12094: 	}
1.395     albertel 12095: 	if ($recurse) { return undef; }
1.1362    raeburn  12096: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 12097: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12098: # ---------------------------------------------------- Any other user namespace
                   12099:     } elsif ($realm eq 'environment') {
                   12100: # ----------------------------------------------------------------- environment
1.620     albertel 12101: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12102: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12103: 	} else {
1.770     albertel 12104: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12105: 		return '';
                   12106: 	    }
1.219     albertel 12107: 	    my %returnhash=&userenvironment($udom,$uname,
                   12108: 					    $spacequalifierrest);
                   12109: 	    return $returnhash{$spacequalifierrest};
                   12110: 	}
1.28      www      12111:     } elsif ($realm eq 'system') {
1.48      www      12112: # ----------------------------------------------------------------- system.time
                   12113: 	if ($space eq 'time') {
                   12114: 	    return time;
                   12115:         }
1.696     albertel 12116:     } elsif ($realm eq 'server') {
                   12117: # ----------------------------------------------------------------- system.time
                   12118: 	if ($space eq 'name') {
                   12119: 	    return $ENV{'SERVER_NAME'};
                   12120:         }
1.28      www      12121:     }
1.48      www      12122:     return '';
1.61      www      12123: }
                   12124: 
1.927     albertel 12125: sub get_reply {
                   12126:     my ($reply_value) = @_;
1.940     raeburn  12127:     if (ref($reply_value) eq 'ARRAY') {
                   12128:         if (wantarray) {
                   12129: 	    return @$reply_value;
                   12130:         }
                   12131:         return $reply_value->[0];
                   12132:     } else {
                   12133:         return $reply_value;
1.927     albertel 12134:     }
                   12135: }
                   12136: 
1.691     raeburn  12137: sub check_group_parms {
1.1301    raeburn  12138:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   12139:         $recursed,$recurseupref) = @_;
                   12140:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   12141:                   [$what,'course']);
                   12142:     my $coursereply;
1.691     raeburn  12143:     foreach my $group (@{$groups}) {
1.1301    raeburn  12144:         my @groupitems = ();
1.691     raeburn  12145:         foreach my $level (@levels) {
1.927     albertel 12146:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12147:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12148:         }
1.1301    raeburn  12149:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12150:                                    $env{'course.'.$courseid.'.domain'},
                   12151:                                    'course',$mapp,$recursed,$recurseupref,
                   12152:                                    $courseid,'.['.$group.'].',$what,
                   12153:                                    @groupitems);
                   12154:         last if (defined($coursereply));
1.691     raeburn  12155:     }
                   12156:     return $coursereply;
                   12157: }
                   12158: 
1.1301    raeburn  12159: sub get_map_hierarchy {
1.1302    raeburn  12160:     my ($mapname,$courseid) = @_;
                   12161:     my @recurseup = ();
1.1301    raeburn  12162:     if ($mapname) {
1.1302    raeburn  12163:         if (($cachedmapkey eq $courseid) &&
                   12164:             (abs($cachedmaptime-time)<5)) {
                   12165:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12166:                 return @{$cachedmaps{$mapname}};
                   12167:             }
                   12168:         }
1.1301    raeburn  12169:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12170:         if (ref($navmap)) {
                   12171:             @recurseup = $navmap->recurseup_maps($mapname);
                   12172:             undef($navmap);
1.1302    raeburn  12173:             $cachedmaps{$mapname} = \@recurseup;
                   12174:             $cachedmaptime=time;
                   12175:             $cachedmapkey=$courseid;
1.1301    raeburn  12176:         }
                   12177:     }
                   12178:     return @recurseup;
                   12179: }
                   12180: 
1.1302    raeburn  12181: }
                   12182: 
1.691     raeburn  12183: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12184:     my ($courseid,@groups) = @_;
                   12185:     @groups = sort(@groups);
1.691     raeburn  12186:     return @groups;
                   12187: }
                   12188: 
1.395     albertel 12189: sub packages_tab_default {
1.1362    raeburn  12190:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 12191:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12192: 
                   12193:     my (@extension,@specifics,$do_default);
1.1362    raeburn  12194:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 12195: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12196: 	if ($pack_type eq 'default') {
                   12197: 	    $do_default=1;
                   12198: 	} elsif ($pack_type eq 'extension') {
                   12199: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12200: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12201: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12202: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12203: 	}
                   12204:     }
                   12205:     # first look for a package that matches the requested part id
                   12206:     foreach my $package (@specifics) {
                   12207: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12208: 	next if ($pack_part ne $part);
                   12209: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12210: 	    return $packagetab{"$pack_type&$name&default"};
                   12211: 	}
                   12212:     }
                   12213:     # look for any possible matching non extension_ package
                   12214:     foreach my $package (@specifics) {
                   12215: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12216: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12217: 	    return $packagetab{"$pack_type&$name&default"};
                   12218: 	}
1.585     albertel 12219: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12220: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12221: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12222: 	}
                   12223:     }
1.738     albertel 12224:     # look for any posible extension_ match
                   12225:     foreach my $package (@extension) {
                   12226: 	my ($package,$pack_type)=@{$package};
                   12227: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12228: 	    return $packagetab{"$pack_type&$name&default"};
                   12229: 	}
                   12230: 	if (defined($packagetab{$package."&$name&default"})) {
                   12231: 	    return $packagetab{$package."&$name&default"};
                   12232: 	}
                   12233:     }
                   12234:     # look for a global default setting
                   12235:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12236: 	return $packagetab{"default&$name&default"};
                   12237:     }
1.395     albertel 12238:     return undef;
                   12239: }
                   12240: 
1.334     albertel 12241: sub add_prefix_and_part {
                   12242:     my ($prefix,$part)=@_;
                   12243:     my $keyroot;
                   12244:     if (defined($prefix) && $prefix !~ /^__/) {
                   12245: 	# prefix that has a part already
                   12246: 	$keyroot=$prefix;
                   12247:     } elsif (defined($prefix)) {
                   12248: 	# prefix that is missing a part
                   12249: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12250:     } else {
                   12251: 	# no prefix at all
                   12252: 	if (defined($part)) { $keyroot='_'.$part; }
                   12253:     }
                   12254:     return $keyroot;
                   12255: }
                   12256: 
1.71      www      12257: # ---------------------------------------------------------------- Get metadata
                   12258: 
1.599     albertel 12259: my %metaentry;
1.1070    www      12260: my %importedpartids;
1.1369    raeburn  12261: my %importedrespids;
1.71      www      12262: sub metadata {
1.1362    raeburn  12263:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      12264:     $uri=&declutter($uri);
1.288     albertel 12265:     # if it is a non metadata possible uri return quickly
1.529     albertel 12266:     if (($uri eq '') || 
                   12267: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  12268: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12269:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12270: 	return undef;
                   12271:     }
1.1261    raeburn  12272:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12273: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12274: 	return undef;
1.288     albertel 12275:     }
1.73      www      12276:     my $filename=$uri;
                   12277:     $uri=~s/\.meta$//;
1.172     www      12278: #
                   12279: # Is the metadata already cached?
1.177     www      12280: # Look at timestamp of caching
1.172     www      12281: # Everything is cached by the main uri, libraries are never directly cached
                   12282: #
1.428     albertel 12283:     if (!defined($liburi)) {
1.599     albertel 12284: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12285: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12286:     }
1.1362    raeburn  12287: 
                   12288: #
                   12289: # If the uri is for an external tool the file from
                   12290: # which metadata should be retrieved depends on whether
                   12291: # the tool had been configured to be gradable (set in the Course
                   12292: # Editor or Resource Editor).
                   12293: #
                   12294: # If a valid symb has been included as the third arg in the call
                   12295: # to &metadata() that can be used to retrieve the value of
                   12296: # parameter_0_gradable set for the resource, and included in the
                   12297: # uploaded map containing the tool. The value is retrieved via
                   12298: # &EXT(), if a valid symb is available.  Otherwise the value of
                   12299: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  12300: # is retrieved via &get().
                   12301: #
                   12302: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   12303: # hiddenresource and encrypturl (during course initialization)
                   12304: # the map-level parameter for resource.0.gradable included in the 
                   12305: # uploaded map containing the tool will not yet have been stored
                   12306: # in the user_course_parms.db file for the user's session, so in 
                   12307: # this case fall back to retrieving gradable status from the
                   12308: # exttool_$marker.db file.
1.1362    raeburn  12309: #
                   12310: # In order to avoid an infinite loop, &metadata() will return
                   12311: # before a call to &EXT(), if the uri is for an external tool
                   12312: # and the $what for which metadata is being requested is
                   12313: # parameter_0_gradable or 0_gradable.
                   12314: #
                   12315: 
                   12316:     if ($uri =~ /ext\.tool$/) {
                   12317:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   12318:             return;
                   12319:         } else {
                   12320:             my ($checked,$use_passback);
                   12321:             if ($toolsymb ne '') {
                   12322:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  12323:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  12324:                     $checked = 1;
                   12325:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   12326:                         $use_passback = 1;
                   12327:                     }
                   12328:                 }
                   12329:             }
                   12330:             unless ($checked) {
                   12331:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   12332:                 $marker=~s/\D//g;
1.1363    raeburn  12333:                 if ($marker) {
1.1362    raeburn  12334:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   12335:                     $use_passback = $toolsettings{'gradable'};
                   12336:                 }
                   12337:             }
                   12338:             if ($use_passback) {
                   12339:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   12340:             } else {
                   12341:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   12342:             }
                   12343:         }
                   12344:     }
                   12345: 
1.428     albertel 12346:     {
1.1069    www      12347: # Imported parts would go here
1.1369    raeburn  12348:         my @origfiletagids=();
1.1069    www      12349:         my $importedparts=0;
1.1369    raeburn  12350: 
                   12351: # Imported responseids would go here
                   12352:         my $importedresponses=0;
1.172     www      12353: #
                   12354: # Is this a recursive call for a library?
                   12355: #
1.599     albertel 12356: #	if (! exists($metacache{$uri})) {
                   12357: #	    $metacache{$uri}={};
                   12358: #	}
1.924     albertel 12359: 	my $cachetime = 60*60;
1.171     www      12360:         if ($liburi) {
                   12361: 	    $liburi=&declutter($liburi);
                   12362:             $filename=$liburi;
1.401     bowersj2 12363:         } else {
1.599     albertel 12364: 	    &devalidate_cache_new('meta',$uri);
                   12365: 	    undef(%metaentry);
1.401     bowersj2 12366: 	}
1.140     www      12367:         my %metathesekeys=();
1.73      www      12368:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12369: 	my $metastring;
1.1140    www      12370: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12371: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12372: 	    $metastring = 
1.929     albertel 12373: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12374: 					  ('grade_target' => 'meta'));
                   12375: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12376: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12377:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12378: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12379: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12380: 	    $metastring=&getfile($file);
1.489     albertel 12381: 	}
1.208     albertel 12382:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12383:         my $token;
1.140     www      12384:         undef %metathesekeys;
1.71      www      12385:         while ($token=$parser->get_token) {
1.339     albertel 12386: 	    if ($token->[0] eq 'S') {
                   12387: 		if (defined($token->[2]->{'package'})) {
1.172     www      12388: #
                   12389: # This is a package - get package info
                   12390: #
1.339     albertel 12391: 		    my $package=$token->[2]->{'package'};
                   12392: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12393: 		    if (defined($token->[2]->{'id'})) { 
                   12394: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12395: 		    }
1.599     albertel 12396: 		    if ($metaentry{':packages'}) {
                   12397: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12398: 		    } else {
1.599     albertel 12399: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12400: 		    }
1.736     albertel 12401: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12402: 			my $part=$keyroot;
                   12403: 			$part=~s/^\_//;
1.736     albertel 12404: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12405: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12406: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12407: 			    # ignore package.tab specified default values
                   12408:                             # here &package_tab_default() will fetch those
                   12409: 			    if ($subp eq 'default') { next; }
1.736     albertel 12410: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12411: 			    my $unikey;
                   12412: 			    if ($pack =~ /_0$/) {
                   12413: 				$unikey='parameter_0_'.$name;
                   12414: 				$part=0;
                   12415: 			    } else {
                   12416: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12417: 			    }
1.339     albertel 12418: 			    if ($subp eq 'display') {
                   12419: 				$value.=' [Part: '.$part.']';
                   12420: 			    }
1.599     albertel 12421: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12422: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12423: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12424: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12425: 			    }
1.599     albertel 12426: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12427: 				$metaentry{':'.$unikey}=
                   12428: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12429: 			    }
1.339     albertel 12430: 			}
                   12431: 		    }
                   12432: 		} else {
1.172     www      12433: #
                   12434: # This is not a package - some other kind of start tag
1.339     albertel 12435: #
                   12436: 		    my $entry=$token->[1];
1.1068    www      12437: 		    my $unikey='';
1.175     www      12438: 
1.339     albertel 12439: 		    if ($entry eq 'import') {
1.175     www      12440: #
                   12441: # Importing a library here
1.339     albertel 12442: #
1.1067    www      12443:                         my $location=$parser->get_text('/import');
                   12444:                         my $dir=$filename;
                   12445:                         $dir=~s|[^/]*$||;
                   12446:                         $location=&filelocation($dir,$location);
1.1369    raeburn  12447: 
                   12448:                         my $importid=$token->[2]->{'id'};
1.1068    www      12449:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  12450: #
                   12451: # Check metadata for imported file to
                   12452: # see if it contained response items
                   12453: #
1.1372    raeburn  12454:                         my ($origfile,@libfilekeys);
1.1370    raeburn  12455:                         my %currmetaentry = %metaentry;
1.1372    raeburn  12456:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   12457:                                                            $depthcount+1));
                   12458:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   12459:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   12460:                                                              undef,$depthcount+1);
                   12461:                             if ($libresponseorder ne '') {
                   12462:                                 if ($#origfiletagids<0) {
                   12463:                                     undef(%importedrespids);
                   12464:                                     undef(%importedpartids);
                   12465:                                 }
1.1373    raeburn  12466:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   12467:                                 if (@respids) {
                   12468:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   12469:                                 }
                   12470:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  12471:                                     $importedresponses = 1;
1.1369    raeburn  12472: # We need to get the original file and the imported file to get the response order correct
                   12473: # Load and inspect original file
1.1372    raeburn  12474:                                     if ($#origfiletagids<0) {
                   12475:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12476:                                         $origfile=&getfile($origfilelocation);
                   12477:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12478:                                     }
1.1369    raeburn  12479:                                 }
                   12480:                             }
                   12481:                         }
1.1370    raeburn  12482: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12483: # hash populated for imported library file
                   12484:                         %metaentry = %currmetaentry;
                   12485:                         undef(%currmetaentry);
1.1374    raeburn  12486:                         if ($importmode eq 'part') {
1.1068    www      12487: # Import as part(s)
1.1069    www      12488:                            $importedparts=1;
                   12489: # We need to get the original file and the imported file to get the part order correct
                   12490: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  12491: # Load and inspect original file if we didn't do that already
                   12492:                            if ($#origfiletagids<0) {
                   12493:                                undef(%importedrespids);
                   12494:                                undef(%importedpartids);
                   12495:                                if ($origfile eq '') {
                   12496:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12497:                                    $origfile=&getfile($origfilelocation);
                   12498:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12499:                                }
1.1070    www      12500:                            }
1.1372    raeburn  12501:                            my @impfilepartids;
                   12502: # If <partorder> tag is included in metadata for the imported file
                   12503: # get the parts in the imported file from that.
                   12504:                            if (grep(/^partorder$/,@libfilekeys)) {
                   12505:                                %currmetaentry = %metaentry;
                   12506:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12507:                                                             $depthcount+1);
                   12508:                                %metaentry = %currmetaentry;
                   12509:                                undef(%currmetaentry);
                   12510:                                if ($libpartorder ne '') {
                   12511:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   12512:                                }
                   12513:                            } else {
                   12514: # If no <partorder> tag available, load and inspect imported file
                   12515:                                my $impfile=&getfile($location);
                   12516:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12517:                            }
1.1069    www      12518:                            if ($#impfilepartids>=0) {
                   12519: # This problem had parts
1.1070    www      12520:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12521:                            } else {
                   12522: # Importing by turning a single problem into a problem part
                   12523: # It gets the import-tags ID as part-ID
                   12524:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12525:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12526:                            }
1.1068    www      12527:                         } else {
1.1374    raeburn  12528: # Import as problem or as normal import
                   12529:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12530:                             unless ($importmode eq 'problem') {
1.1068    www      12531: # Normal import
1.1374    raeburn  12532:                                 if (defined($token->[2]->{'id'})) {
                   12533:                                     $unikey.='_'.$token->[2]->{'id'};
                   12534:                                 }
                   12535:                             }
                   12536: # Check metadata for imported file to
                   12537: # see if it contained parts
                   12538:                             if (grep(/^partorder$/,@libfilekeys)) {
                   12539:                                 %currmetaentry = %metaentry;
                   12540:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12541:                                                              $depthcount+1);
                   12542:                                 %metaentry = %currmetaentry;
                   12543:                                 undef(%currmetaentry);
                   12544:                                 if ($libpartorder ne '') {
                   12545:                                     $importedparts = 1;
                   12546:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   12547:                                 }
                   12548:                             }
1.1067    www      12549:                         }
1.339     albertel 12550: 			if ($depthcount<20) {
1.736     albertel 12551: 			    my $metadata = 
1.1362    raeburn  12552: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12553: 					  $depthcount+1);
                   12554: 			    foreach my $meta (split(',',$metadata)) {
                   12555: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12556: 				$metathesekeys{$meta}=1;
1.339     albertel 12557: 			    }
1.1068    www      12558:                         }
1.1067    www      12559: 		    } else {
                   12560: #
                   12561: # Not importing, some other kind of non-package, non-library start tag
                   12562: # 
                   12563:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12564:                         if (defined($token->[2]->{'id'})) {
                   12565:                             $unikey.='_'.$token->[2]->{'id'};
                   12566:                         }
1.339     albertel 12567: 			if (defined($token->[2]->{'name'})) { 
                   12568: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12569: 			}
                   12570: 			$metathesekeys{$unikey}=1;
1.736     albertel 12571: 			foreach my $param (@{$token->[3]}) {
                   12572: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12573: 				$token->[2]->{$param};
1.339     albertel 12574: 			}
                   12575: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12576: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12577: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12578: 		 # only ws inside the tag, and not in default, so use default
                   12579: 		 # as value
1.599     albertel 12580: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12581: 			} elsif ( $internaltext =~ /\S/ ) {
                   12582: 		  # something interesting inside the tag
                   12583: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12584: 			} else {
1.908     albertel 12585: 		  # no interesting values, don't set a default
1.339     albertel 12586: 			}
1.172     www      12587: # end of not-a-package not-a-library import
1.339     albertel 12588: 		    }
1.172     www      12589: # end of not-a-package start tag
1.339     albertel 12590: 		}
1.172     www      12591: # the next is the end of "start tag"
1.339     albertel 12592: 	    }
                   12593: 	}
1.483     albertel 12594: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12595: 	$extension = lc($extension);
                   12596: 	if ($extension eq 'htm') { $extension='html'; }
                   12597: 
1.737     albertel 12598: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12599: 	    #no specific packages #how's our extension
                   12600: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12601: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12602: 					 \%metathesekeys);
                   12603: 	}
1.883     albertel 12604: 
                   12605: 	if (!exists($metaentry{':packages'})
                   12606: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12607: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12608: 		#no specific packages well let's get default then
                   12609: 		if ($key!~/^default&/) { next; }
1.488     albertel 12610: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12611: 					     \%metathesekeys);
                   12612: 	    }
                   12613: 	}
1.338     www      12614: # are there custom rights to evaluate
1.599     albertel 12615: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12616: 
1.338     www      12617:     #
                   12618:     # Importing a rights file here
1.339     albertel 12619:     #
                   12620: 	    unless ($depthcount) {
1.599     albertel 12621: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12622: 		my $dir=$filename;
                   12623: 		$dir=~s|[^/]*$||;
                   12624: 		$location=&filelocation($dir,$location);
1.736     albertel 12625: 		my $rights_metadata =
1.1362    raeburn  12626: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 12627: 			      $depthcount+1);
                   12628: 		foreach my $rights (split(',',$rights_metadata)) {
                   12629: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12630: 		    $metathesekeys{$rights}=1;
1.339     albertel 12631: 		}
                   12632: 	    }
                   12633: 	}
1.737     albertel 12634: 	# uniqifiy package listing
                   12635: 	my %seen;
                   12636: 	my @uniq_packages =
                   12637: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12638: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12639: 
1.1369    raeburn  12640:         if (($importedresponses) || ($importedparts)) {
                   12641:             if ($importedparts) {
1.1070    www      12642: # We had imported parts and need to rebuild partorder
1.1369    raeburn  12643:                 $metaentry{':partorder'}='';
                   12644:                 $metathesekeys{'partorder'}=1;
                   12645:             }
                   12646:             if ($importedresponses) {
                   12647: # We had imported responses and need to rebuil responseorder
                   12648:                 $metaentry{':responseorder'}='';
                   12649:                 $metathesekeys{'responseorder'}=1;
                   12650:             }
                   12651:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12652:                 my $origid = $origfiletagids[$index+1];
                   12653:                 if ($origfiletagids[$index] eq 'part') {
                   12654: # Original part, part of the problem
                   12655:                     if ($importedparts) {
                   12656:                         $metaentry{':partorder'}.=','.$origid;
                   12657:                     }
                   12658:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12659:                     if ($importedparts) {
                   12660: # We have imported parts at this position
1.1373    raeburn  12661:                         if ($importedpartids{$origid} ne '') {
                   12662:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12663:                         }
1.1369    raeburn  12664:                     }
                   12665:                     if ($importedresponses) {
                   12666: # We have imported responses at this position
1.1373    raeburn  12667:                         if ($importedrespids{$origid} ne '') {
                   12668:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  12669:                         }
                   12670:                     }
                   12671:                 } else {
                   12672: # Original response item, part of the problem
                   12673:                     if ($importedresponses) {
                   12674:                         $metaentry{':responseorder'}.=','.$origid;
                   12675:                     }
                   12676:                 }
                   12677:             }
                   12678:             if ($importedparts) {
                   12679:                 $metaentry{':partorder'}=~s/^\,//;
                   12680:             }
                   12681:             if ($importedresponses) {
                   12682:                 $metaentry{':responseorder'}=~s/^\,//;
                   12683:             }
1.1070    www      12684:         }
1.737     albertel 12685: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12686: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  12687: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  12688:         unless ($liburi) {
                   12689: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   12690:         }
1.177     www      12691: # this is the end of "was not already recently cached
1.71      www      12692:     }
1.599     albertel 12693:     return $metaentry{':'.$what};
1.261     albertel 12694: }
                   12695: 
1.488     albertel 12696: sub metadata_create_package_def {
1.483     albertel 12697:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12698:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12699:     if ($subp eq 'default') { next; }
                   12700:     
1.599     albertel 12701:     if (defined($metaentry{':packages'})) {
                   12702: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12703:     } else {
1.599     albertel 12704: 	$metaentry{':packages'}=$package;
1.483     albertel 12705:     }
                   12706:     my $value=$packagetab{$key};
                   12707:     my $unikey;
                   12708:     $unikey='parameter_0_'.$name;
1.599     albertel 12709:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12710:     $$metathesekeys{$unikey}=1;
1.599     albertel 12711:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12712: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12713:     }
1.599     albertel 12714:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12715: 	$metaentry{':'.$unikey}=
                   12716: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12717:     }
                   12718: }
                   12719: 
1.261     albertel 12720: sub metadata_generate_part0 {
                   12721:     my ($metadata,$metacache,$uri) = @_;
                   12722:     my %allnames;
1.737     albertel 12723:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12724: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12725: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12726: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12727: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12728: 	    $allnames{$name}=$part;
                   12729: 	  }
                   12730: 	}
                   12731:     }
                   12732:     foreach my $name (keys(%allnames)) {
                   12733:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12734:       my $key=":parameter_0_$name";
1.261     albertel 12735:       $$metacache{"$key.part"}='0';
                   12736:       $$metacache{"$key.name"}=$name;
1.428     albertel 12737:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12738: 					   $allnames{$name}.'_'.$name.
                   12739: 					   '.type'};
1.428     albertel 12740:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12741: 			     '.display'};
1.644     www      12742:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12743:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12744:       $$metacache{"$key.display"}=$olddis;
                   12745:     }
1.71      www      12746: }
                   12747: 
1.764     albertel 12748: # ------------------------------------------------------ Devalidate title cache
                   12749: 
                   12750: sub devalidate_title_cache {
                   12751:     my ($url)=@_;
                   12752:     if (!$env{'request.course.id'}) { return; }
                   12753:     my $symb=&symbread($url);
                   12754:     if (!$symb) { return; }
                   12755:     my $key=$env{'request.course.id'}."\0".$symb;
                   12756:     &devalidate_cache_new('title',$key);
                   12757: }
                   12758: 
1.1014    droeschl 12759: # ------------------------------------------------- Get the title of a course
                   12760: 
                   12761: sub current_course_title {
                   12762:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12763: }
1.301     www      12764: # ------------------------------------------------- Get the title of a resource
                   12765: 
                   12766: sub gettitle {
                   12767:     my $urlsymb=shift;
                   12768:     my $symb=&symbread($urlsymb);
1.534     albertel 12769:     if ($symb) {
1.620     albertel 12770: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12771: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12772: 	if (defined($cached)) { 
                   12773: 	    return $result;
                   12774: 	}
1.534     albertel 12775: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12776: 	my $title='';
1.907     albertel 12777: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12778: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12779: 	} else {
                   12780: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12781: 		    &GDBM_READER(),0640)) {
                   12782: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12783: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12784: 		untie(%bighash);
                   12785: 	    }
1.534     albertel 12786: 	}
                   12787: 	$title=~s/\&colon\;/\:/gs;
                   12788: 	if ($title) {
1.1159    www      12789: # Remember both $symb and $title for dynamic metadata
                   12790:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12791:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12792: # Cache this title and then return it
1.599     albertel 12793: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12794: 	}
                   12795: 	$urlsymb=$url;
                   12796:     }
                   12797:     my $title=&metadata($urlsymb,'title');
                   12798:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12799:     return $title;
1.301     www      12800: }
1.613     albertel 12801: 
1.614     albertel 12802: sub get_slot {
                   12803:     my ($which,$cnum,$cdom)=@_;
                   12804:     if (!$cnum || !$cdom) {
1.790     albertel 12805: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12806: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12807: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12808:     }
1.703     albertel 12809:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12810:     my %slotinfo;
                   12811:     if (exists($remembered{$key})) {
                   12812: 	$slotinfo{$which} = $remembered{$key};
                   12813:     } else {
                   12814: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12815: 	&Apache::lonhomework::showhash(%slotinfo);
                   12816: 	my ($tmp)=keys(%slotinfo);
                   12817: 	if ($tmp=~/^error:/) { return (); }
                   12818: 	$remembered{$key} = $slotinfo{$which};
                   12819:     }
1.616     albertel 12820:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12821: 	return %{$slotinfo{$which}};
                   12822:     }
                   12823:     return $slotinfo{$which};
1.614     albertel 12824: }
1.1150    raeburn  12825: 
                   12826: sub get_reservable_slots {
                   12827:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12828:     my $now = time;
                   12829:     my $reservable_info;
                   12830:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12831:     if (exists($remembered{$key})) {
                   12832:         $reservable_info = $remembered{$key};
                   12833:     } else {
                   12834:         my %resv;
                   12835:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12836:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12837:         $reservable_info = \%resv;
                   12838:         $remembered{$key} = $reservable_info;
                   12839:     }
                   12840:     return $reservable_info;
                   12841: }
                   12842: 
                   12843: sub get_course_slots {
                   12844:     my ($cnum,$cdom) = @_;
                   12845:     my $hashid=$cnum.':'.$cdom;
                   12846:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12847:     if (defined($cached)) {
                   12848:         if (ref($result) eq 'HASH') {
                   12849:             return %{$result};
                   12850:         }
                   12851:     } else {
                   12852:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12853:         my ($tmp) = keys(%slots);
                   12854:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  12855:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12856:             return %slots;
                   12857:         }
                   12858:     }
                   12859:     return;
                   12860: }
                   12861: 
                   12862: sub devalidate_slots_cache {
                   12863:     my ($cnum,$cdom)=@_;
                   12864:     my $hashid=$cnum.':'.$cdom;
                   12865:     &devalidate_cache_new('allslots',$hashid);
                   12866: }
                   12867: 
1.1181    raeburn  12868: sub get_coursechange {
                   12869:     my ($cdom,$cnum) = @_;
                   12870:     if ($cdom eq '' || $cnum eq '') {
                   12871:         return unless ($env{'request.course.id'});
                   12872:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12873:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12874:     }
                   12875:     my $hashid=$cdom.'_'.$cnum;
                   12876:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12877:     if ((defined($cached)) && ($change ne '')) {
                   12878:         return $change;
                   12879:     } else {
                   12880:         my %crshash;
                   12881:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12882:         if ($crshash{'internal.contentchange'} eq '') {
                   12883:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12884:             if ($change eq '') {
                   12885:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12886:                 $change = $crshash{'internal.created'};
                   12887:             }
                   12888:         } else {
                   12889:             $change = $crshash{'internal.contentchange'};
                   12890:         }
                   12891:         my $cachetime = 600;
                   12892:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12893:     }
                   12894:     return $change;
                   12895: }
                   12896: 
                   12897: sub devalidate_coursechange_cache {
                   12898:     my ($cnum,$cdom)=@_;
                   12899:     my $hashid=$cnum.':'.$cdom;
                   12900:     &devalidate_cache_new('crschange',$hashid);
                   12901: }
                   12902: 
1.31      www      12903: # ------------------------------------------------- Update symbolic store links
                   12904: 
                   12905: sub symblist {
                   12906:     my ($mapname,%newhash)=@_;
1.438     www      12907:     $mapname=&deversion(&declutter($mapname));
1.31      www      12908:     my %hash;
1.620     albertel 12909:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12910:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12911:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12912: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12913: 		next if ($url eq 'last_known'
                   12914: 			 && $env{'form.no_update_last_known'});
                   12915: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12916: 						    $newhash{$url}->[1],
                   12917: 						    $newhash{$url}->[0]);
1.191     harris41 12918:             }
1.31      www      12919:             if (untie(%hash)) {
                   12920: 		return 'ok';
                   12921:             }
                   12922:         }
                   12923:     }
                   12924:     return 'error';
1.212     www      12925: }
                   12926: 
                   12927: # --------------------------------------------------------------- Verify a symb
                   12928: 
                   12929: sub symbverify {
1.1190    raeburn  12930:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12931:     my $thisfn=$thisurl;
1.439     www      12932:     $thisfn=&declutter($thisfn);
1.215     www      12933: # direct jump to resource in page or to a sequence - will construct own symbs
                   12934:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12935: # check URL part
1.409     www      12936:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12937: 
1.431     www      12938:     unless ($url eq $thisfn) { return 0; }
1.213     www      12939: 
1.216     www      12940:     $symb=&symbclean($symb);
1.510     www      12941:     $thisurl=&deversion($thisurl);
1.439     www      12942:     $thisfn=&deversion($thisfn);
1.213     www      12943: 
                   12944:     my %bighash;
                   12945:     my $okay=0;
1.431     www      12946: 
1.620     albertel 12947:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12948:                             &GDBM_READER(),0640)) {
1.1204    raeburn  12949:         my $noclutter;
1.1032    raeburn  12950:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12951:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  12952:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12953:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12954:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12955:                 $noclutter = 1;
                   12956:             }
                   12957:         }
                   12958:         my $ids;
                   12959:         if ($noclutter) {
                   12960:             $ids=$bighash{'ids_'.$thisurl};
                   12961:         } else {
                   12962:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12963:         }
1.1102    raeburn  12964:         unless ($ids) {
                   12965:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   12966:             $ids=$bighash{$idkey};
1.216     www      12967:         }
                   12968:         if ($ids) {
                   12969: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  12970:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  12971:                 $symb =~ s/\?.+$//;
1.1202    raeburn  12972:             }
1.800     albertel 12973: 	    foreach my $id (split(/\,/,$ids)) {
                   12974: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12975:                if (
                   12976:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  12977:    eq $symb) {
                   12978:                    if (ref($encstate)) {
                   12979:                        $$encstate = $bighash{'encrypted_'.$id};
                   12980:                    }
1.620     albertel 12981: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  12982: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   12983:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  12984: 		       $okay=1;
1.1202    raeburn  12985:                        last;
1.582     albertel 12986: 		   }
                   12987: 	       }
1.216     www      12988: 	   }
                   12989:         }
1.213     www      12990: 	untie(%bighash);
                   12991:     }
                   12992:     return $okay;
1.31      www      12993: }
                   12994: 
1.210     www      12995: # --------------------------------------------------------------- Clean-up symb
                   12996: 
                   12997: sub symbclean {
                   12998:     my $symb=shift;
1.568     albertel 12999:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      13000: # remove version from map
                   13001:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      13002: 
1.210     www      13003: # remove version from URL
                   13004:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      13005: 
1.507     www      13006: # remove wrapper
                   13007: 
1.510     www      13008:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 13009:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      13010:     return $symb;
1.409     www      13011: }
                   13012: 
                   13013: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 13014: 
                   13015: sub encode_symb {
                   13016:     my ($map,$resid,$url)=@_;
                   13017:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   13018: }
1.409     www      13019: 
                   13020: sub decode_symb {
1.568     albertel 13021:     my $symb=shift;
                   13022:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   13023:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      13024:     return (&fixversion($map),$resid,&fixversion($url));
                   13025: }
                   13026: 
                   13027: sub fixversion {
                   13028:     my $fn=shift;
1.609     banghart 13029:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      13030:     my %bighash;
                   13031:     my $uri=&clutter($fn);
1.620     albertel 13032:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      13033: # is this cached?
1.599     albertel 13034:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      13035:     if (defined($cached)) { return $result; }
                   13036: # unfortunately not cached, or expired
1.620     albertel 13037:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      13038: 	    &GDBM_READER(),0640)) {
                   13039:  	if ($bighash{'version_'.$uri}) {
                   13040:  	    my $version=$bighash{'version_'.$uri};
1.444     www      13041:  	    unless (($version eq 'mostrecent') || 
                   13042: 		    ($version==&getversion($uri))) {
1.440     www      13043:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   13044:  	    }
                   13045:  	}
                   13046:  	untie %bighash;
1.413     www      13047:     }
1.599     albertel 13048:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      13049: }
                   13050: 
                   13051: sub deversion {
                   13052:     my $url=shift;
                   13053:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   13054:     return $url;
1.210     www      13055: }
                   13056: 
1.31      www      13057: # ------------------------------------------------------ Return symb list entry
                   13058: 
                   13059: sub symbread {
1.1282    raeburn  13060:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  13061:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  13062:     if (defined($env{$cache_str})) {
                   13063:         if ($ignorecachednull) {
                   13064:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   13065:         } else {
                   13066:             return $env{$cache_str};
                   13067:         }
                   13068:     }
1.242     www      13069: # no filename provided? try from environment
1.1265    raeburn  13070:     unless ($thisfn) {
1.620     albertel 13071:         if ($env{'request.symb'}) {
                   13072: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 13073: 	}
1.620     albertel 13074: 	$thisfn=$env{'request.filename'};
1.44      www      13075:     }
1.569     albertel 13076:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13077: # is that filename actually a symb? Verify, clean, and return
                   13078:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13079: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 13080: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13081: 	}
1.242     www      13082:     }
1.44      www      13083:     $thisfn=declutter($thisfn);
1.31      www      13084:     my %hash;
1.37      www      13085:     my %bighash;
                   13086:     my $syval='';
1.620     albertel 13087:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  13088:         my $targetfn = $thisfn;
1.609     banghart 13089:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  13090:             $targetfn = 'adm/wrapper/'.$thisfn;
                   13091:         }
1.687     albertel 13092: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   13093: 	    $targetfn=$1;
                   13094: 	}
1.620     albertel 13095:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 13096:                       &GDBM_READER(),0640)) {
1.481     raeburn  13097: 	    $syval=$hash{$targetfn};
1.37      www      13098:             untie(%hash);
                   13099:         }
                   13100: # ---------------------------------------------------------- There was an entry
                   13101:         if ($syval) {
1.601     albertel 13102: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13103: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13104: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13105: 		    #return $env{$cache_str}='';
1.601     albertel 13106: 		#}    
                   13107: 		#$syval.=$1;
                   13108: 	    #}
1.37      www      13109:         } else {
                   13110: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13111:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13112:                             &GDBM_READER(),0640)) {
1.37      www      13113: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13114:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13115:               unless ($ids) { 
                   13116:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13117:               }
                   13118:               unless ($ids) {
                   13119: # alias?
                   13120: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13121:               }
1.37      www      13122:               if ($ids) {
                   13123: # ------------------------------------------------------------------- Has ID(s)
                   13124:                  my @possibilities=split(/\,/,$ids);
1.39      www      13125:                  if ($#possibilities==0) {
                   13126: # ----------------------------------------------- There is only one possibility
1.37      www      13127: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13128: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13129: 						    $resid,$thisfn);
1.1282    raeburn  13130:                      if (ref($possibles) eq 'HASH') {
                   13131:                          $possibles->{$syval} = 1;    
                   13132:                      }
                   13133:                      if ($checkforblock) {
                   13134:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   13135:                          if (@blockers) {
                   13136:                              $syval = '';
                   13137:                              return;
                   13138:                          }
                   13139:                      }
                   13140:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      13141: # ------------------------------------------ There is more than one possibility
                   13142:                      my $realpossible=0;
1.800     albertel 13143:                      foreach my $id (@possibilities) {
                   13144: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  13145:                          my $canaccess;
                   13146:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13147:                              $canaccess = 1;
                   13148:                          } else { 
                   13149:                              $canaccess = &allowed('bre',$file);
                   13150:                          }
                   13151:                          if ($canaccess) {
                   13152:          		     my ($mapid,$resid)=split(/\./,$id);
                   13153:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13154:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13155: 						             $resid,$thisfn);
                   13156:                                  if (ref($possibles) eq 'HASH') {
                   13157:                                      $possibles->{$syval} = 1;
                   13158:                                  }
                   13159:                                  if ($checkforblock) {
                   13160:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   13161:                                      unless (@blockers > 0) {
                   13162:                                          $syval = $poss_syval;
                   13163:                                          $realpossible++;
                   13164:                                      }
                   13165:                                  } else {
                   13166:                                      $syval = $poss_syval;
                   13167:                                      $realpossible++;
                   13168:                                  }
                   13169:                              }
1.39      www      13170: 			 }
1.191     harris41 13171:                      }
1.39      www      13172: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13173:                  } else {
                   13174:                      $syval='';
1.37      www      13175:                  }
                   13176: 	      }
1.1282    raeburn  13177:               untie(%bighash);
1.481     raeburn  13178:            }
1.31      www      13179:         }
1.62      www      13180:         if ($syval) {
1.620     albertel 13181: 	    return $env{$cache_str}=$syval;
1.62      www      13182:         }
1.31      www      13183:     }
1.949     raeburn  13184:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13185:     return $env{$cache_str}='';
1.31      www      13186: }
                   13187: 
                   13188: # ---------------------------------------------------------- Return random seed
                   13189: 
1.32      www      13190: sub numval {
                   13191:     my $txt=shift;
                   13192:     $txt=~tr/A-J/0-9/;
                   13193:     $txt=~tr/a-j/0-9/;
                   13194:     $txt=~tr/K-T/0-9/;
                   13195:     $txt=~tr/k-t/0-9/;
                   13196:     $txt=~tr/U-Z/0-5/;
                   13197:     $txt=~tr/u-z/0-5/;
                   13198:     $txt=~s/\D//g;
1.564     albertel 13199:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13200:     return int($txt);
1.368     albertel 13201: }
                   13202: 
1.484     albertel 13203: sub numval2 {
                   13204:     my $txt=shift;
                   13205:     $txt=~tr/A-J/0-9/;
                   13206:     $txt=~tr/a-j/0-9/;
                   13207:     $txt=~tr/K-T/0-9/;
                   13208:     $txt=~tr/k-t/0-9/;
                   13209:     $txt=~tr/U-Z/0-5/;
                   13210:     $txt=~tr/u-z/0-5/;
                   13211:     $txt=~s/\D//g;
                   13212:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13213:     my $total;
                   13214:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13215:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13216:     return int($total);
                   13217: }
                   13218: 
1.575     albertel 13219: sub numval3 {
                   13220:     use integer;
                   13221:     my $txt=shift;
                   13222:     $txt=~tr/A-J/0-9/;
                   13223:     $txt=~tr/a-j/0-9/;
                   13224:     $txt=~tr/K-T/0-9/;
                   13225:     $txt=~tr/k-t/0-9/;
                   13226:     $txt=~tr/U-Z/0-5/;
                   13227:     $txt=~tr/u-z/0-5/;
                   13228:     $txt=~s/\D//g;
                   13229:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13230:     my $total;
                   13231:     foreach my $val (@txts) { $total+=$val; }
                   13232:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13233:     return $total;
                   13234: }
                   13235: 
1.675     albertel 13236: sub digest {
                   13237:     my ($data)=@_;
                   13238:     my $digest=&Digest::MD5::md5($data);
                   13239:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13240:     my ($e,$f);
                   13241:     {
                   13242:         use integer;
                   13243:         $e=($a+$b);
                   13244:         $f=($c+$d);
                   13245:         if ($_64bit) {
                   13246:             $e=(($e<<32)>>32);
                   13247:             $f=(($f<<32)>>32);
                   13248:         }
                   13249:     }
                   13250:     if (wantarray) {
                   13251: 	return ($e,$f);
                   13252:     } else {
                   13253: 	my $g;
                   13254: 	{
                   13255: 	    use integer;
                   13256: 	    $g=($e+$f);
                   13257: 	    if ($_64bit) {
                   13258: 		$g=(($g<<32)>>32);
                   13259: 	    }
                   13260: 	}
                   13261: 	return $g;
                   13262:     }
                   13263: }
                   13264: 
1.368     albertel 13265: sub latest_rnd_algorithm_id {
1.675     albertel 13266:     return '64bit5';
1.366     albertel 13267: }
1.32      www      13268: 
1.503     albertel 13269: sub get_rand_alg {
                   13270:     my ($courseid)=@_;
1.790     albertel 13271:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13272:     if ($courseid) {
1.620     albertel 13273: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13274:     }
                   13275:     return &latest_rnd_algorithm_id();
                   13276: }
                   13277: 
1.562     albertel 13278: sub validCODE {
                   13279:     my ($CODE)=@_;
                   13280:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13281:     return 0;
                   13282: }
                   13283: 
1.491     albertel 13284: sub getCODE {
1.620     albertel 13285:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13286:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13287: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13288: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13289: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13290:     }
                   13291:     return undef;
                   13292: }
1.1133    foxr     13293: #
                   13294: #  Determines the random seed for a specific context:
                   13295: #
                   13296: # parameters:
                   13297: #   symb      - in course context the symb for the seed.
                   13298: #   course_id - The course id of the form domain_coursenum.
                   13299: #   domain    - Domain for the user.
                   13300: #   course    - Course for the user.
                   13301: #   cenv      - environment of the course.
                   13302: #
                   13303: # NOTE:
                   13304: #   All parameters are picked out of the environment if missing
                   13305: #   or not defined.
                   13306: #   If a symb cannot be determined the current time is used instead.
                   13307: #
                   13308: #  For a given well defined symb, courside, domain, username,
                   13309: #  and course environment, the seed is reproducible.
                   13310: #
1.31      www      13311: sub rndseed {
1.1133    foxr     13312:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13313:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13314:     if (!defined($symb)) {
1.366     albertel 13315: 	unless ($symb=$wsymb) { return time; }
                   13316:     }
1.1146    foxr     13317:     if (!defined $courseid) { 
                   13318: 	$courseid=$wcourseid; 
                   13319:     }
                   13320:     if (!defined $domain) { $domain=$wdomain; }
                   13321:     if (!defined $username) { $username=$wusername }
1.1133    foxr     13322: 
                   13323:     my $which;
                   13324:     if (defined($cenv->{'rndseed'})) {
                   13325: 	$which = $cenv->{'rndseed'};
                   13326:     } else {
                   13327: 	$which =&get_rand_alg($courseid);
                   13328:     }
1.491     albertel 13329:     if (defined(&getCODE())) {
1.1133    foxr     13330: 
1.675     albertel 13331: 	if ($which eq '64bit5') {
                   13332: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   13333: 	} elsif ($which eq '64bit4') {
1.575     albertel 13334: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   13335: 	} else {
                   13336: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   13337: 	}
1.675     albertel 13338:     } elsif ($which eq '64bit5') {
                   13339: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 13340:     } elsif ($which eq '64bit4') {
                   13341: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 13342:     } elsif ($which eq '64bit3') {
                   13343: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 13344:     } elsif ($which eq '64bit2') {
                   13345: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13346:     } elsif ($which eq '64bit') {
                   13347: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13348:     }
                   13349:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13350: }
                   13351: 
                   13352: sub rndseed_32bit {
                   13353:     my ($symb,$courseid,$domain,$username)=@_;
                   13354:     {
                   13355: 	use integer;
                   13356: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13357: 	my $symbseed=numval($symb) << 22;
                   13358: 	my $namechck=unpack("%32C*",$username) << 17;
                   13359: 	my $nameseed=numval($username) << 12;
                   13360: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13361: 	my $courseseed=unpack("%32C*",$courseid);
                   13362: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13363: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13364: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13365: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13366: 	return $num;
                   13367:     }
                   13368: }
                   13369: 
                   13370: sub rndseed_64bit {
                   13371:     my ($symb,$courseid,$domain,$username)=@_;
                   13372:     {
                   13373: 	use integer;
                   13374: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13375: 	my $symbseed=numval($symb) << 10;
                   13376: 	my $namechck=unpack("%32S*",$username);
                   13377: 	
                   13378: 	my $nameseed=numval($username) << 21;
                   13379: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13380: 	my $courseseed=unpack("%32S*",$courseid);
                   13381: 	
                   13382: 	my $num1=$symbchck+$symbseed+$namechck;
                   13383: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13384: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13385: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13386: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13387: 	return "$num1,$num2";
1.155     albertel 13388:     }
1.366     albertel 13389: }
                   13390: 
1.443     albertel 13391: sub rndseed_64bit2 {
                   13392:     my ($symb,$courseid,$domain,$username)=@_;
                   13393:     {
                   13394: 	use integer;
                   13395: 	# strings need to be an even # of cahracters long, it it is odd the
                   13396:         # last characters gets thrown away
                   13397: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13398: 	my $symbseed=numval($symb) << 10;
                   13399: 	my $namechck=unpack("%32S*",$username.' ');
                   13400: 	
                   13401: 	my $nameseed=numval($username) << 21;
1.501     albertel 13402: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13403: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13404: 	
                   13405: 	my $num1=$symbchck+$symbseed+$namechck;
                   13406: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13407: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13408: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13409: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13410: 	return "$num1,$num2";
                   13411:     }
                   13412: }
                   13413: 
                   13414: sub rndseed_64bit3 {
                   13415:     my ($symb,$courseid,$domain,$username)=@_;
                   13416:     {
                   13417: 	use integer;
                   13418: 	# strings need to be an even # of cahracters long, it it is odd the
                   13419:         # last characters gets thrown away
                   13420: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13421: 	my $symbseed=numval2($symb) << 10;
                   13422: 	my $namechck=unpack("%32S*",$username.' ');
                   13423: 	
                   13424: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13425: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13426: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13427: 	
                   13428: 	my $num1=$symbchck+$symbseed+$namechck;
                   13429: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13430: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13431: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13432: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13433: 	
1.503     albertel 13434: 	return "$num1:$num2";
1.443     albertel 13435:     }
                   13436: }
                   13437: 
1.575     albertel 13438: sub rndseed_64bit4 {
                   13439:     my ($symb,$courseid,$domain,$username)=@_;
                   13440:     {
                   13441: 	use integer;
                   13442: 	# strings need to be an even # of cahracters long, it it is odd the
                   13443:         # last characters gets thrown away
                   13444: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13445: 	my $symbseed=numval3($symb) << 10;
                   13446: 	my $namechck=unpack("%32S*",$username.' ');
                   13447: 	
                   13448: 	my $nameseed=numval3($username) << 21;
                   13449: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13450: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13451: 	
                   13452: 	my $num1=$symbchck+$symbseed+$namechck;
                   13453: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13454: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13455: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13456: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13457: 	
1.575     albertel 13458: 	return "$num1:$num2";
                   13459:     }
                   13460: }
                   13461: 
1.675     albertel 13462: sub rndseed_64bit5 {
                   13463:     my ($symb,$courseid,$domain,$username)=@_;
                   13464:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13465:     return "$num1:$num2";
                   13466: }
                   13467: 
1.366     albertel 13468: sub rndseed_CODE_64bit {
                   13469:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13470:     {
1.366     albertel 13471: 	use integer;
1.443     albertel 13472: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13473: 	my $symbseed=numval2($symb);
1.491     albertel 13474: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13475: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13476: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13477: 	my $num1=$symbseed+$CODEchck;
                   13478: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13479: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13480: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13481: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13482: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13483: 	return "$num1:$num2";
1.366     albertel 13484:     }
                   13485: }
                   13486: 
1.575     albertel 13487: sub rndseed_CODE_64bit4 {
                   13488:     my ($symb,$courseid,$domain,$username)=@_;
                   13489:     {
                   13490: 	use integer;
                   13491: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13492: 	my $symbseed=numval3($symb);
                   13493: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13494: 	my $CODEseed=numval3(&getCODE());
                   13495: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13496: 	my $num1=$symbseed+$CODEchck;
                   13497: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13498: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13499: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13500: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13501: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13502: 	return "$num1:$num2";
                   13503:     }
                   13504: }
                   13505: 
1.675     albertel 13506: sub rndseed_CODE_64bit5 {
                   13507:     my ($symb,$courseid,$domain,$username)=@_;
                   13508:     my $code = &getCODE();
                   13509:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13510:     return "$num1:$num2";
                   13511: }
                   13512: 
1.366     albertel 13513: sub setup_random_from_rndseed {
                   13514:     my ($rndseed)=@_;
1.503     albertel 13515:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  13516:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13517:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13518:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13519:         } else {
                   13520:             &Math::Random::random_set_seed($num1,$num2);
                   13521:         }
1.366     albertel 13522:     } else {
                   13523: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13524:     }
1.36      albertel 13525: }
                   13526: 
1.474     albertel 13527: sub latest_receipt_algorithm_id {
1.835     albertel 13528:     return 'receipt3';
1.474     albertel 13529: }
                   13530: 
1.480     www      13531: sub recunique {
                   13532:     my $fucourseid=shift;
                   13533:     my $unique;
1.835     albertel 13534:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13535: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13536: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13537:     } else {
                   13538: 	$unique=$perlvar{'lonReceipt'};
                   13539:     }
                   13540:     return unpack("%32C*",$unique);
                   13541: }
                   13542: 
                   13543: sub recprefix {
                   13544:     my $fucourseid=shift;
                   13545:     my $prefix;
1.835     albertel 13546:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13547: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13548: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13549:     } else {
                   13550: 	$prefix=$perlvar{'lonHostID'};
                   13551:     }
                   13552:     return unpack("%32C*",$prefix);
                   13553: }
                   13554: 
1.76      www      13555: sub ireceipt {
1.474     albertel 13556:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13557: 
                   13558:     my $return =&recprefix($fucourseid).'-';
                   13559: 
                   13560:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13561: 	$env{'request.state'} eq 'construct') {
                   13562: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13563: 	return $return;
                   13564:     }
                   13565: 
1.76      www      13566:     my $cuname=unpack("%32C*",$funame);
                   13567:     my $cudom=unpack("%32C*",$fudom);
                   13568:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13569:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13570:     my $cunique=&recunique($fucourseid);
1.474     albertel 13571:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13572:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13573: 
1.790     albertel 13574: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13575: 			       
                   13576: 	$return.= ($cunique%$cuname+
                   13577: 		   $cunique%$cudom+
                   13578: 		   $cusymb%$cuname+
                   13579: 		   $cusymb%$cudom+
                   13580: 		   $cucourseid%$cuname+
                   13581: 		   $cucourseid%$cudom+
                   13582: 		   $cpart%$cuname+
                   13583: 		   $cpart%$cudom);
                   13584:     } else {
                   13585: 	$return.= ($cunique%$cuname+
                   13586: 		   $cunique%$cudom+
                   13587: 		   $cusymb%$cuname+
                   13588: 		   $cusymb%$cudom+
                   13589: 		   $cucourseid%$cuname+
                   13590: 		   $cucourseid%$cudom);
                   13591:     }
                   13592:     return $return;
1.76      www      13593: }
                   13594: 
                   13595: sub receipt {
1.474     albertel 13596:     my ($part)=@_;
1.790     albertel 13597:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13598:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13599: }
1.260     ng       13600: 
1.790     albertel 13601: sub whichuser {
                   13602:     my ($passedsymb)=@_;
                   13603:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13604:     if (defined($env{'form.grade_symb'})) {
                   13605: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13606: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13607: 	if (!$allowed &&
                   13608: 	    exists($env{'request.course.sec'}) &&
                   13609: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13610: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13611: 			      '/'.$env{'request.course.sec'});
                   13612: 	}
                   13613: 	if ($allowed) {
                   13614: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13615: 	    $courseid=$tmp_courseid;
                   13616: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13617: 	    ($name)=&get_env_multiple('form.grade_username');
                   13618: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13619: 	}
                   13620:     }
                   13621:     if (!$passedsymb) {
                   13622: 	$symb=&symbread();
                   13623:     } else {
                   13624: 	$symb=$passedsymb;
                   13625:     }
                   13626:     $courseid=$env{'request.course.id'};
                   13627:     $domain=$env{'user.domain'};
                   13628:     $name=$env{'user.name'};
                   13629:     if ($name eq 'public' && $domain eq 'public') {
                   13630: 	if (!defined($env{'form.username'})) {
                   13631: 	    $env{'form.username'}.=time.rand(10000000);
                   13632: 	}
                   13633: 	$name.=$env{'form.username'};
                   13634:     }
                   13635:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13636: 
                   13637: }
                   13638: 
1.36      albertel 13639: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13640: # returns either the contents of the file or 
                   13641: # -1 if the file doesn't exist
1.481     raeburn  13642: #
                   13643: # if the target is a file that was uploaded via DOCS, 
                   13644: # a check will be made to see if a current copy exists on the local server,
                   13645: # if it does this will be served, otherwise a copy will be retrieved from
                   13646: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13647: # the local server.   
1.472     albertel 13648: 
1.36      albertel 13649: sub getfile {
1.538     albertel 13650:     my ($file) = @_;
1.609     banghart 13651:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13652:     &repcopy($file);
                   13653:     return &readfile($file);
                   13654: }
                   13655: 
                   13656: sub repcopy_userfile {
                   13657:     my ($file)=@_;
1.1142    raeburn  13658:     my $londocroot = $perlvar{'lonDocRoot'};
                   13659:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13660:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13661:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13662: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13663:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13664:     if (-e "$file") {
1.828     www      13665: # we already have a local copy, check it out
1.538     albertel 13666: 	my @fileinfo = stat($file);
1.828     www      13667: 	my $rtncode;
                   13668: 	my $info;
1.538     albertel 13669: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13670: 	if ($lwpresp ne 'ok') {
1.828     www      13671: # there is no such file anymore, even though we had a local copy
1.482     albertel 13672: 	    if ($rtncode eq '404') {
1.538     albertel 13673: 		unlink($file);
1.482     albertel 13674: 	    }
                   13675: 	    return -1;
                   13676: 	}
                   13677: 	if ($info < $fileinfo[9]) {
1.828     www      13678: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13679: 	    return 'ok';
1.828     www      13680: 	} else {
                   13681: # the file is outdated, get rid of it
                   13682: 	    unlink($file);
1.482     albertel 13683: 	}
1.828     www      13684:     }
                   13685: # one way or the other, at this point, we don't have the file
                   13686: # construct the correct path for the file
                   13687:     my @parts = ($cdom,$cnum); 
                   13688:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13689: 	push @parts, split(/\//,$1);
                   13690:     }
                   13691:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13692:     foreach my $part (@parts) {
                   13693: 	$path .= '/'.$part;
                   13694: 	if (!-e $path) {
                   13695: 	    mkdir($path,0770);
1.482     albertel 13696: 	}
                   13697:     }
1.828     www      13698: # now the path exists for sure
                   13699: # get a user agent
                   13700:     my $transferfile=$file.'.in.transfer';
                   13701: # FIXME: this should flock
                   13702:     if (-e $transferfile) { return 'ok'; }
                   13703:     my $request;
                   13704:     $uri=~s/^\///;
1.980     raeburn  13705:     my $homeserver = &homeserver($cnum,$cdom);
1.1398    raeburn  13706:     my $hostname = &hostname($homeserver);
1.980     raeburn  13707:     my $protocol = $protocol{$homeserver};
                   13708:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  13709:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345    raeburn  13710:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      13711: # did it work?
                   13712:     if ($response->is_error()) {
                   13713: 	unlink($transferfile);
                   13714: 	&logthis("Userfile repcopy failed for $uri");
                   13715: 	return -1;
                   13716:     }
                   13717: # worked, rename the transfer file
                   13718:     rename($transferfile,$file);
1.607     raeburn  13719:     return 'ok';
1.481     raeburn  13720: }
                   13721: 
1.517     albertel 13722: sub tokenwrapper {
                   13723:     my $uri=shift;
1.980     raeburn  13724:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13725:     $uri=~s|^/||;
1.620     albertel 13726:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13727:     my $token=$1;
1.552     albertel 13728:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13729:     if ($udom && $uname && $file) {
                   13730: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13731:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13732:         my $homeserver = &homeserver($uname,$udom);
1.1397    raeburn  13733:         my $hostname = &hostname($homeserver);
1.980     raeburn  13734:         my $protocol = $protocol{$homeserver};
                   13735:         $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  13736:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13737:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13738:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13739:     } else {
                   13740:         return '/adm/notfound.html';
                   13741:     }
                   13742: }
                   13743: 
1.828     www      13744: # call with reqtype HEAD: get last modification time
                   13745: # call with reqtype GET: get the file contents
                   13746: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13747: #
1.481     raeburn  13748: sub getuploaded {
                   13749:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13750:     $uri=~s/^\///;
1.980     raeburn  13751:     my $homeserver = &homeserver($cnum,$cdom);
1.1397    raeburn  13752:     my $hostname = &hostname($homeserver);
1.980     raeburn  13753:     my $protocol = $protocol{$homeserver};
                   13754:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  13755:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13756:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  13757:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  13758:     $$rtncode = $response->code;
1.482     albertel 13759:     if (! $response->is_success()) {
                   13760: 	return 'failed';
                   13761:     }      
                   13762:     if ($reqtype eq 'HEAD') {
1.486     www      13763: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13764:     } elsif ($reqtype eq 'GET') {
                   13765: 	$$info = $response->content;
1.472     albertel 13766:     }
1.482     albertel 13767:     return 'ok';
1.36      albertel 13768: }
                   13769: 
1.481     raeburn  13770: sub readfile {
                   13771:     my $file = shift;
                   13772:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13773:     my $fh;
1.1359    raeburn  13774:     open($fh,"<",$file);
1.481     raeburn  13775:     my $a='';
1.800     albertel 13776:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13777:     return $a;
                   13778: }
                   13779: 
1.36      albertel 13780: sub filelocation {
1.590     banghart 13781:     my ($dir,$file) = @_;
                   13782:     my $location;
                   13783:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13784: 
                   13785:     if ($file =~ m-^/adm/-) {
                   13786: 	$file=~s-^/adm/wrapper/-/-;
                   13787: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13788:     }
1.882     albertel 13789: 
1.1139    www      13790:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13791:         $location = $file;
1.609     banghart 13792:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13793:         my ($udom,$uname,$filename)=
1.811     albertel 13794:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13795:         my $home=&homeserver($uname,$udom);
                   13796:         my $is_me=0;
                   13797:         my @ids=&current_machine_ids();
                   13798:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13799:         if ($is_me) {
1.1117    foxr     13800:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13801:         } else {
                   13802:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13803:   	      $udom.'/'.$uname.'/'.$filename;
                   13804:         }
1.882     albertel 13805:     } elsif ($file =~ m-^/adm/-) {
                   13806: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13807:     } else {
                   13808:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13809:         $file=~s:^/(res|priv)/:/:;
                   13810:         my $space=$1;
1.590     banghart 13811:         if ( !( $file =~ m:^/:) ) {
                   13812:             $location = $dir. '/'.$file;
                   13813:         } else {
1.1142    raeburn  13814:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13815:         }
1.59      albertel 13816:     }
1.590     banghart 13817:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13818:     while ($location=~m{/\.\./}) {
                   13819: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13820: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13821: 	} else {
                   13822: 	    $location=~ s{/\.\./}{/}g;
                   13823: 	}
                   13824:     } #remove dir/..
1.590     banghart 13825:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13826:     return $location;
1.46      www      13827: }
1.36      albertel 13828: 
1.46      www      13829: sub hreflocation {
                   13830:     my ($dir,$file)=@_;
1.980     raeburn  13831:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13832: 	$file=filelocation($dir,$file);
1.700     albertel 13833:     } elsif ($file=~m-^/adm/-) {
                   13834: 	$file=~s-^/adm/wrapper/-/-;
                   13835: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13836:     }
                   13837:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13838: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13839:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13840: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13841: 	        {/uploaded/$1/$2/}x;
1.46      www      13842:     }
1.913     albertel 13843:     if ($file=~ m{^/userfiles/}) {
                   13844: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13845:     }
1.462     albertel 13846:     return $file;
1.465     albertel 13847: }
                   13848: 
1.1139    www      13849: 
                   13850: 
                   13851: 
                   13852: 
1.465     albertel 13853: sub current_machine_domains {
1.853     albertel 13854:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13855: }
                   13856: 
                   13857: sub machine_domains {
                   13858:     my ($hostname) = @_;
1.465     albertel 13859:     my @domains;
1.838     albertel 13860:     my %hostname = &all_hostnames();
1.465     albertel 13861:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13862: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13863: 	if ($hostname eq $name) {
1.844     albertel 13864: 	    push(@domains,&host_domain($id));
1.465     albertel 13865: 	}
                   13866:     }
                   13867:     return @domains;
                   13868: }
                   13869: 
                   13870: sub current_machine_ids {
1.853     albertel 13871:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13872: }
                   13873: 
                   13874: sub machine_ids {
                   13875:     my ($hostname) = @_;
                   13876:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13877:     my @ids;
1.888     albertel 13878:     my %name_to_host = &all_names();
1.889     albertel 13879:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13880: 	return @{ $name_to_host{$hostname} };
                   13881:     }
                   13882:     return;
1.31      www      13883: }
                   13884: 
1.824     raeburn  13885: sub additional_machine_domains {
                   13886:     my @domains;
1.1359    raeburn  13887:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13888:     while( my $line = <$fh>) {
                   13889:         $line =~ s/\s//g;
                   13890:         push(@domains,$line);
                   13891:     }
                   13892:     return @domains;
                   13893: }
                   13894: 
                   13895: sub default_login_domain {
                   13896:     my $domain = $perlvar{'lonDefDomain'};
                   13897:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13898:     foreach my $posdom (&current_machine_domains(),
                   13899:                         &additional_machine_domains()) {
                   13900:         if (lc($posdom) eq lc($testdomain)) {
                   13901:             $domain=$posdom;
                   13902:             last;
                   13903:         }
                   13904:     }
                   13905:     return $domain;
                   13906: }
                   13907: 
1.1398    raeburn  13908: sub uses_sts {
                   13909:     my ($ignore_cache) = @_;
                   13910:     my $lonhost = $perlvar{'lonHostID'};
                   13911:     my $hostname = &hostname($lonhost);
                   13912:     my $sts_on;
                   13913:     if ($protocol{$lonhost} eq 'https') {
                   13914:         my $cachetime = 12*3600;
                   13915:         if (!$ignore_cache) {
                   13916:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13917:             if (defined($cached)) {
                   13918:                 return $sts_on;
                   13919:             }
                   13920:         }
                   13921:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13922:         my $request=new HTTP::Request('HEAD',$url);
                   13923:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
                   13924:         if ($response->is_success) {
                   13925:             my $has_sts = $response->header('Strict-Transport-Security');
                   13926:             if ($has_sts eq '') {
                   13927:                 $sts_on = 0;
                   13928:             } else {
                   13929:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13930:                     my $maxage = $1;
                   13931:                     if ($maxage) {
                   13932:                         $sts_on = 1;
                   13933:                     } else {
                   13934:                         $sts_on = 0;
                   13935:                     }
                   13936:                 } else {
                   13937:                     $sts_on = 0;
                   13938:                 }
                   13939:             }
                   13940:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13941:         }
                   13942:     }
                   13943:     return;
                   13944: }
                   13945: 
1.31      www      13946: # ------------------------------------------------------------- Declutters URLs
                   13947: 
                   13948: sub declutter {
                   13949:     my $thisfn=shift;
1.569     albertel 13950:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  13951:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13952:         $thisfn=~s{^/home/httpd/html}{};
                   13953:     }
1.31      www      13954:     $thisfn=~s/^\///;
1.697     albertel 13955:     $thisfn=~s|^adm/wrapper/||;
                   13956:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13957:     $thisfn=~s/^res\///;
1.1172    bisitz   13958:     $thisfn=~s/^priv\///;
1.1032    raeburn  13959:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13960:         $thisfn=~s/\?.+$//;
                   13961:     }
1.268     www      13962:     return $thisfn;
                   13963: }
                   13964: 
                   13965: # ------------------------------------------------------------- Clutter up URLs
                   13966: 
                   13967: sub clutter {
                   13968:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13969:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13970: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13971:        $thisfn='/res'.$thisfn; 
                   13972:     }
1.1031    raeburn  13973:     if ($thisfn !~m|^/adm|) {
                   13974: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13975: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13976: 	} else {
                   13977: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13978: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13979: 	    if ($embstyle eq 'ssi'
                   13980: 		|| ($embstyle eq 'hdn')
                   13981: 		|| ($embstyle eq 'rat')
                   13982: 		|| ($embstyle eq 'prv')
                   13983: 		|| ($embstyle eq 'ign')) {
                   13984: 		#do nothing with these
                   13985: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13986: 		|| ($embstyle eq 'emb')
                   13987: 		|| ($embstyle eq 'wrp')) {
                   13988: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13989: 	    } elsif ($embstyle eq 'unk'
                   13990: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13991: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13992: 	    } else {
1.718     www      13993: #		&logthis("Got a blank emb style");
1.695     albertel 13994: 	    }
1.694     albertel 13995: 	}
1.1343    raeburn  13996:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  13997:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13998:     }
1.31      www      13999:     return $thisfn;
1.12      www      14000: }
                   14001: 
1.787     albertel 14002: sub clutter_with_no_wrapper {
                   14003:     my $uri = &clutter(shift);
                   14004:     if ($uri =~ m-^/adm/-) {
                   14005: 	$uri =~ s-^/adm/wrapper/-/-;
                   14006: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14007:     }
                   14008:     return $uri;
                   14009: }
                   14010: 
1.557     albertel 14011: sub freeze_escape {
                   14012:     my ($value)=@_;
                   14013:     if (ref($value)) {
                   14014: 	$value=&nfreeze($value);
                   14015: 	return '__FROZEN__'.&escape($value);
                   14016:     }
                   14017:     return &escape($value);
                   14018: }
                   14019: 
1.11      www      14020: 
1.557     albertel 14021: sub thaw_unescape {
                   14022:     my ($value)=@_;
                   14023:     if ($value =~ /^__FROZEN__/) {
                   14024: 	substr($value,0,10,undef);
                   14025: 	$value=&unescape($value);
                   14026: 	return &thaw($value);
                   14027:     }
                   14028:     return &unescape($value);
                   14029: }
                   14030: 
1.436     albertel 14031: sub correct_line_ends {
                   14032:     my ($result)=@_;
                   14033:     $$result =~s/\r\n/\n/mg;
                   14034:     $$result =~s/\r/\n/mg;
1.415     albertel 14035: }
1.1       albertel 14036: # ================================================================ Main Program
                   14037: 
1.184     www      14038: sub goodbye {
1.204     albertel 14039:    &logthis("Starting Shut down");
1.443     albertel 14040: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14041:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14042: #converted
1.599     albertel 14043: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14044:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14045: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   14046: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 14047: #1.1 only
1.870     albertel 14048: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   14049: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   14050: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   14051: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   14052:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 14053:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   14054:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      14055:    &flushcourselogs();
                   14056:    &logthis("Shutting down");
                   14057: }
                   14058: 
1.852     albertel 14059: sub get_dns {
1.1210    raeburn  14060:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 14061:     if (!$ignore_cache) {
                   14062: 	my ($content,$cached)=
                   14063: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   14064: 	if ($cached) {
1.1210    raeburn  14065: 	    &$func($content,$hashref);
1.869     albertel 14066: 	    return;
                   14067: 	}
                   14068:     }
                   14069: 
                   14070:     my %alldns;
1.1379    raeburn  14071:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   14072:         foreach my $dns (<$config>) {
                   14073: 	    next if ($dns !~ /^\^(\S*)/x);
                   14074:             my $line = $1;
                   14075:             my ($host,$protocol) = split(/:/,$line);
                   14076:             if ($protocol ne 'https') {
                   14077:                 $protocol = 'http';
                   14078:             }
                   14079: 	    $alldns{$host} = $protocol;
1.979     raeburn  14080:         }
1.1379    raeburn  14081:         close($config);
1.869     albertel 14082:     }
                   14083:     while (%alldns) {
1.1263    raeburn  14084: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979     raeburn  14085: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345    raeburn  14086:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979     raeburn  14087:         delete($alldns{$dns});
1.852     albertel 14088: 	next if ($response->is_error());
1.1379    raeburn  14089:         if ($url eq '/adm/dns/loncapaCRL') {
                   14090:             return &$func($response);
                   14091:         } else {
                   14092: 	    my @content = split("\n",$response->content);
                   14093: 	    unless ($nocache) {
                   14094: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   14095: 	    }
                   14096: 	    &$func(\@content,$hashref);
                   14097:             return;
                   14098:         }
                   14099:     }
                   14100:     my $which = (split('/',$url,4))[3];
                   14101:     if ($which eq 'loncapaCRL') {
                   14102:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   14103:         if (-e $diskfile) {
                   14104:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   14105:         } else {
                   14106:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   14107:         }
                   14108:     } else {
                   14109:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   14110:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   14111:             my @content = <$config>;
                   14112:             close($config);
                   14113:             &$func(\@content,$hashref);
                   14114:         }
1.852     albertel 14115:     }
1.1210    raeburn  14116:     return;
                   14117: }
                   14118: 
                   14119: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  14120: sub parse_dns_checksums_tab {
1.1210    raeburn  14121:     my ($lines,$hashref) = @_;
1.1264    raeburn  14122:     my $lonhost = $perlvar{'lonHostID'};
                   14123:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  14124:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  14125:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14126:     my $webconfdir = '/etc/httpd/conf';
                   14127:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14128:         $webconfdir = '/etc/apache2';
                   14129:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14130:         if ($1 >= 10) {
                   14131:             $webconfdir = '/etc/apache2';
                   14132:         }
                   14133:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14134:         if ($1 >= 10.0) {
                   14135:             $webconfdir = '/etc/apache2';
                   14136:         }
                   14137:     }
1.1210    raeburn  14138:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14139:     my (%chksum,%revnum);
                   14140:     if (ref($lines) eq 'ARRAY') {
                   14141:         chomp(@{$lines});
1.1238    raeburn  14142:         my $version = shift(@{$lines});
                   14143:         if ($version eq $release) {  
1.1210    raeburn  14144:             foreach my $line (@{$lines}) {
1.1238    raeburn  14145:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  14146:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14147:                     if ($webconfdir eq '/etc/apache2') {
                   14148:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14149:                     }
                   14150:                 }
1.1238    raeburn  14151:                 $chksum{$file} = $shasum;
                   14152:                 $revnum{$file} = $version;
1.1210    raeburn  14153:             }
                   14154:             if (ref($hashref) eq 'HASH') {
                   14155:                 %{$hashref} = (
                   14156:                                 sums     => \%chksum,
                   14157:                                 versions => \%revnum,
                   14158:                               );
                   14159:             }
                   14160:         }
                   14161:     }
1.869     albertel 14162:     return;
1.852     albertel 14163: }
1.1210    raeburn  14164: 
                   14165: sub fetch_dns_checksums {
1.1238    raeburn  14166:     my %checksums;
                   14167:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  14168:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  14169:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14170:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  14171:              \%checksums);
1.1210    raeburn  14172:     return \%checksums;
                   14173: }
                   14174: 
1.1379    raeburn  14175: sub fetch_crl_pemfile {
                   14176:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   14177: }
                   14178: 
                   14179: sub save_crl_pem {
                   14180:     my ($response) = @_;
1.1380    raeburn  14181:     my ($msg,$hadchanges);
1.1379    raeburn  14182:     if (ref($response)) {
                   14183:         my $now = time;
                   14184:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   14185:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   14186:         if (open(my $fh,'>',"$tmpcrl")) {
                   14187:             print $fh $response->content;
                   14188:             close($fh);
                   14189:             if (-e $lonca) {
                   14190:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   14191:                     my $check = <PIPE>;
                   14192:                     close(PIPE);
                   14193:                     chomp($check);
                   14194:                     if ($check eq 'verify OK') {
                   14195:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  14196:                         my $backup;
1.1379    raeburn  14197:                         if (-e $dest) {
1.1380    raeburn  14198:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   14199:                                 $backup = 'ok';
                   14200:                             }
1.1379    raeburn  14201:                         }
                   14202:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   14203:                             $msg = 'ok';
1.1380    raeburn  14204:                             if ($backup) {
                   14205:                                 my (%oldnums,%newnums);
                   14206:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   14207:                                     while (<PIPE>) {
                   14208:                                         $oldnums{(split(/:/))[1]} = 1;
                   14209:                                     }
                   14210:                                     close(PIPE);
                   14211:                                 }
                   14212:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   14213:                                     while(<PIPE>) {
                   14214:                                         $newnums{(split(/:/))[1]} = 1;
                   14215:                                     }
                   14216:                                     close(PIPE);
                   14217:                                 }
                   14218:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   14219:                                     unless (exists($oldnums{$key})) {
                   14220:                                         $hadchanges = 1;
                   14221:                                         last;
                   14222:                                     }
                   14223:                                 }
                   14224:                                 unless ($hadchanges) {
                   14225:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   14226:                                         unless (exists($newnums{$key})) {
                   14227:                                             $hadchanges = 1;
                   14228:                                             last;
                   14229:                                         }
                   14230:                                     }
                   14231:                                 }
                   14232:                             }
1.1379    raeburn  14233:                         }
                   14234:                     } else {
                   14235:                         unlink($tmpcrl);
                   14236:                     }
                   14237:                 } else {
                   14238:                     unlink($tmpcrl);
                   14239:                 }
                   14240:             } else {
                   14241:                 unlink($tmpcrl);
                   14242:             }
                   14243:         }
                   14244:     }
1.1380    raeburn  14245:     return ($msg,$hadchanges);
1.1379    raeburn  14246: }
                   14247: 
1.327     albertel 14248: # ------------------------------------------------------------ Read domain file
                   14249: {
1.852     albertel 14250:     my $loaded;
1.846     albertel 14251:     my %domain;
                   14252: 
1.852     albertel 14253:     sub parse_domain_tab {
                   14254: 	my ($lines) = @_;
                   14255: 	foreach my $line (@$lines) {
                   14256: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      14257: 
1.846     albertel 14258: 	    chomp($line);
1.852     albertel 14259: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 14260: 	    my %this_domain;
                   14261: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   14262: 			       'lang_def', 'city', 'longi', 'lati',
                   14263: 			       'primary') {
                   14264: 		$this_domain{$field} = shift(@elements);
                   14265: 	    }
                   14266: 	    $domain{$name} = \%this_domain;
1.852     albertel 14267: 	}
                   14268:     }
1.864     albertel 14269: 
                   14270:     sub reset_domain_info {
                   14271: 	undef($loaded);
                   14272: 	undef(%domain);
                   14273:     }
                   14274: 
1.852     albertel 14275:     sub load_domain_tab {
1.1293    raeburn  14276: 	my ($ignore_cache,$nocache) = @_;
                   14277: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 14278: 	my $fh;
1.1359    raeburn  14279: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 14280: 	    my @lines = <$fh>;
                   14281: 	    &parse_domain_tab(\@lines);
1.448     albertel 14282: 	}
1.852     albertel 14283: 	close($fh);
                   14284: 	$loaded = 1;
1.327     albertel 14285:     }
1.846     albertel 14286: 
                   14287:     sub domain {
1.852     albertel 14288: 	&load_domain_tab() if (!$loaded);
                   14289: 
1.846     albertel 14290: 	my ($name,$what) = @_;
                   14291: 	return if ( !exists($domain{$name}) );
                   14292: 
                   14293: 	if (!$what) {
                   14294: 	    return $domain{$name}{'description'};
                   14295: 	}
                   14296: 	return $domain{$name}{$what};
                   14297:     }
1.974     raeburn  14298: 
                   14299:     sub domain_info {
                   14300:         &load_domain_tab() if (!$loaded);
                   14301:         return %domain;
                   14302:     }
                   14303: 
1.327     albertel 14304: }
                   14305: 
                   14306: 
1.1       albertel 14307: # ------------------------------------------------------------- Read hosts file
                   14308: {
1.838     albertel 14309:     my %hostname;
1.844     albertel 14310:     my %hostdom;
1.845     albertel 14311:     my %libserv;
1.852     albertel 14312:     my $loaded;
1.888     albertel 14313:     my %name_to_host;
1.1074    raeburn  14314:     my %internetdom;
1.1107    raeburn  14315:     my %LC_dns_serv;
1.852     albertel 14316: 
                   14317:     sub parse_hosts_tab {
                   14318: 	my ($file) = @_;
                   14319: 	foreach my $configline (@$file) {
                   14320: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  14321:             chomp($configline);
                   14322: 	    if ($configline =~ /^\^/) {
                   14323:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   14324:                     $LC_dns_serv{$1} = 1;
                   14325:                 }
                   14326:                 next;
                   14327:             }
1.1074    raeburn  14328: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 14329: 	    $name=~s/\s//g;
                   14330: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  14331:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   14332:                     my $curr = $hostname{$id};
                   14333:                     my $skip;
                   14334:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   14335:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   14336:                             $skip = 1;
                   14337:                         } else {
                   14338:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   14339:                         }
                   14340:                     }
                   14341:                     unless ($skip) {
                   14342:                         push(@{$name_to_host{$name}},$id);
                   14343:                     }
                   14344:                 } else {
                   14345:                     push(@{$name_to_host{$name}},$id);
                   14346:                 }
1.852     albertel 14347: 		$hostname{$id}=$name;
                   14348: 		$hostdom{$id}=$domain;
                   14349: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  14350:                 if (defined($protocol)) {
                   14351:                     if ($protocol eq 'https') {
                   14352:                         $protocol{$id} = $protocol;
                   14353:                     } else {
                   14354:                         $protocol{$id} = 'http'; 
                   14355:                     }
1.968     raeburn  14356:                 } else {
1.969     raeburn  14357:                     $protocol{$id} = 'http';
1.968     raeburn  14358:                 }
1.1074    raeburn  14359:                 if (defined($intdom)) {
                   14360:                     $internetdom{$id} = $intdom;
                   14361:                 }
1.852     albertel 14362: 	    }
                   14363: 	}
                   14364:     }
1.864     albertel 14365:     
                   14366:     sub reset_hosts_info {
1.897     albertel 14367: 	&purge_remembered();
1.864     albertel 14368: 	&reset_domain_info();
                   14369: 	&reset_hosts_ip_info();
1.1339    raeburn  14370:         undef(%internetdom);
1.892     albertel 14371: 	undef(%name_to_host);
1.864     albertel 14372: 	undef(%hostname);
                   14373: 	undef(%hostdom);
                   14374: 	undef(%libserv);
                   14375: 	undef($loaded);
                   14376:     }
1.1       albertel 14377: 
1.852     albertel 14378:     sub load_hosts_tab {
1.1293    raeburn  14379: 	my ($ignore_cache,$nocache) = @_;
                   14380: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  14381: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 14382: 	my @config = <$config>;
                   14383: 	&parse_hosts_tab(\@config);
                   14384: 	close($config);
                   14385: 	$loaded=1;
1.1       albertel 14386:     }
1.852     albertel 14387: 
1.838     albertel 14388:     sub hostname {
1.852     albertel 14389: 	&load_hosts_tab() if (!$loaded);
                   14390: 
1.838     albertel 14391: 	my ($lonid) = @_;
                   14392: 	return $hostname{$lonid};
                   14393:     }
1.845     albertel 14394: 
1.838     albertel 14395:     sub all_hostnames {
1.852     albertel 14396: 	&load_hosts_tab() if (!$loaded);
                   14397: 
1.838     albertel 14398: 	return %hostname;
                   14399:     }
1.845     albertel 14400: 
1.888     albertel 14401:     sub all_names {
1.1293    raeburn  14402:         my ($ignore_cache,$nocache) = @_;
                   14403: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 14404: 
                   14405: 	return %name_to_host;
                   14406:     }
                   14407: 
1.974     raeburn  14408:     sub all_host_domain {
                   14409:         &load_hosts_tab() if (!$loaded);
                   14410:         return %hostdom;
                   14411:     }
                   14412: 
1.1339    raeburn  14413:     sub all_host_intdom {
                   14414:         &load_hosts_tab() if (!$loaded);
                   14415:         return %internetdom;
                   14416:     }
                   14417: 
1.845     albertel 14418:     sub is_library {
1.852     albertel 14419: 	&load_hosts_tab() if (!$loaded);
                   14420: 
1.845     albertel 14421: 	return exists($libserv{$_[0]});
                   14422:     }
                   14423: 
                   14424:     sub all_library {
1.852     albertel 14425: 	&load_hosts_tab() if (!$loaded);
                   14426: 
1.845     albertel 14427: 	return %libserv;
                   14428:     }
                   14429: 
1.1062    droeschl 14430:     sub unique_library {
                   14431: 	#2x reverse removes all hostnames that appear more than once
                   14432:         my %unique = reverse &all_library();
                   14433:         return reverse %unique;
                   14434:     }
                   14435: 
1.841     albertel 14436:     sub get_servers {
1.852     albertel 14437: 	&load_hosts_tab() if (!$loaded);
                   14438: 
1.841     albertel 14439: 	my ($domain,$type) = @_;
                   14440: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14441: 	                                          : %hostname;
                   14442: 	my %result;
1.842     albertel 14443: 	if (ref($domain) eq 'ARRAY') {
                   14444: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14445: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14446: 		    $result{$host} = $hostname;
                   14447: 		}
                   14448: 	    }
                   14449: 	} else {
                   14450: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14451: 		if ($hostdom{$host} eq $domain) {
                   14452: 		    $result{$host} = $hostname;
                   14453: 		}
1.841     albertel 14454: 	    }
                   14455: 	}
                   14456: 	return %result;
                   14457:     }
1.845     albertel 14458: 
1.1062    droeschl 14459:     sub get_unique_servers {
                   14460:         my %unique = reverse &get_servers(@_);
                   14461: 	return reverse %unique;
                   14462:     }
                   14463: 
1.844     albertel 14464:     sub host_domain {
1.852     albertel 14465: 	&load_hosts_tab() if (!$loaded);
                   14466: 
1.844     albertel 14467: 	my ($lonid) = @_;
                   14468: 	return $hostdom{$lonid};
                   14469:     }
                   14470: 
1.841     albertel 14471:     sub all_domains {
1.852     albertel 14472: 	&load_hosts_tab() if (!$loaded);
                   14473: 
1.841     albertel 14474: 	my %seen;
                   14475: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14476: 	return @uniq;
                   14477:     }
1.1074    raeburn  14478: 
                   14479:     sub internet_dom {
                   14480:         &load_hosts_tab() if (!$loaded);
                   14481: 
                   14482:         my ($lonid) = @_;
                   14483:         return $internetdom{$lonid};
                   14484:     }
1.1107    raeburn  14485: 
                   14486:     sub is_LC_dns {
                   14487:         &load_hosts_tab() if (!$loaded);
                   14488: 
                   14489:         my ($hostname) = @_;
                   14490:         return exists($LC_dns_serv{$hostname});
                   14491:     }
                   14492: 
1.1       albertel 14493: }
                   14494: 
1.847     albertel 14495: { 
                   14496:     my %iphost;
1.856     albertel 14497:     my %name_to_ip;
                   14498:     my %lonid_to_ip;
1.869     albertel 14499: 
1.847     albertel 14500:     sub get_hosts_from_ip {
                   14501: 	my ($ip) = @_;
                   14502: 	my %iphosts = &get_iphost();
                   14503: 	if (ref($iphosts{$ip})) {
                   14504: 	    return @{$iphosts{$ip}};
                   14505: 	}
                   14506: 	return;
1.839     albertel 14507:     }
1.864     albertel 14508:     
                   14509:     sub reset_hosts_ip_info {
                   14510: 	undef(%iphost);
                   14511: 	undef(%name_to_ip);
                   14512: 	undef(%lonid_to_ip);
                   14513:     }
1.856     albertel 14514: 
                   14515:     sub get_host_ip {
                   14516: 	my ($lonid) = @_;
                   14517: 	if (exists($lonid_to_ip{$lonid})) {
                   14518: 	    return $lonid_to_ip{$lonid};
                   14519: 	}
                   14520: 	my $name=&hostname($lonid);
                   14521:    	my $ip = gethostbyname($name);
                   14522: 	return if (!$ip || length($ip) ne 4);
                   14523: 	$ip=inet_ntoa($ip);
                   14524: 	$name_to_ip{$name}   = $ip;
                   14525: 	$lonid_to_ip{$lonid} = $ip;
                   14526: 	return $ip;
                   14527:     }
1.847     albertel 14528:     
                   14529:     sub get_iphost {
1.1293    raeburn  14530: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14531: 
1.869     albertel 14532: 	if (!$ignore_cache) {
                   14533: 	    if (%iphost) {
                   14534: 		return %iphost;
                   14535: 	    }
                   14536: 	    my ($ip_info,$cached)=
                   14537: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14538: 	    if ($cached) {
                   14539: 		%iphost      = %{$ip_info->[0]};
                   14540: 		%name_to_ip  = %{$ip_info->[1]};
                   14541: 		%lonid_to_ip = %{$ip_info->[2]};
                   14542: 		return %iphost;
                   14543: 	    }
                   14544: 	}
1.894     albertel 14545: 
                   14546: 	# get yesterday's info for fallback
                   14547: 	my %old_name_to_ip;
                   14548: 	my ($ip_info,$cached)=
                   14549: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14550: 	if ($cached) {
                   14551: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14552: 	}
                   14553: 
1.1293    raeburn  14554: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14555: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14556: 	    my $ip;
                   14557: 	    if (!exists($name_to_ip{$name})) {
                   14558: 		$ip = gethostbyname($name);
                   14559: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14560: 		    if (defined($old_name_to_ip{$name})) {
                   14561: 			$ip = $old_name_to_ip{$name};
                   14562: 			&logthis("Can't find $name defaulting to old $ip");
                   14563: 		    } else {
                   14564: 			&logthis("Name $name no IP found");
                   14565: 			next;
                   14566: 		    }
                   14567: 		} else {
                   14568: 		    $ip=inet_ntoa($ip);
1.847     albertel 14569: 		}
                   14570: 		$name_to_ip{$name} = $ip;
                   14571: 	    } else {
                   14572: 		$ip = $name_to_ip{$name};
1.653     albertel 14573: 	    }
1.888     albertel 14574: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14575: 		$lonid_to_ip{$id} = $ip;
                   14576: 	    }
                   14577: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14578: 	}
1.1293    raeburn  14579:         unless ($nocache) {
                   14580: 	    &do_cache_new('iphost','iphost',
                   14581: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14582: 		          48*60*60);
                   14583:         }
1.869     albertel 14584: 
1.847     albertel 14585: 	return %iphost;
1.598     albertel 14586:     }
                   14587: 
1.992     raeburn  14588:     #
                   14589:     #  Given a DNS returns the loncapa host name for that DNS 
                   14590:     # 
                   14591:     sub host_from_dns {
                   14592:         my ($dns) = @_;
                   14593:         my @hosts;
                   14594:         my $ip;
                   14595: 
1.993     raeburn  14596:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14597:             $ip = $name_to_ip{$dns};
                   14598:         }
                   14599:         if (!$ip) {
                   14600:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14601:             if (length($ip) == 4) { 
                   14602: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14603:             }
                   14604:         }
                   14605:         if ($ip) {
                   14606: 	    @hosts = get_hosts_from_ip($ip);
                   14607: 	    return $hosts[0];
                   14608:         }
                   14609:         return undef;
1.986     foxr     14610:     }
1.992     raeburn  14611: 
1.1074    raeburn  14612:     sub get_internet_names {
                   14613:         my ($lonid) = @_;
                   14614:         return if ($lonid eq '');
                   14615:         my ($idnref,$cached)=
                   14616:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14617:         if ($cached) {
                   14618:             return $idnref;
                   14619:         }
                   14620:         my $ip = &get_host_ip($lonid);
                   14621:         my @hosts = &get_hosts_from_ip($ip);
                   14622:         my %iphost = &get_iphost();
                   14623:         my (@idns,%seen);
                   14624:         foreach my $id (@hosts) {
                   14625:             my $dom = &host_domain($id);
                   14626:             my $prim_id = &domain($dom,'primary');
                   14627:             my $prim_ip = &get_host_ip($prim_id);
                   14628:             next if ($seen{$prim_ip});
                   14629:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14630:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14631:                     my $intdom = &internet_dom($id);
                   14632:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14633:                         push(@idns,$intdom);
                   14634:                     }
                   14635:                 }
                   14636:             }
                   14637:             $seen{$prim_ip} = 1;
                   14638:         }
1.1219    raeburn  14639:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14640:     }
                   14641: 
1.986     foxr     14642: }
                   14643: 
1.1079    raeburn  14644: sub all_loncaparevs {
1.1249    raeburn  14645:     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  14646: }
                   14647: 
1.1227    raeburn  14648: # ---------------------------------------------------------- Read loncaparev table
                   14649: {
                   14650:     sub load_loncaparevs { 
                   14651:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  14652:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  14653:                 while (my $configline=<$config>) {
                   14654:                     chomp($configline);
                   14655:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14656:                     $loncaparevs{$hostid}=$loncaparev;
                   14657:                 }
                   14658:                 close($config);
                   14659:             }
                   14660:         }
                   14661:     }
                   14662: }
                   14663: 
                   14664: # ---------------------------------------------------------- Read serverhostID table
                   14665: {
                   14666:     sub load_serverhomeIDs {
                   14667:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  14668:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  14669:                 while (my $configline=<$config>) {
                   14670:                     chomp($configline);
                   14671:                     my ($name,$id)=split(/:/,$configline);
                   14672:                     $serverhomeIDs{$name}=$id;
                   14673:                 }
                   14674:                 close($config);
                   14675:             }
                   14676:         }
                   14677:     }
                   14678: }
                   14679: 
                   14680: 
1.862     albertel 14681: BEGIN {
                   14682: 
                   14683: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14684:     unless ($readit) {
                   14685: {
                   14686:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14687:     %perlvar = (%perlvar,%{$configvars});
                   14688: }
                   14689: 
                   14690: 
1.1       albertel 14691: # ------------------------------------------------------ Read spare server file
                   14692: {
1.1359    raeburn  14693:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14694: 
                   14695:     while (my $configline=<$config>) {
                   14696:        chomp($configline);
1.284     matthew  14697:        if ($configline) {
1.784     albertel 14698: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14699: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14700: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14701:        }
                   14702:     }
1.448     albertel 14703:     close($config);
1.1       albertel 14704: }
1.11      www      14705: # ------------------------------------------------------------ Read permissions
                   14706: {
1.1359    raeburn  14707:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14708: 
                   14709:     while (my $configline=<$config>) {
1.448     albertel 14710: 	chomp($configline);
                   14711: 	if ($configline) {
                   14712: 	    my ($role,$perm)=split(/ /,$configline);
                   14713: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14714: 	}
1.11      www      14715:     }
1.448     albertel 14716:     close($config);
1.11      www      14717: }
                   14718: 
                   14719: # -------------------------------------------- Read plain texts for permissions
                   14720: {
1.1359    raeburn  14721:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14722: 
                   14723:     while (my $configline=<$config>) {
1.448     albertel 14724: 	chomp($configline);
                   14725: 	if ($configline) {
1.742     raeburn  14726: 	    my ($short,@plain)=split(/:/,$configline);
                   14727:             %{$prp{$short}} = ();
                   14728: 	    if (@plain > 0) {
                   14729:                 $prp{$short}{'std'} = $plain[0];
                   14730:                 for (my $i=1; $i<@plain; $i++) {
                   14731:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14732:                 }
                   14733:             }
1.448     albertel 14734: 	}
1.135     www      14735:     }
1.448     albertel 14736:     close($config);
1.135     www      14737: }
                   14738: 
                   14739: # ---------------------------------------------------------- Read package table
                   14740: {
1.1359    raeburn  14741:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14742: 
                   14743:     while (my $configline=<$config>) {
1.483     albertel 14744: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14745: 	chomp($configline);
                   14746: 	my ($short,$plain)=split(/:/,$configline);
                   14747: 	my ($pack,$name)=split(/\&/,$short);
                   14748: 	if ($plain ne '') {
                   14749: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14750: 	    $packagetab{$short}=$plain; 
                   14751: 	}
1.11      www      14752:     }
1.448     albertel 14753:     close($config);
1.329     matthew  14754: }
                   14755: 
1.1073    raeburn  14756: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  14757: 
                   14758: &load_loncaparevs();
1.1073    raeburn  14759: 
1.1074    raeburn  14760: # ---------------------------------------------------------- Read serverhostID table
                   14761: 
1.1227    raeburn  14762: &load_serverhomeIDs();
                   14763: 
                   14764: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14765: {
                   14766:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14767:     if (-e $file) {
                   14768:         my $parser = HTML::LCParser->new($file);
                   14769:         while (my $token = $parser->get_token()) {
                   14770:             if ($token->[0] eq 'S') {
                   14771:                 my $item = $token->[1];
                   14772:                 my $name = $token->[2]{'name'};
                   14773:                 my $value = $token->[2]{'value'};
1.1285    raeburn  14774:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  14775:                 my $namematch = $token->[2]{'namematch'};
                   14776:                 if ($item eq 'parameter') {
                   14777:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   14778:                         my $release = $parser->get_text();
                   14779:                         $release =~ s/(^\s*|\s*$ )//gx;
                   14780:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   14781:                     }
                   14782:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  14783:                     my $release = $parser->get_text();
                   14784:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  14785:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  14786:                 }
                   14787:             }
                   14788:         }
                   14789:     }
1.1073    raeburn  14790: }
                   14791: 
1.1138    raeburn  14792: # ---------------------------------------------------------- Read managers table
                   14793: {
                   14794:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  14795:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14796:             while (my $configline=<$config>) {
                   14797:                 chomp($configline);
                   14798:                 next if ($configline =~ /^\#/);
                   14799:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14800:                     $managerstab{$configline} = 1;
                   14801:                 }
                   14802:             }
                   14803:             close($config);
                   14804:         }
                   14805:     }
                   14806: }
                   14807: 
1.329     matthew  14808: # ------------- set up temporary directory
                   14809: {
1.1117    foxr     14810:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14811: 
1.11      www      14812: }
                   14813: 
1.794     albertel 14814: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14815: 				'compress_threshold'=> 20_000,
                   14816:  			        });
1.185     www      14817: 
1.281     www      14818: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14819: $dumpcount=0;
1.958     www      14820: $locknum=0;
1.22      www      14821: 
1.163     harris41 14822: &logtouch();
1.672     albertel 14823: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14824: $readit=1;
1.564     albertel 14825:     {
                   14826: 	use integer;
                   14827: 	my $test=(2**32)+1;
1.568     albertel 14828: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14829: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14830:     }
1.195     www      14831: }
1.1       albertel 14832: }
1.179     www      14833: 
1.1       albertel 14834: 1;
1.191     harris41 14835: __END__
                   14836: 
1.243     albertel 14837: =pod
                   14838: 
1.191     harris41 14839: =head1 NAME
                   14840: 
1.243     albertel 14841: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14842: 
                   14843: =head1 SYNOPSIS
                   14844: 
1.243     albertel 14845: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14846: 
                   14847:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14848: 
1.243     albertel 14849: Common parameters:
                   14850: 
                   14851: =over 4
                   14852: 
                   14853: =item *
                   14854: 
                   14855: $uname : an internal username (if $cname expecting a course Id specifically)
                   14856: 
                   14857: =item *
                   14858: 
                   14859: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14860: 
                   14861: =item *
                   14862: 
                   14863: $symb : a resource instance identifier
                   14864: 
                   14865: =item *
                   14866: 
                   14867: $namespace : the name of a .db file that contains the data needed or
                   14868: being set.
                   14869: 
                   14870: =back
                   14871: 
1.394     bowersj2 14872: =head1 OVERVIEW
1.191     harris41 14873: 
1.394     bowersj2 14874: lonnet provides subroutines which interact with the
                   14875: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14876: about classes, users, and resources.
1.243     albertel 14877: 
                   14878: For many of these objects you can also use this to store data about
                   14879: them or modify them in various ways.
1.191     harris41 14880: 
1.394     bowersj2 14881: =head2 Symbs
1.191     harris41 14882: 
1.394     bowersj2 14883: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14884: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14885: map, the resource number of the resource in the map, and the URL of
                   14886: the resource itself. The latter is somewhat redundant, but might help
                   14887: if maps change.
                   14888: 
                   14889: An example is
                   14890: 
                   14891:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14892: 
                   14893: The respective map entry is
                   14894: 
                   14895:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14896:   title="Problem 2">
                   14897:  </resource>
                   14898: 
                   14899: Symbs are used by the random number generator, as well as to store and
                   14900: restore data specific to a certain instance of for example a problem.
                   14901: 
                   14902: =head2 Storing And Retrieving Data
                   14903: 
                   14904: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14905: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14906: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14907: is is the non-critical message twin of cstore. These functions are for
                   14908: handlers to store a perl hash to a user's permanent data space in an
                   14909: easy manner, and to retrieve it again on another call. It is expected
                   14910: that a handler would use this once at the beginning to retrieve data,
                   14911: and then again once at the end to send only the new data back.
                   14912: 
                   14913: The data is stored in the user's data directory on the user's
                   14914: homeserver under the ID of the course.
                   14915: 
                   14916: The hash that is returned by restore will have all of the previous
                   14917: value for all of the elements of the hash.
                   14918: 
                   14919: Example:
                   14920: 
                   14921:  #creating a hash
                   14922:  my %hash;
                   14923:  $hash{'foo'}='bar';
                   14924: 
                   14925:  #storing it
                   14926:  &Apache::lonnet::cstore(\%hash);
                   14927: 
                   14928:  #changing a value
                   14929:  $hash{'foo'}='notbar';
                   14930: 
                   14931:  #adding a new value
                   14932:  $hash{'bar'}='foo';
                   14933:  &Apache::lonnet::cstore(\%hash);
                   14934: 
                   14935:  #retrieving the hash
                   14936:  my %history=&Apache::lonnet::restore();
                   14937: 
                   14938:  #print the hash
                   14939:  foreach my $key (sort(keys(%history))) {
                   14940:    print("\%history{$key} = $history{$key}");
                   14941:  }
                   14942: 
                   14943: Will print out:
1.191     harris41 14944: 
1.394     bowersj2 14945:  %history{1:foo} = bar
                   14946:  %history{1:keys} = foo:timestamp
                   14947:  %history{1:timestamp} = 990455579
                   14948:  %history{2:bar} = foo
                   14949:  %history{2:foo} = notbar
                   14950:  %history{2:keys} = foo:bar:timestamp
                   14951:  %history{2:timestamp} = 990455580
                   14952:  %history{bar} = foo
                   14953:  %history{foo} = notbar
                   14954:  %history{timestamp} = 990455580
                   14955:  %history{version} = 2
                   14956: 
                   14957: Note that the special hash entries C<keys>, C<version> and
                   14958: C<timestamp> were added to the hash. C<version> will be equal to the
                   14959: total number of versions of the data that have been stored. The
                   14960: C<timestamp> attribute will be the UNIX time the hash was
                   14961: stored. C<keys> is available in every historical section to list which
                   14962: keys were added or changed at a specific historical revision of a
                   14963: hash.
                   14964: 
                   14965: B<Warning>: do not store the hash that restore returns directly. This
                   14966: will cause a mess since it will restore the historical keys as if the
                   14967: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14968: 
1.394     bowersj2 14969: Calling convention:
1.191     harris41 14970: 
1.1225    raeburn  14971:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  14972:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14973: 
1.394     bowersj2 14974: For more detailed information, see lonnet specific documentation.
1.191     harris41 14975: 
1.394     bowersj2 14976: =head1 RETURN MESSAGES
1.191     harris41 14977: 
1.394     bowersj2 14978: =over 4
1.191     harris41 14979: 
1.394     bowersj2 14980: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14981: 
1.394     bowersj2 14982: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14983: when the connection is brought back up
1.191     harris41 14984: 
1.394     bowersj2 14985: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14986: for later delivery
1.191     harris41 14987: 
1.967     bisitz   14988: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14989: 
1.394     bowersj2 14990: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14991: that was requested
1.191     harris41 14992: 
1.243     albertel 14993: =back
1.191     harris41 14994: 
1.243     albertel 14995: =head1 PUBLIC SUBROUTINES
1.191     harris41 14996: 
1.243     albertel 14997: =head2 Session Environment Functions
1.191     harris41 14998: 
1.243     albertel 14999: =over 4
1.191     harris41 15000: 
1.394     bowersj2 15001: =item * 
                   15002: X<appenv()>
1.949     raeburn  15003: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 15004: the user envirnoment file, and will be restored for each access this
1.620     albertel 15005: user makes during this session, also modifies the %env for the current
1.949     raeburn  15006: process. Optional rolesarrayref - if defined contains a reference to an array
                   15007: of roles which are exempt from the restriction on modifying user.role entries 
                   15008: in the user's environment.db and in %env.    
1.191     harris41 15009: 
                   15010: =item *
1.394     bowersj2 15011: X<delenv()>
1.987     raeburn  15012: B<delenv($delthis,$regexp)>: removes all items from the session
                   15013: environment file that begin with $delthis. If the 
                   15014: optional second arg - $regexp - is true, $delthis is treated as a 
                   15015: regular expression, otherwise \Q$delthis\E is used. 
                   15016: The values are also deleted from the current processes %env.
1.191     harris41 15017: 
1.795     albertel 15018: =item * get_env_multiple($name) 
                   15019: 
                   15020: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   15021: values may be defined and end up as an array ref.
                   15022: 
                   15023: returns an array of values
                   15024: 
1.243     albertel 15025: =back
                   15026: 
                   15027: =head2 User Information
1.191     harris41 15028: 
1.243     albertel 15029: =over 4
1.191     harris41 15030: 
                   15031: =item *
1.394     bowersj2 15032: X<queryauthenticate()>
                   15033: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 15034: authentication scheme
                   15035: 
                   15036: =item *
1.394     bowersj2 15037: X<authenticate()>
1.1073    raeburn  15038: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 15039: authenticate user from domain's lib servers (first use the current
                   15040: one). C<$upass> should be the users password.
1.1073    raeburn  15041: $checkdefauth is optional (value is 1 if a check should be made to
                   15042:    authenticate user using default authentication method, and allow
                   15043:    account creation if username does not have account in the domain).
                   15044: $clientcancheckhost is optional (value is 1 if checking whether the
                   15045:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 15046: 
                   15047: =item *
1.394     bowersj2 15048: X<homeserver()>
                   15049: B<homeserver($uname,$udom)>: find the server which has
                   15050: the user's directory and files (there must be only one), this caches
                   15051: the answer, and also caches if there is a borken connection.
1.191     harris41 15052: 
                   15053: =item *
1.394     bowersj2 15054: X<idget()>
1.1300    raeburn  15055: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   15056: a list of student/employee IDs or clicker IDs
                   15057: (student/employee IDs are a unique resource in a domain, there must be 
                   15058: only 1 ID per username, and only 1 username per ID in a specific domain).
                   15059: clickerIDs are not necessarily unique, as students might share clickers.
                   15060: (returns hash: id=>name,id=>name)
1.191     harris41 15061: 
                   15062: =item *
1.394     bowersj2 15063: X<idrget()>
                   15064: B<idrget($udom,@unames)>: find the IDs behind a list of
                   15065: usernames (returns hash: name=>id,name=>id)
1.191     harris41 15066: 
                   15067: =item *
1.394     bowersj2 15068: X<idput()>
1.1300    raeburn  15069: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   15070: names and associated student/employee IDs or clicker IDs.
                   15071: 
                   15072: =item *
                   15073: X<iddel()>
                   15074: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   15075: student/employee ID or clicker ID username look-ups from domain.
                   15076: The homeserver ($uhome) and namespace ($namespace) are optional.
                   15077: If no $uhome is provided, it will be determined usig &homeserver()
                   15078: for each user.  If no $namespace is provided, the default is ids.
                   15079: 
                   15080: =item *
                   15081: X<updateclickers()>
                   15082: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   15083: clicker ID-to-username look-ups in clickers.db on library server.
                   15084: Permitted actions are add or del (i.e., add or delete). The 
                   15085: clickers.db contains clickerID as keys (escaped), and each corresponding
                   15086: value is an escaped comma-separated list of usernames (for whom the
                   15087: library server is the homeserver), who registered that particular ID.
                   15088: If $critical is true, the update will be sent via &critical, otherwise
                   15089: &reply() will be used.
1.191     harris41 15090: 
                   15091: =item *
1.394     bowersj2 15092: X<rolesinit()>
1.1169    droeschl 15093: B<rolesinit($udom,$username)>: get user privileges.
                   15094: returns user role, first access and timer interval hashes
1.243     albertel 15095: 
                   15096: =item *
1.1171    droeschl 15097: X<privileged()>
                   15098: B<privileged($username,$domain)>: returns a true if user has a
                   15099: privileged and active role (i.e. su or dc), false otherwise.
                   15100: 
                   15101: =item *
1.551     albertel 15102: X<getsection()>
                   15103: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 15104: course $cname, return section name/number or '' for "not in course"
                   15105: and '-1' for "no section"
                   15106: 
                   15107: =item *
1.394     bowersj2 15108: X<userenvironment()>
                   15109: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 15110: passed in @what from the requested user's environment, returns a hash
                   15111: 
1.858     raeburn  15112: =item * 
                   15113: X<userlog_query()>
1.859     albertel 15114: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   15115: activity.log file. %filters defines filters applied when parsing the
                   15116: log file. These can be start or end timestamps, or the type of action
                   15117: - log to look for Login or Logout events, check for Checkin or
                   15118: Checkout, role for role selection. The response is in the form
                   15119: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   15120: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  15121: 
1.243     albertel 15122: =back
                   15123: 
                   15124: =head2 User Roles
                   15125: 
                   15126: =over 4
                   15127: 
                   15128: =item *
                   15129: 
1.1284    raeburn  15130: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   15131: returns codes for allowed actions.
                   15132: 
                   15133: The first argument is required, all others are optional.
                   15134: 
                   15135: $priv is the privilege being checked.
                   15136: $uri contains additional information about what is being checked for access (e.g.,
                   15137: URL, course ID etc.). 
                   15138: $symb is the unique resource instance identifier in a course; if needed,
                   15139: but not provided, it will be retrieved via a call to &symbread(). 
                   15140: $role is the role for which a priv is being checked (only used if priv is evb). 
                   15141: $clientip is the user's IP address (only used when checking for access to portfolio 
                   15142: files).
                   15143: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   15144: prevents recursive calls to &allowed.
                   15145: 
1.243     albertel 15146:  F: full access
                   15147:  U,I,K: authentication modes (cxx only)
                   15148:  '': forbidden
                   15149:  1: user needs to choose course
                   15150:  2: browse allowed
1.766     albertel 15151:  A: passphrase authentication needed
1.1284    raeburn  15152:  B: access temporarily blocked because of a blocking event in a course.
1.1402    raeburn  15153:  D: access blocked because access is required via session initiated via deep-link 
1.243     albertel 15154: 
                   15155: =item *
                   15156: 
1.1192    raeburn  15157: constructaccess($url,$setpriv) : check for access to construction space URL
                   15158: 
                   15159: See if the owner domain and name in the URL match those in the
                   15160: expected environment.  If so, return three element list
                   15161: ($ownername,$ownerdomain,$ownerhome).
                   15162: 
                   15163: Otherwise return the null string.
                   15164: 
                   15165: If second argument 'setpriv' is true, it assigns the privileges,
                   15166: and returns the same three element list, unless the owner has
                   15167: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   15168: in which case the null string is returned.
                   15169: 
                   15170: =item *
                   15171: 
1.1326    raeburn  15172: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   15173: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   15174: for system, domain, and course level. $uname and $udom are optional (current
                   15175: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 15176: 
                   15177: =item *
                   15178: 
1.988     raeburn  15179: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   15180: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  15181: $type is Course (default) or Community.
1.988     raeburn  15182: If $forcedefault evaluates to true, text returned will be default 
                   15183: text for $type. Otherwise, if this is a course, the text returned 
                   15184: will be a custom name for the role (if defined in the course's 
                   15185: environment).  If no custom name is defined the default is returned.
                   15186:    
1.832     raeburn  15187: =item *
                   15188: 
1.1219    raeburn  15189: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  15190: All arguments are optional. Returns a hash of a roles, either for
                   15191: co-author/assistant author roles for a user's Construction Space
1.906     albertel 15192: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  15193: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   15194: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   15195: For each key, value is set to colon-separated start and end times for
                   15196: the role.  If no username and domain are specified, will default to
1.934     raeburn  15197: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  15198: of role statuses (active, future or previous), roles 
                   15199: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   15200: to restrict the list of roles reported. If no array ref is 
                   15201: provided for types, will default to return only active roles.
1.834     albertel 15202: 
1.1195    raeburn  15203: =item *
                   15204: 
                   15205: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  15206: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   15207: 
                   15208: Additional optional arguments are: $type (if role checking is to be restricted 
                   15209: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  15210: available roles) or future (roles available in the future), and
                   15211: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  15212: have active Domain Coordinator role in course's domain or in additional
                   15213: domains (specified in 'Domains to check for privileged users' in course
                   15214: environment -- set via:  Course Settings -> Classlists and staff listing).
                   15215: 
                   15216: =item *
                   15217: 
                   15218: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   15219: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   15220: $possdomains and $possroles are optional array refs -- to domains to check and
                   15221: roles to check.  If $possdomains is not specified, a dump will be done of the
                   15222: users' roles.db to check for a dc or su role in any domain. This can be
                   15223: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   15224: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   15225: this then allows &privileged_by_domain() to be used, which caches the identity
                   15226: of privileged users, eliminating the need for repeated calls to &dump().
                   15227: 
                   15228: =item *
                   15229: 
                   15230: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15231: where the outer hash keys are domains specified in the $possdomains array ref,
                   15232: next inner hash keys are privileged roles specified in the $roles array ref,
                   15233: and the innermost hash contains key = value pairs for username:domain = end:start
                   15234: for active or future "privileged" users with that role in that domain. To avoid
                   15235: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15236: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  15237: 
1.243     albertel 15238: =back
                   15239: 
                   15240: =head2 User Modification
                   15241: 
                   15242: =over 4
                   15243: 
                   15244: =item *
                   15245: 
1.957     raeburn  15246: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15247: user for the level given by URL.  Optional start and end dates (leave empty
                   15248: string or zero for "no date")
1.191     harris41 15249: 
                   15250: =item *
                   15251: 
1.243     albertel 15252: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15253: change a users, password, possible return values are: ok,
                   15254: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15255: refused
1.191     harris41 15256: 
                   15257: =item *
                   15258: 
1.243     albertel 15259: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15260: 
                   15261: =item *
                   15262: 
1.1058    raeburn  15263: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   15264:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   15265: 
                   15266: will update user information (firstname,middlename,lastname,generation,
                   15267: permanentemail), and if forceid is true, student/employee ID also.
                   15268: A user's institutional affiliation(s) can also be updated.
                   15269: User information fields will not be overwritten with empty entries 
                   15270: unless the field is included in the $candelete array reference.
                   15271: This array is included when a single user is modified via "Manage Users",
                   15272: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 15273: 
                   15274: =item *
                   15275: 
1.286     matthew  15276: modifystudent
                   15277: 
1.957     raeburn  15278: modify a student's enrollment and identification information.
1.1235    raeburn  15279: The course id is resolved based on the current user's environment.  
                   15280: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  15281: associated with a course.
                   15282: 
1.297     matthew  15283: This call is essentially a wrapper for lonnet::modifyuser and
                   15284: lonnet::modify_student_enrollment
1.286     matthew  15285: 
                   15286: Inputs: 
                   15287: 
                   15288: =over 4
                   15289: 
1.957     raeburn  15290: =item B<$udom> Student's loncapa domain
1.286     matthew  15291: 
1.957     raeburn  15292: =item B<$uname> Student's loncapa login name
1.286     matthew  15293: 
1.964     bisitz   15294: =item B<$uid> Student/Employee ID
1.286     matthew  15295: 
1.957     raeburn  15296: =item B<$umode> Student's authentication mode
1.286     matthew  15297: 
1.957     raeburn  15298: =item B<$upass> Student's password
1.286     matthew  15299: 
1.957     raeburn  15300: =item B<$first> Student's first name
1.286     matthew  15301: 
1.957     raeburn  15302: =item B<$middle> Student's middle name
1.286     matthew  15303: 
1.957     raeburn  15304: =item B<$last> Student's last name
1.286     matthew  15305: 
1.957     raeburn  15306: =item B<$gene> Student's generation
1.286     matthew  15307: 
1.957     raeburn  15308: =item B<$usec> Student's section in course
1.286     matthew  15309: 
                   15310: =item B<$end> Unix time of the roles expiration
                   15311: 
                   15312: =item B<$start> Unix time of the roles start date
                   15313: 
                   15314: =item B<$forceid> If defined, allow $uid to be changed
                   15315: 
                   15316: =item B<$desiredhome> server to use as home server for student
                   15317: 
1.957     raeburn  15318: =item B<$email> Student's permanent e-mail address
                   15319: 
                   15320: =item B<$type> Type of enrollment (auto or manual)
                   15321: 
1.963     raeburn  15322: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   15323: 
                   15324: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  15325: 
1.963     raeburn  15326: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  15327: 
1.963     raeburn  15328: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  15329: 
1.1216    raeburn  15330: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   15331: 
                   15332: =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  15333: 
1.286     matthew  15334: =back
1.297     matthew  15335: 
                   15336: =item *
                   15337: 
                   15338: modify_student_enrollment
                   15339: 
1.1235    raeburn  15340: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  15341: 'role.request.course' must be defined for this function to proceed.
                   15342: 
                   15343: Inputs:
                   15344: 
                   15345: =over 4
                   15346: 
1.1235    raeburn  15347: =item $udom, student's domain
1.297     matthew  15348: 
1.1235    raeburn  15349: =item $uname, student's name
1.297     matthew  15350: 
1.1235    raeburn  15351: =item $uid, student's user id
1.297     matthew  15352: 
1.1235    raeburn  15353: =item $first, student's first name
1.297     matthew  15354: 
                   15355: =item $middle
                   15356: 
                   15357: =item $last
                   15358: 
                   15359: =item $gene
                   15360: 
                   15361: =item $usec
                   15362: 
                   15363: =item $end
                   15364: 
                   15365: =item $start
                   15366: 
1.957     raeburn  15367: =item $type
                   15368: 
                   15369: =item $locktype
                   15370: 
                   15371: =item $cid
                   15372: 
                   15373: =item $selfenroll
                   15374: 
                   15375: =item $context
                   15376: 
1.1216    raeburn  15377: =item $credits, number of credits student will earn from this class
                   15378: 
1.1314    raeburn  15379: =item $instsec, institutional course section code for student
                   15380: 
1.297     matthew  15381: =back
                   15382: 
1.191     harris41 15383: 
                   15384: =item *
                   15385: 
1.243     albertel 15386: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   15387: custom role; give a custom role to a user for the level given by URL.  Specify
                   15388: name and domain of role author, and role name
1.191     harris41 15389: 
                   15390: =item *
                   15391: 
1.243     albertel 15392: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 15393: 
                   15394: =item *
                   15395: 
1.243     albertel 15396: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   15397: 
                   15398: =back
                   15399: 
                   15400: =head2 Course Infomation
                   15401: 
                   15402: =over 4
1.191     harris41 15403: 
                   15404: =item *
                   15405: 
1.1118    foxr     15406: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 15407: specified course id, including all environment settings for the
                   15408: course, the description of the course will be in the hash under the
                   15409: key 'description'
1.191     harris41 15410: 
1.1118    foxr     15411: $options is an optional parameter that if supplied is a hash reference that controls
                   15412: what how this function works.  It has the following key/values:
                   15413: 
                   15414: =over 4
                   15415: 
                   15416: =item freshen_cache
                   15417: 
                   15418: If defined, and the environment cache for the course is valid, it is 
                   15419: returned in the returned hash.
                   15420: 
                   15421: =item one_time
                   15422: 
                   15423: If defined, the last cache time is set to _now_
                   15424: 
                   15425: =item user
                   15426: 
                   15427: If defined, the supplied username is used instead of the current user.
                   15428: 
                   15429: 
                   15430: =back
                   15431: 
1.191     harris41 15432: =item *
                   15433: 
1.624     albertel 15434: resdata($name,$domain,$type,@which) : request for current parameter
                   15435: setting for a specific $type, where $type is either 'course' or 'user',
                   15436: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  15437: answers for 10 minutes.
1.243     albertel 15438: 
1.877     foxr     15439: =item *
                   15440: 
                   15441: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15442: data base, returning a hash that is keyed by the resource name and has
                   15443: values that are the resource value.  I believe that the timestamps and
                   15444: versions are also returned.
                   15445: 
1.1236    raeburn  15446: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15447: supplemental content area. This routine caches the number of files for 
                   15448: 10 minutes.
                   15449: 
1.243     albertel 15450: =back
                   15451: 
                   15452: =head2 Course Modification
                   15453: 
                   15454: =over 4
1.191     harris41 15455: 
                   15456: =item *
                   15457: 
1.243     albertel 15458: writecoursepref($courseid,%prefs) : write preferences (environment
                   15459: database) for a course
1.191     harris41 15460: 
                   15461: =item *
                   15462: 
1.1011    raeburn  15463: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15464: 
                   15465: =item *
                   15466: 
1.1038    raeburn  15467: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15468: 
1.1167    droeschl 15469: =item *
                   15470: 
                   15471: is_course($courseid), is_course($cdom, $cnum)
                   15472: 
                   15473: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15474: two component version $cdom, $cnum. It checks if the specified course exists.
                   15475: 
                   15476: Returns:
                   15477:     undef if the course doesn't exist, otherwise
                   15478:     in scalar context the combined courseid.
                   15479:     in list context the two components of the course identifier, domain and 
                   15480:     courseid.    
                   15481: 
1.243     albertel 15482: =back
                   15483: 
1.1401    raeburn  15484: =head2 Bubblesheet Configuration
                   15485: 
                   15486: =over 4
                   15487: 
                   15488: =item *
                   15489: 
                   15490: get_scantron_config($which)
                   15491: 
                   15492: $which - the name of the configuration to parse from the file.
                   15493: 
                   15494: Parses and returns the bubblesheet configuration line selected as a
                   15495: hash of configuration file fields.
                   15496: 
                   15497: 
                   15498: Returns:
                   15499:     If the named configuration is not in the file, an empty
                   15500:     hash is returned.
                   15501: 
                   15502:     a hash with the fields
                   15503:       name         - internal name for the this configuration setup
                   15504:       description  - text to display to operator that describes this config
                   15505:       CODElocation - if 0 or the string 'none'
                   15506:                           - no CODE exists for this config
                   15507:                      if -1 || the string 'letter'
                   15508:                           - a CODE exists for this config and is
                   15509:                             a string of letters
                   15510:                      Unsupported value (but planned for future support)
                   15511:                           if a positive integer
                   15512:                                - The CODE exists as the first n items from
                   15513:                                  the question section of the form
                   15514:                           if the string 'number'
                   15515:                                - The CODE exists for this config and is
                   15516:                                  a string of numbers
                   15517:       CODEstart   - (only matter if a CODE exists) column in the line where
                   15518:                      the CODE starts
                   15519:       CODElength  - length of the CODE
                   15520:       IDstart     - column where the student/employee ID starts
                   15521:       IDlength    - length of the student/employee ID info
                   15522:       Qstart      - column where the information from the bubbled
                   15523:                     'questions' start
                   15524:       Qlength     - number of columns comprising a single bubble line from
                   15525:                     the sheet. (usually either 1 or 10)
                   15526:       Qon         - either a single character representing the character used
                   15527:                     to signal a bubble was chosen in the positional setup, or
                   15528:                     the string 'letter' if the letter of the chosen bubble is
                   15529:                     in the final, or 'number' if a number representing the
                   15530:                     chosen bubble is in the file (1->A 0->J)
                   15531:       Qoff        - the character used to represent that a bubble was
                   15532:                     left blank
                   15533:       PaperID     - if the scanning process generates a unique number for each
                   15534:                     sheet scanned the column that this ID number starts in
                   15535:       PaperIDlength - number of columns that comprise the unique ID number
                   15536:                       for the sheet of paper
                   15537:       FirstName   - column that the first name starts in
                   15538:       FirstNameLength - number of columns that the first name spans
                   15539: 
                   15540:       LastName    - column that the last name starts in
                   15541:       LastNameLength - number of columns that the last name spans
                   15542:       BubblesPerRow - number of bubbles available in each row used to
                   15543:                       bubble an answer. (If not specified, 10 assumed).
                   15544: 
                   15545: 
                   15546: =item *
                   15547: 
                   15548: get_scantronformat_file($cdom)
                   15549: 
                   15550: $cdom - the course's domain (optional); if not supplied, uses
                   15551: domain for current $env{'request.course.id'}.
                   15552: 
                   15553: Returns an array containing lines from the scantron format file for
                   15554: the domain of the course.
                   15555: 
                   15556: If a url for a custom.tab file is listed in domain's configuration.db,
                   15557: lines are from this file.
                   15558: 
                   15559: Otherwise, if a default.tab has been published in RES space by the
                   15560: domainconfig user, lines are from this file.
                   15561: 
                   15562: Otherwise, fall back to getting lines from the legacy file on the
                   15563: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   15564: 
                   15565: =back
                   15566: 
1.243     albertel 15567: =head2 Resource Subroutines
                   15568: 
                   15569: =over 4
1.191     harris41 15570: 
                   15571: =item *
                   15572: 
1.243     albertel 15573: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15574: 
                   15575: =item *
                   15576: 
1.243     albertel 15577: repcopy($filename) : subscribes to the requested file, and attempts to
                   15578: replicate from the owning library server, Might return
1.607     raeburn  15579: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15580: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15581: resource. Expects the local filesystem pathname
                   15582: (/home/httpd/html/res/....)
                   15583: 
                   15584: =back
                   15585: 
                   15586: =head2 Resource Information
                   15587: 
                   15588: =over 4
1.191     harris41 15589: 
                   15590: =item *
                   15591: 
1.1228    raeburn  15592: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15593: and returns the value of a variety of different possible values,
                   15594: $varname should be a request string, and the other parameters can be
                   15595: used to specify who and what one is asking about. Ordinarily, $cid 
                   15596: does not need to be specified, as it is retrived from 
                   15597: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15598: within lonuserstate::loadmap() when initializing a course, before
                   15599: $env{'request.course.id'} has been set, so it needs to be provided
                   15600: in that one case.
1.243     albertel 15601: 
                   15602: Possible values for $varname are environment.lastname (or other item
                   15603: from the envirnment hash), user.name (or someother aspect about the
                   15604: user), resource.0.maxtries (or some other part and parameter of a
                   15605: resource)
1.204     albertel 15606: 
                   15607: =item *
                   15608: 
1.243     albertel 15609: directcondval($number) : get current value of a condition; reads from a state
                   15610: string
1.204     albertel 15611: 
                   15612: =item *
                   15613: 
1.243     albertel 15614: condval($condidx) : value of condition index based on state
1.204     albertel 15615: 
                   15616: =item *
                   15617: 
1.1362    raeburn  15618: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 15619: resource's metadata, $what should be either a specific key, or either
                   15620: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  15621: packages that this resource currently uses, the last 3 arguments are 
                   15622: only used internally for recursive metadata.
                   15623: 
                   15624: the toolsymb is only used where the uri is for an external tool (for which
                   15625: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 15626: 
1.1371    raeburn  15627: this function automatically caches all requests except any made recursively
                   15628: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   15629: defined).
1.191     harris41 15630: 
                   15631: =item *
                   15632: 
1.243     albertel 15633: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15634: network of library servers; returns file handle of where SQL and regex results
                   15635: will be stored for query
1.191     harris41 15636: 
                   15637: =item *
                   15638: 
1.1282    raeburn  15639: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   15640: return symbolic list entry (all arguments optional). 
                   15641: 
                   15642: Args: filename is the filename (including path) for the file for which a symb 
                   15643: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   15644: to check access status if more than one resource was found in the bighash 
                   15645: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   15646: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   15647: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15648: cause possible symbs to be checked to determine if they are subject to content
                   15649: blocking, if so they will not be included as possible symbs; possibles is a
                   15650: ref to a hash, which, as a side effect, will be populated with all possible 
                   15651: symbs (content blocking not tested).
                   15652:  
1.243     albertel 15653: returns the data handle
1.191     harris41 15654: 
                   15655: =item *
                   15656: 
1.1190    raeburn  15657: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   15658: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15659: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  15660: on failure, user must be in a course, as it assumes the existence of
                   15661: the course initial hash, and uses $env('request.course.id'}.  The third
                   15662: arg is an optional reference to a scalar.  If this arg is passed in the 
                   15663: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15664: encrypted; otherwise it will be null.  
1.191     harris41 15665: 
                   15666: =item *
                   15667: 
1.243     albertel 15668: symbclean($symb) : removes versions numbers from a symb, returns the
                   15669: cleaned symb
1.191     harris41 15670: 
                   15671: =item *
                   15672: 
1.243     albertel 15673: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15674: course map, user must be in a course for it to work.
1.191     harris41 15675: 
                   15676: =item *
                   15677: 
1.243     albertel 15678: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15679: 
                   15680: =item *
                   15681: 
1.243     albertel 15682: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15683: a random seed, all arguments are optional, if they aren't sent it uses the
                   15684: environment to derive them. Note: if symb isn't sent and it can't get one
                   15685: from &symbread it will use the current time as its return value
1.191     harris41 15686: 
                   15687: =item *
                   15688: 
1.243     albertel 15689: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15690: unfakeable, receipt
1.191     harris41 15691: 
                   15692: =item *
                   15693: 
1.620     albertel 15694: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15695: 
                   15696: =item *
                   15697: 
1.243     albertel 15698: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15699: 
                   15700: =item *
                   15701: 
1.243     albertel 15702: 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 15703: 
                   15704: =item *
                   15705: 
1.243     albertel 15706: 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 15707: 
                   15708: =item *
                   15709: 
1.243     albertel 15710: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15711: 
                   15712: =item *
                   15713: 
1.243     albertel 15714: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15715: forcing spreadsheet to reevaluate the resource scores next time.
                   15716: 
1.1195    raeburn  15717: =item * 
                   15718: 
1.1196    raeburn  15719: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15720: when viewing in course context.
1.1195    raeburn  15721: 
1.1196    raeburn  15722:  input: six args -- filename (decluttered), course number, course domain,
                   15723:                     url, symb (if registered) and group (if this is a 
                   15724:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  15725: 
1.1196    raeburn  15726:  output: array of five scalars --
1.1195    raeburn  15727:          $cfile -- url for file editing if editable on current server
                   15728:          $home -- homeserver of resource (i.e., for author if published,
                   15729:                                           or course if uploaded.).
                   15730:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  15731:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   15732:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  15733: 
                   15734: =item *
                   15735: 
                   15736: is_course_upload($file,$cnum,$cdom)
                   15737: 
                   15738: Used in course context to determine if current file was uploaded to 
                   15739: the course (i.e., would be found in /userfiles/docs on the course's 
                   15740: homeserver.
                   15741: 
                   15742:   input: 3 args -- filename (decluttered), course number and course domain.
                   15743:   output: boolean -- 1 if file was uploaded.
                   15744: 
1.243     albertel 15745: =back
                   15746: 
                   15747: =head2 Storing/Retreiving Data
                   15748: 
                   15749: =over 4
1.191     harris41 15750: 
                   15751: =item *
                   15752: 
1.1269    raeburn  15753: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   15754: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15755: the remaining args aren't required and if they aren't passed or are '' they will
                   15756: be derived from the env (with the exception of $laststore, which is an 
                   15757: optional arg used when a user's submission is stored in grading).
                   15758: $laststore is $version=$timestamp, where $version is the most recent version
                   15759: number retrieved for the corresponding $symb in the $namespace db file, and
                   15760: $timestamp is the timestamp for that transaction (UNIX time).
                   15761: $laststore is currently only passed when cstore() is called by 
                   15762: structuretags::finalize_storage().
1.191     harris41 15763: 
                   15764: =item *
                   15765: 
1.1269    raeburn  15766: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   15767: but uses critical subroutine
1.191     harris41 15768: 
                   15769: =item *
                   15770: 
1.243     albertel 15771: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15772: all args are optional
1.191     harris41 15773: 
                   15774: =item *
                   15775: 
1.717     albertel 15776: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15777: dumps the complete (or key matching regexp) namespace into a hash
                   15778: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15779: normally &store()ed into
                   15780: 
                   15781: $range should be either an integer '100' (give me the first 100
                   15782:                                            matching records)
                   15783:               or be  two integers sperated by a - with no spaces
                   15784:                  '30-50' (give me the 30th through the 50th matching
                   15785:                           records)
                   15786: 
                   15787: 
                   15788: =item *
                   15789: 
1.1269    raeburn  15790: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15791: replaces a &store() version of data with a replacement set of data
                   15792: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  15793: reference. If $tolog is true, the transaction is logged in the courselog
                   15794: with an action=PUTSTORE.
1.717     albertel 15795: 
                   15796: =item *
                   15797: 
1.243     albertel 15798: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15799: works very similar to store/cstore, but all data is stored in a
                   15800: temporary location and can be reset using tmpreset, $storehash should
                   15801: be a hash reference, returns nothing on success
1.191     harris41 15802: 
                   15803: =item *
                   15804: 
1.243     albertel 15805: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15806: similar to restore, but all data is stored in a temporary location and
                   15807: can be reset using tmpreset. Returns a hash of values on success,
                   15808: error string otherwise.
1.191     harris41 15809: 
                   15810: =item *
                   15811: 
1.243     albertel 15812: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15813: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15814: 
                   15815: =item *
                   15816: 
1.243     albertel 15817: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15818: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15819: 
                   15820: =item *
                   15821: 
1.243     albertel 15822: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15823: namesp ($udom and $uname are optional)
1.191     harris41 15824: 
                   15825: =item *
                   15826: 
1.702     albertel 15827: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15828: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15829: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15830: 
1.702     albertel 15831: $range should be either an integer '100' (give me the first 100
                   15832:                                            matching records)
                   15833:               or be  two integers sperated by a - with no spaces
                   15834:                  '30-50' (give me the 30th through the 50th matching
                   15835:                           records)
1.449     matthew  15836: =item *
                   15837: 
                   15838: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15839: $store can be a scalar, an array reference, or if the amount to be 
                   15840: incremented is > 1, a hash reference.
                   15841: 
                   15842: ($udom and $uname are optional)
1.191     harris41 15843: 
                   15844: =item *
                   15845: 
1.243     albertel 15846: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15847: ($udom and $uname are optional)
1.191     harris41 15848: 
                   15849: =item *
                   15850: 
1.243     albertel 15851: cput($namespace,$storehash,$udom,$uname) : critical put
                   15852: ($udom and $uname are optional)
1.191     harris41 15853: 
                   15854: =item *
                   15855: 
1.748     albertel 15856: newput($namespace,$storehash,$udom,$uname) :
                   15857: 
                   15858: Attempts to store the items in the $storehash, but only if they don't
                   15859: currently exist, if this succeeds you can be certain that you have 
                   15860: successfully created a new key value pair in the $namespace db.
                   15861: 
                   15862: 
                   15863: Args:
                   15864:  $namespace: name of database to store values to
                   15865:  $storehash: hashref to store to the db
                   15866:  $udom: (optional) domain of user containing the db
                   15867:  $uname: (optional) name of user caontaining the db
                   15868: 
                   15869: Returns:
                   15870:  'ok' -> succeeded in storing all keys of $storehash
                   15871:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15872:                         least <key> already existed in the db (other
                   15873:                         requested keys may also already exist)
1.967     bisitz   15874:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15875:  'con_lost' -> unable to contact request server
                   15876:  'refused' -> action was not allowed by remote machine
                   15877: 
                   15878: 
                   15879: =item *
                   15880: 
1.243     albertel 15881: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15882: reference filled in from namesp (encrypts the return communication)
                   15883: ($udom and $uname are optional)
1.191     harris41 15884: 
                   15885: =item *
                   15886: 
1.243     albertel 15887: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15888: critical subroutine
                   15889: 
1.806     raeburn  15890: =item *
                   15891: 
1.860     raeburn  15892: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15893: array reference filled in from namespace found in domain level on either
                   15894: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15895: 
                   15896: =item *
                   15897: 
1.860     raeburn  15898: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15899: domain level either on specified domain server ($uhome) or primary domain 
                   15900: server ($udom and $uhome are optional)
1.806     raeburn  15901: 
1.943     raeburn  15902: =item * 
                   15903: 
1.1240    raeburn  15904: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   15905: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15906: the target domain.
                   15907: 
                   15908: May also include additional key => value pairs for the following groups:
                   15909: 
                   15910: =over
                   15911: 
                   15912: =item
                   15913: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15914: 
                   15915: =over
                   15916: 
                   15917: =item defaultquota, authorquota
                   15918: 
                   15919: =back
                   15920: 
                   15921: =item
                   15922: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15923: portfolio for users).
                   15924: 
                   15925: =over
                   15926: 
                   15927: =item
                   15928: aboutme, blog, webdav, portfolio
                   15929: 
                   15930: =back
                   15931: 
                   15932: =item
                   15933: requestcourses: ability to request courses, and how requests are processed.
                   15934: 
                   15935: =over
                   15936: 
                   15937: =item
1.1305    raeburn  15938: official, unofficial, community, textbook, placement
1.1240    raeburn  15939: 
                   15940: =back
                   15941: 
                   15942: =item
                   15943: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15944: 
                   15945: =over
                   15946: 
                   15947: =item
1.1256    raeburn  15948: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  15949: 
                   15950: =back
                   15951: 
                   15952: =item
                   15953: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15954: for course's uploaded content.
                   15955: 
                   15956: =over
                   15957: 
                   15958: =item
1.1246    raeburn  15959: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  15960: communityquota, textbookquota, placementquota
1.1240    raeburn  15961: 
                   15962: =back
                   15963: 
                   15964: =item
                   15965: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15966: on your servers.
                   15967: 
                   15968: =over
                   15969: 
                   15970: =item 
                   15971: remotesessions, hostedsessions
                   15972: 
                   15973: =back
                   15974: 
                   15975: =back
                   15976: 
                   15977: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15978: utility to create a configuration.db file on a domain's primary library server 
                   15979: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15980: -- corresponding values are authentication type (internal, krb4, krb5,
                   15981: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   15982: will be available. Values are retrieved from cache (if current), unless the
                   15983: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15984: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15985: 
                   15986: Typical usage:
1.943     raeburn  15987: 
1.1240    raeburn  15988: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15989: 
1.243     albertel 15990: =back
                   15991: 
                   15992: =head2 Network Status Functions
                   15993: 
                   15994: =over 4
1.191     harris41 15995: 
                   15996: =item *
                   15997: 
1.1137    raeburn  15998: dirlist() : return directory list based on URI (first arg).
                   15999: 
                   16000: Inputs: 1 required, 5 optional.
                   16001: 
                   16002: =over
                   16003: 
                   16004: =item 
                   16005: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   16006: 
                   16007: =item
                   16008: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   16009: 
                   16010: =item
                   16011: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   16012: 
                   16013: =item
                   16014: $getpropath - boolean: 1 if prepend path using &propath(). 
                   16015: 
                   16016: =item
                   16017: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   16018: 
                   16019: =item 
                   16020: $alternateRoot - path to prepend in place of path from $uri.
                   16021: 
                   16022: =back
                   16023: 
                   16024: Returns: Array of up to two items.
                   16025: 
                   16026: =over
                   16027: 
                   16028: a reference to an array of files/subdirectories
                   16029: 
                   16030: =over
                   16031: 
                   16032: Each element in the array of files/subdirectories is a & separated list of
                   16033: item name and the result of running stat on the item.  If dirlist was requested
                   16034: for a file instead of a directory, the item name will be ''. For a directory 
                   16035: listing, if the item is a metadata file, the element will end &N&M 
                   16036: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   16037: default copyright set (1).  
                   16038: 
                   16039: =back
                   16040: 
                   16041: a scalar containing error condition (if encountered).
                   16042: 
                   16043: =over
                   16044: 
                   16045: =item 
                   16046: no_host (no homeserver identified for $username:$domain).
                   16047: 
                   16048: =item 
                   16049: no_such_host (server contacted for listing not identified as valid host).
                   16050: 
                   16051: =item 
                   16052: con_lost (connection to remote server failed).
                   16053: 
                   16054: =item 
                   16055: refused (invalid $username:$domain received on lond side).
                   16056: 
                   16057: =item 
                   16058: no_such_dir (directory at specified path on lond side does not exist). 
                   16059: 
                   16060: =item 
                   16061: empty (directory at specified path on lond side is empty).
                   16062: 
                   16063: =over
                   16064: 
                   16065: This is currently not encountered because the &ls3, &ls2, 
                   16066: &ls (_handler) routines on the lond side do not filter out
                   16067: . and .. from a directory listing. 
                   16068: 
                   16069: =back
                   16070: 
                   16071: =back
                   16072: 
                   16073: =back
1.191     harris41 16074: 
                   16075: =item *
                   16076: 
1.243     albertel 16077: spareserver() : find server with least workload from spare.tab
                   16078: 
1.986     foxr     16079: 
                   16080: =item *
                   16081: 
                   16082: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   16083: if there is no corresponding loncapa host.
                   16084: 
1.243     albertel 16085: =back
                   16086: 
1.986     foxr     16087: 
1.243     albertel 16088: =head2 Apache Request
                   16089: 
                   16090: =over 4
1.191     harris41 16091: 
                   16092: =item *
                   16093: 
1.243     albertel 16094: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   16095: localhost, posts hash
                   16096: 
                   16097: =back
                   16098: 
                   16099: =head2 Data to String to Data
                   16100: 
                   16101: =over 4
1.191     harris41 16102: 
                   16103: =item *
                   16104: 
1.243     albertel 16105: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   16106: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 16107: 
                   16108: =item *
                   16109: 
1.243     albertel 16110: hashref2str($hashref) : convert a hashref into a string complete with
                   16111: escaping and '=' and '&' separators, supports elements that are
                   16112: arrayrefs and hashrefs
1.191     harris41 16113: 
                   16114: =item *
                   16115: 
1.243     albertel 16116: arrayref2str($arrayref) : convert an arrayref into a string complete
                   16117: with escaping and '&' separators, supports elements that are arrayrefs
                   16118: and hashrefs
1.191     harris41 16119: 
                   16120: =item *
                   16121: 
1.243     albertel 16122: str2hash($string) : convert string to hash using unescaping and
                   16123: splitting on '=' and '&', supports elements that are arrayrefs and
                   16124: hashrefs
1.191     harris41 16125: 
                   16126: =item *
                   16127: 
1.243     albertel 16128: str2array($string) : convert string to hash using unescaping and
                   16129: splitting on '&', supports elements that are arrayrefs and hashrefs
                   16130: 
                   16131: =back
                   16132: 
                   16133: =head2 Logging Routines
                   16134: 
                   16135: 
                   16136: These routines allow one to make log messages in the lonnet.log and
                   16137: lonnet.perm logfiles.
1.191     harris41 16138: 
1.1119    foxr     16139: =over 4
                   16140: 
1.191     harris41 16141: =item *
                   16142: 
1.243     albertel 16143: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 16144: 
                   16145: =item *
                   16146: 
1.243     albertel 16147: logthis() : append message to the normal lonnet.log file, it gets
                   16148: preiodically rolled over and deleted.
1.191     harris41 16149: 
                   16150: =item *
                   16151: 
1.243     albertel 16152: logperm() : append a permanent message to lonnet.perm.log, this log
                   16153: file never gets deleted by any automated portion of the system, only
                   16154: messages of critical importance should go in here.
                   16155: 
1.1119    foxr     16156: 
1.243     albertel 16157: =back
                   16158: 
                   16159: =head2 General File Helper Routines
                   16160: 
                   16161: =over 4
1.191     harris41 16162: 
                   16163: =item *
                   16164: 
1.481     raeburn  16165: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   16166: (a) files in /uploaded
                   16167:   (i) If a local copy of the file exists - 
                   16168:       compares modification date of local copy with last-modified date for 
                   16169:       definitive version stored on home server for course. If local copy is 
                   16170:       stale, requests a new version from the home server and stores it. 
                   16171:       If the original has been removed from the home server, then local copy 
                   16172:       is unlinked.
                   16173:   (ii) If local copy does not exist -
                   16174:       requests the file from the home server and stores it. 
                   16175:   
                   16176:   If $caller is 'uploadrep':  
                   16177:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   16178:     for request for files originally uploaded via DOCS. 
                   16179:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   16180:   
                   16181:   Otherwise:
                   16182:      This indicates a call from the content generation phase of the request.
                   16183:      -  returns the entire contents of the file or -1.
                   16184:      
                   16185: (b) files in /res
                   16186:    - returns the entire contents of a file or -1; 
                   16187:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 16188: 
1.712     albertel 16189: 
                   16190: =item *
                   16191: 
                   16192: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   16193:                   reference
                   16194: 
                   16195: returns either a stat() list of data about the file or an empty list
                   16196: if the file doesn't exist or couldn't find out about it (connection
                   16197: problems or user unknown)
                   16198: 
1.191     harris41 16199: =item *
                   16200: 
1.243     albertel 16201: filelocation($dir,$file) : returns file system location of a file
                   16202: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   16203: directory that relative $file lookups are to looked in ($dir of /a/dir
                   16204: and a file of ../bob will become /a/bob)
1.191     harris41 16205: 
                   16206: =item *
                   16207: 
                   16208: hreflocation($dir,$file) : returns file system location or a URL; same as
                   16209: filelocation except for hrefs
                   16210: 
                   16211: =item *
                   16212: 
1.1261    raeburn  16213: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   16214: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 16215: 
1.243     albertel 16216: =back
                   16217: 
1.608     albertel 16218: =head2 Usererfile file routines (/uploaded*)
                   16219: 
                   16220: =over 4
                   16221: 
                   16222: =item *
                   16223: 
                   16224: userfileupload(): main rotine for putting a file in a user or course's
                   16225:                   filespace, arguments are,
                   16226: 
1.620     albertel 16227:  formname - required - this is the name of the element in $env where the
1.608     albertel 16228:            filename, and the contents of the file to create/modifed exist
1.620     albertel 16229:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   16230:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  16231:  context - if coursedoc, store the file in the course of the active role
                   16232:              of the current user; 
                   16233:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   16234:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 16235:  subdir - required - subdirectory to put the file in under ../userfiles/
                   16236:          if undefined, it will be placed in "unknown"
                   16237: 
                   16238:  (This routine calls clean_filename() to remove any dangerous
                   16239:  characters from the filename, and then calls finuserfileupload() to
                   16240:  complete the transaction)
                   16241: 
                   16242:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16243:  and /adm/notfound.html if unsuccessful
                   16244: 
                   16245: =item *
                   16246: 
                   16247: clean_filename(): routine for cleaing a filename up for storage in
                   16248:                  userfile space, argument is:
                   16249: 
                   16250:  filename - proposed filename
                   16251: 
                   16252: returns: the new clean filename
                   16253: 
                   16254: =item *
                   16255: 
1.1090    raeburn  16256: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16257: userspace, probably shouldn't be called directly
                   16258: 
                   16259:   docuname: username or courseid of destination for the file
                   16260:   docudom: domain of user/course of destination for the file
                   16261:   formname: same as for userfileupload()
1.1090    raeburn  16262:   fname: filename (including subdirectories) for the file
                   16263:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401    raeburn  16264:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16265:   allfiles: reference to hash used to store objects found by parser
                   16266:   codebase: reference to hash used for codebases of java objects found by parser
                   16267:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16268:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16269:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   16270:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   16271:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   16272:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  16273:   mimetype: reference to scalar to accommodate mime type determined
                   16274:             from File::MMagic if $parser = parse.
1.608     albertel 16275: 
                   16276:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  16277:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   16278:  was 'overwrite').
                   16279:  
1.608     albertel 16280: 
                   16281: =item *
                   16282: 
                   16283: renameuserfile(): renames an existing userfile to a new name
                   16284: 
                   16285:   Args:
                   16286:    docuname: username or courseid of destination for the file
                   16287:    docudom: domain of user/course of destination for the file
                   16288:    old: current file name (including any subdirs under userfiles)
                   16289:    new: desired file name (including any subdirs under userfiles)
                   16290: 
                   16291: =item *
                   16292: 
                   16293: mkdiruserfile(): creates a directory is a userfiles dir
                   16294: 
                   16295:   Args:
                   16296:    docuname: username or courseid of destination for the file
                   16297:    docudom: domain of user/course of destination for the file
                   16298:    dir: dir to create (including any subdirs under userfiles)
                   16299: 
                   16300: =item *
                   16301: 
                   16302: removeuserfile(): removes a file that exists in userfiles
                   16303: 
                   16304:   Args:
                   16305:    docuname: username or courseid of destination for the file
                   16306:    docudom: domain of user/course of destination for the file
                   16307:    fname: filname to delete (including any subdirs under userfiles)
                   16308: 
                   16309: =item *
                   16310: 
                   16311: removeuploadedurl(): convience function for removeuserfile()
                   16312: 
                   16313:   Args:
                   16314:    url:  a full /uploaded/... url to delete
                   16315: 
1.747     albertel 16316: =item * 
                   16317: 
                   16318: get_portfile_permissions():
                   16319:   Args:
                   16320:     domain: domain of user or course contain the portfolio files
                   16321:     user: name of user or num of course contain the portfolio files
                   16322:   Returns:
                   16323:     hashref of a dump of the proper file_permissions.db
                   16324:    
                   16325: 
                   16326: =item * 
                   16327: 
                   16328: get_access_controls():
                   16329: 
                   16330: Args:
                   16331:   current_permissions: the hash ref returned from get_portfile_permissions()
                   16332:   group: (optional) the group you want the files associated with
                   16333:   file: (optional) the file you want access info on
                   16334: 
                   16335: Returns:
1.749     raeburn  16336:     a hash (keys are file names) of hashes containing
                   16337:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   16338:         values are XML containing access control settings (see below) 
1.747     albertel 16339: 
                   16340: Internal notes:
                   16341: 
1.749     raeburn  16342:  access controls are stored in file_permissions.db as key=value pairs.
                   16343:     key -> path to file/file_name\0uniqueID:scope_end_start
                   16344:         where scope -> public,guest,course,group,domains or users.
                   16345:               end -> UNIX time for end of access (0 -> no end date)
                   16346:               start -> UNIX time for start of access
                   16347: 
                   16348:     value -> XML description of access control
                   16349:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   16350:             <start></start>
                   16351:             <end></end>
                   16352: 
                   16353:             <password></password>  for scope type = guest
                   16354: 
                   16355:             <domain></domain>     for scope type = course or group
                   16356:             <number></number>
                   16357:             <roles id="">
                   16358:              <role></role>
                   16359:              <access></access>
                   16360:              <section></section>
                   16361:              <group></group>
                   16362:             </roles>
                   16363: 
                   16364:             <dom></dom>         for scope type = domains
                   16365: 
                   16366:             <users>             for scope type = users
                   16367:              <user>
                   16368:               <uname></uname>
                   16369:               <udom></udom>
                   16370:              </user>
                   16371:             </users>
                   16372:            </scope> 
                   16373:               
                   16374:  Access data is also aggregated for each file in an additional key=value pair:
                   16375:  key -> path to file/file_name\0accesscontrol 
                   16376:  value -> reference to hash
                   16377:           hash contains key = value pairs
                   16378:           where key = uniqueID:scope_end_start
                   16379:                 value = UNIX time record was last updated
                   16380: 
                   16381:           Used to improve speed of look-ups of access controls for each file.  
                   16382:  
                   16383:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   16384: 
1.1198    raeburn  16385: =item *
                   16386: 
1.749     raeburn  16387: modify_access_controls():
                   16388: 
                   16389: Modifies access controls for a portfolio file
                   16390: Args
                   16391: 1. file name
                   16392: 2. reference to hash of required changes,
                   16393: 3. domain
                   16394: 4. username
                   16395:   where domain,username are the domain of the portfolio owner 
                   16396:   (either a user or a course) 
                   16397: 
                   16398: Returns:
                   16399: 1. result of additions or updates ('ok' or 'error', with error message). 
                   16400: 2. result of deletions ('ok' or 'error', with error message).
                   16401: 3. reference to hash of any new or updated access controls.
                   16402: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   16403:    key = integer (inbound ID)
1.1198    raeburn  16404:    value = uniqueID
                   16405: 
                   16406: =item *
                   16407: 
                   16408: get_timebased_id():
                   16409: 
                   16410: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   16411: course via the Course Editor (e.g., folders, composite pages, 
                   16412: group bulletin boards).
                   16413: 
                   16414: Args: (first three required; six others optional)
                   16415: 
                   16416: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   16417:    docssequence, or name of group
                   16418: 
                   16419: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   16420:    e.g., num, boardids
                   16421: 
                   16422: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   16423:    file will be named nohist_namespace.db
                   16424: 
                   16425: 4. cdom: domain of course; default is current course domain from %env
                   16426: 
                   16427: 5. cnum: course number; default is current course number from %env
                   16428: 
                   16429: 6. idtype: set to concat if an additional digit is to be appended to the 
                   16430:    unix timestamp to form the suffix, if the plain timestamp is already
                   16431:    in use.  Default is to not do this, but simply increment the unix 
                   16432:    timestamp by 1 until a unique key is obtained.
                   16433: 
                   16434: 7. who: holder of locking key; defaults to user:domain for user.
                   16435: 
                   16436: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   16437:    retrying); default is 3.
                   16438: 
                   16439: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   16440: 
                   16441: Returns:
                   16442: 
                   16443: 1. suffix obtained (numeric)
                   16444: 
                   16445: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   16446: 
                   16447: 3. error: contains (localized) error message if an error occurred.
                   16448: 
1.747     albertel 16449: 
1.608     albertel 16450: =back
                   16451: 
1.243     albertel 16452: =head2 HTTP Helper Routines
                   16453: 
                   16454: =over 4
                   16455: 
1.191     harris41 16456: =item *
                   16457: 
                   16458: escape() : unpack non-word characters into CGI-compatible hex codes
                   16459: 
                   16460: =item *
                   16461: 
                   16462: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   16463: 
1.243     albertel 16464: =back
                   16465: 
                   16466: =head1 PRIVATE SUBROUTINES
                   16467: 
                   16468: =head2 Underlying communication routines (Shouldn't call)
                   16469: 
                   16470: =over 4
                   16471: 
                   16472: =item *
                   16473: 
                   16474: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   16475: 
                   16476: =item *
                   16477: 
                   16478: reply() : uses subreply to send a message to remote machine, logs all failures
                   16479: 
                   16480: =item *
                   16481: 
                   16482: critical() : passes a critical message to another server; if cannot
                   16483: get through then place message in connection buffer directory and
                   16484: returns con_delayed, if incapable of saving message, returns
                   16485: con_failed
                   16486: 
                   16487: =item *
                   16488: 
                   16489: reconlonc() : tries to reconnect lonc client processes.
                   16490: 
                   16491: =back
                   16492: 
                   16493: =head2 Resource Access Logging
                   16494: 
                   16495: =over 4
                   16496: 
                   16497: =item *
                   16498: 
                   16499: flushcourselogs() : flush (save) buffer logs and access logs
                   16500: 
                   16501: =item *
                   16502: 
                   16503: courselog($what) : save message for course in hash
                   16504: 
                   16505: =item *
                   16506: 
                   16507: courseacclog($what) : save message for course using &courselog().  Perform
                   16508: special processing for specific resource types (problems, exams, quizzes, etc).
                   16509: 
1.191     harris41 16510: =item *
                   16511: 
                   16512: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16513: as a PerlChildExitHandler
1.243     albertel 16514: 
                   16515: =back
                   16516: 
                   16517: =head2 Other
                   16518: 
                   16519: =over 4
                   16520: 
                   16521: =item *
                   16522: 
                   16523: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16524: 
                   16525: =back
                   16526: 
                   16527: =cut
1.877     foxr     16528: 

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