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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1402  ! raeburn     4: # $Id: lonnet.pm,v 1.1401 2019/01/27 14:40:02 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 '') &&
                   4362:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/$match_courseid/scantron_orig}) &&
                   4363:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4364:         my %csvcols = %{$config};
                   4365:         my %csvbynum = reverse(%csvcols);
                   4366:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4367:         if (keys(%scantronconf)) {
                   4368:             my %bynum = (
                   4369:                           $scantronconf{CODEstart} => 'CODEstart',
                   4370:                           $scantronconf{IDstart}   => 'IDstart',
                   4371:                           $scantronconf{PaperID}   => 'PaperID',
                   4372:                           $scantronconf{FirstName} => 'FirstName',
                   4373:                           $scantronconf{LastName}  => 'LastName',
                   4374:                           $scantronconf{Qstart}    => 'Qstart',
                   4375:                         );
                   4376:             my @ordered;
                   4377:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4378:                 push (@ordered,$bynum{$item}));
                   4379:             }
                   4380:             my %mapstart = (
                   4381:                               CODEstart => 'CODE',
                   4382:                               IDstart   => 'ID',
                   4383:                               PaperID   => 'PaperID',
                   4384:                               FirstName => 'FirstName',
                   4385:                               LastName  => 'LastName',
                   4386:                               Qstart    => 'FirstQuestion',
                   4387:                            );
                   4388:             my %maplength = (
                   4389:                               CODEstart => 'CODElength',
                   4390:                               IDstart   => 'IDlength',
                   4391:                               PaperID   => 'PaperIDlength',
                   4392:                               FirstName => 'FirstNamelength',
                   4393:                               LastName  => 'LastNamelength',
                   4394:             );
                   4395:             if (open(my $fh,'<',$fullpath)) {
                   4396:                 my $output;
                   4397:                 while (my $line=<$fh>) {
                   4398:                     $line =~ s{[\r\n]+$}{};
                   4399:                     my %found;
                   4400:                     my @values = split(/,/,$line);
                   4401:                     my ($qstart,$record);
                   4402:                     for (my $i=0; $i<@values; $i++) {
                   4403:                         if (($qstart ne '') && ($i > $qstart)) {
                   4404:                             $found{'FirstQuestion'} .= $values[$i];
                   4405:                         } elsif (exists($csvbynum{$i})) {
                   4406:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4407:                                 $qstart = $i;
                   4408:                             } else {
                   4409:                                 $values[$i] =~ s/^\s+//;
                   4410:                                 if ($csvbynum{$i} eq 'PaperID') {
                   4411:                                     while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4412:                                         $values[$i] = '0'.$values[$i];
                   4413:                                     }
                   4414:                                 }
                   4415:                             }
                   4416:                             $found{$csvbynum{$i}} = $values[$i];
                   4417:                         }
                   4418:                     }
                   4419:                     foreach my $item (@ordered) {
                   4420:                         my $currlength = 1+length($record);
                   4421:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4422:                         if ($numspaces > 0) {
                   4423:                             $record .= (' ' x $numspaces);
                   4424:                         }
                   4425:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4426:                             unless ($item eq 'Qstart') {
                   4427:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4428:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4429:                                 }
                   4430:                             }
                   4431:                             $record .= $found{$mapstart{$item}};
                   4432:                         }
                   4433:                     }
                   4434:                     $output .= "$record\n";
                   4435:                 }
                   4436:                 close($fh);
                   4437:                 if ($output) {
                   4438:                     if (open(my $fh,'>',$fullpath)) {
                   4439:                         print $fh $output;
                   4440:                         close($fh);
                   4441:                     }
                   4442:                 }
                   4443:             }
                   4444:         }
                   4445:         return;
                   4446:     }
                   4447: }
                   4448: 
                   4449: sub get_scantron_config {
                   4450:     my ($which,$cdom) = @_;
                   4451:     my @lines = &get_scantronformat_file($cdom);
                   4452:     my %config;
                   4453:     #FIXME probably should move to XML it has already gotten a bit much now
                   4454:     foreach my $line (@lines) {
                   4455:         my ($name,$descrip)=split(/:/,$line);
                   4456:         if ($name ne $which ) { next; }
                   4457:         chomp($line);
                   4458:         my @config=split(/:/,$line);
                   4459:         $config{'name'}=$config[0];
                   4460:         $config{'description'}=$config[1];
                   4461:         $config{'CODElocation'}=$config[2];
                   4462:         $config{'CODEstart'}=$config[3];
                   4463:         $config{'CODElength'}=$config[4];
                   4464:         $config{'IDstart'}=$config[5];
                   4465:         $config{'IDlength'}=$config[6];
                   4466:         $config{'Qstart'}=$config[7];
                   4467:         $config{'Qlength'}=$config[8];
                   4468:         $config{'Qoff'}=$config[9];
                   4469:         $config{'Qon'}=$config[10];
                   4470:         $config{'PaperID'}=$config[11];
                   4471:         $config{'PaperIDlength'}=$config[12];
                   4472:         $config{'FirstName'}=$config[13];
                   4473:         $config{'FirstNamelength'}=$config[14];
                   4474:         $config{'LastName'}=$config[15];
                   4475:         $config{'LastNamelength'}=$config[16];
                   4476:         $config{'BubblesPerRow'}=$config[17];
                   4477:         last;
                   4478:     }
                   4479:     return %config;
                   4480: }
                   4481: 
                   4482: sub get_scantronformat_file {
                   4483:     my ($cdom) = @_;
                   4484:     if ($cdom eq '') {
                   4485:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4486:     }
                   4487:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4488:     my $gottab = 0;
                   4489:     my @lines;
                   4490:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4491:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4492:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4493:             if ($formatfile ne '-1') {
                   4494:                 @lines = split("\n",$formatfile,-1);
                   4495:                 $gottab = 1;
                   4496:             }
                   4497:         }
                   4498:     }
                   4499:     if (!$gottab) {
                   4500:         my $confname = $cdom.'-domainconfig';
                   4501:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4502:         my $formatfile = &getfile($default);
                   4503:         if ($formatfile ne '-1') {
                   4504:             @lines = split("\n",$formatfile,-1);
                   4505:             $gottab = 1;
                   4506:         }
                   4507:     }
                   4508:     if (!$gottab) {
                   4509:         my @domains = &current_machine_domains();
                   4510:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4511:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4512:                 @lines = <$fh>;
                   4513:                 close($fh);
                   4514:             }  
                   4515:         } else {
                   4516:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4517:                 @lines = <$fh>;
                   4518:                 close($fh);
                   4519:             }
                   4520:         }
                   4521:     }
                   4522:     return @lines;
                   4523: }
                   4524: 
1.493     albertel 4525: sub removeuploadedurl {
1.984     neumanie 4526:     my ($url)=@_;	
                   4527:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4528:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4529: }
                   4530: 
                   4531: sub removeuserfile {
                   4532:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4533:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4534:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4535:     if ($result eq 'ok') {	
1.798     raeburn  4536:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4537:             my $metafile = $fname.'.meta';
                   4538:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4539: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4540:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4541:             my $sqlresult = 
1.823     albertel 4542:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4543:                                         'portfolio_metadata',$group,
                   4544:                                         'delete');
1.798     raeburn  4545:         }
                   4546:     }
                   4547:     return $result;
1.257     www      4548: }
1.15      www      4549: 
1.530     albertel 4550: sub mkdiruserfile {
                   4551:     my ($docuname,$docudom,$dir)=@_;
                   4552:     my $home=&homeserver($docuname,$docudom);
                   4553:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4554: }
                   4555: 
1.531     albertel 4556: sub renameuserfile {
                   4557:     my ($docuname,$docudom,$old,$new)=@_;
                   4558:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4559:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4560:                         &escape("$old").':'.&escape("$new"),$home);
                   4561:     if ($result eq 'ok') {
                   4562:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4563:             my $oldmeta = $old.'.meta';
                   4564:             my $newmeta = $new.'.meta';
                   4565:             my $metaresult = 
                   4566:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4567: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4568:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4569:             my $sqlresult = 
1.823     albertel 4570:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4571:                                         'portfolio_metadata',$group,
                   4572:                                         'delete');
1.798     raeburn  4573:         }
                   4574:     }
                   4575:     return $result;
1.531     albertel 4576: }
                   4577: 
1.14      www      4578: # ------------------------------------------------------------------------- Log
                   4579: 
                   4580: sub log {
                   4581:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4582:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4583: }
                   4584: 
                   4585: # ------------------------------------------------------------------ Course Log
1.352     www      4586: #
                   4587: # This routine flushes several buffers of non-mission-critical nature
                   4588: #
1.157     www      4589: 
                   4590: sub flushcourselogs {
1.352     www      4591:     &logthis('Flushing log buffers');
                   4592: #
                   4593: # course logs
                   4594: # This is a log of all transactions in a course, which can be used
                   4595: # for data mining purposes
                   4596: #
                   4597: # It also collects the courseid database, which lists last transaction
                   4598: # times and course titles for all courseids
                   4599: #
                   4600:     my %courseidbuffer=();
1.921     raeburn  4601:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4602:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4603: 		          &escape($courselogs{$crsid}),
                   4604: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4605: 	    delete $courselogs{$crsid};
                   4606:         } else {
                   4607:             &logthis('Failed to flush log buffer for '.$crsid);
                   4608:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4609:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4610:                         " exceeded maximum size, deleting.</font>");
                   4611:                delete $courselogs{$crsid};
                   4612:             }
1.352     www      4613:         }
1.920     raeburn  4614:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4615:             'description' => $coursedescrbuf{$crsid},
                   4616:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4617:             'type'        => $coursetypebuf{$crsid},
                   4618:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4619:         };
1.191     harris41 4620:     }
1.352     www      4621: #
                   4622: # Write course id database (reverse lookup) to homeserver of courses 
                   4623: # Is used in pickcourse
                   4624: #
1.840     albertel 4625:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4626:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4627:                                     $courseidbuffer{$crs_home},
                   4628:                                     $crs_home,'timeonly');
1.352     www      4629:     }
                   4630: #
                   4631: # File accesses
                   4632: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4633: #
1.449     matthew  4634:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4635:         if ($entry =~ /___count$/) {
                   4636:             my ($dom,$name);
1.807     albertel 4637:             ($dom,$name,undef)=
1.811     albertel 4638: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4639:             if (! defined($dom) || $dom eq '' || 
                   4640:                 ! defined($name) || $name eq '') {
1.620     albertel 4641:                 my $cid = $env{'request.course.id'};
                   4642:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4643:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4644:             }
1.450     matthew  4645:             my $value = $accesshash{$entry};
                   4646:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4647:             my %temphash=($url => $value);
1.449     matthew  4648:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4649:             if ($result eq 'ok') {
                   4650:                 delete $accesshash{$entry};
                   4651:             }
                   4652:         } else {
1.811     albertel 4653:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4654:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4655:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4656:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4657:                 delete $accesshash{$entry};
                   4658:             }
1.185     www      4659:         }
1.191     harris41 4660:     }
1.352     www      4661: #
                   4662: # Roles
                   4663: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4664: #
1.800     albertel 4665:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4666:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4667: 	    split(/\:/,$entry);
                   4668:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4669:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4670:                 $rudom,$runame) eq 'ok') {
                   4671: 	    delete $userrolehash{$entry};
                   4672:         }
                   4673:     }
1.662     raeburn  4674: #
1.1334    raeburn  4675: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4676: #
                   4677:     my %domrolebuffer = ();
1.1000    raeburn  4678:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4679:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4680:         if ($domrolebuffer{$rudom}) {
                   4681:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4682:                       '='.&escape($domainrolehash{$entry});
                   4683:         } else {
                   4684:             $domrolebuffer{$rudom}.=&escape($entry).
                   4685:                       '='.&escape($domainrolehash{$entry});
                   4686:         }
                   4687:         delete $domainrolehash{$entry};
                   4688:     }
                   4689:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4690: 	my %servers;
                   4691: 	if (defined(&domain($dom,'primary'))) {
                   4692: 	    my $primary=&domain($dom,'primary');
                   4693: 	    my $hostname=&hostname($primary);
                   4694: 	    $servers{$primary} = $hostname;
                   4695: 	} else { 
                   4696: 	    %servers = &get_servers($dom,'library');
                   4697: 	}
1.841     albertel 4698: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4699: 	    if (&reply('domroleput:'.$dom.':'.
                   4700: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4701: 		last;
                   4702: 	    } else {  
1.841     albertel 4703: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4704: 	    }
1.662     raeburn  4705:         }
                   4706:     }
1.186     www      4707:     $dumpcount++;
1.157     www      4708: }
                   4709: 
                   4710: sub courselog {
                   4711:     my $what=shift;
1.158     www      4712:     $what=time.':'.$what;
1.620     albertel 4713:     unless ($env{'request.course.id'}) { return ''; }
                   4714:     $coursedombuf{$env{'request.course.id'}}=
                   4715:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4716:     $coursenumbuf{$env{'request.course.id'}}=
                   4717:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4718:     $coursehombuf{$env{'request.course.id'}}=
                   4719:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4720:     $coursedescrbuf{$env{'request.course.id'}}=
                   4721:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4722:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4723:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4724:     $courseownerbuf{$env{'request.course.id'}}=
                   4725:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4726:     $coursetypebuf{$env{'request.course.id'}}=
                   4727:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4728:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4729: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4730:     } else {
1.620     albertel 4731: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4732:     }
1.620     albertel 4733:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4734: 	&flushcourselogs();
                   4735:     }
1.158     www      4736: }
                   4737: 
                   4738: sub courseacclog {
                   4739:     my $fnsymb=shift;
1.620     albertel 4740:     unless ($env{'request.course.id'}) { return ''; }
                   4741:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4742:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4743:         $what.=':POST';
1.583     matthew  4744:         # FIXME: Probably ought to escape things....
1.800     albertel 4745: 	foreach my $key (keys(%env)) {
                   4746:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4747:                 my $formitem = $1;
                   4748:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4749:                     $what.=':'.$formitem.'='.$env{$key};
                   4750:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4751:                     $what.=':'.$formitem.'='.$env{$key};
                   4752:                 }
1.158     www      4753:             }
1.191     harris41 4754:         }
1.583     matthew  4755:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4756:         # FIXME: We should not be depending on a form parameter that someone
                   4757:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4758:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4759:             $what.= ':POST';
                   4760:             # FIXME: Probably ought to escape things....
                   4761:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4762:                                  'crsdiscuss') {
1.620     albertel 4763:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4764:             }
                   4765:         }
1.158     www      4766:     }
                   4767:     &courselog($what);
1.149     www      4768: }
                   4769: 
1.185     www      4770: sub countacc {
                   4771:     my $url=&declutter(shift);
1.458     matthew  4772:     return if (! defined($url) || $url eq '');
1.620     albertel 4773:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4774: #
                   4775: # Mark that this url was used in this course
                   4776: #
1.620     albertel 4777:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4778: #
                   4779: # Increase the access count for this resource in this child process
                   4780: #
1.281     www      4781:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4782:     $accesshash{$key}++;
1.185     www      4783: }
1.349     www      4784: 
1.361     www      4785: sub linklog {
                   4786:     my ($from,$to)=@_;
                   4787:     $from=&declutter($from);
                   4788:     $to=&declutter($to);
                   4789:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4790:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4791: }
1.1160    www      4792: 
                   4793: sub statslog {
                   4794:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4795:     if ($users<2) { return; }
                   4796:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4797:             'course'       => $env{'request.course.id'},
                   4798:             'sections'     => '"all"',
                   4799:             'num_students' => $users,
                   4800:             'part'         => $part,
                   4801:             'symb'         => $symb,
                   4802:             'mean_tries'   => $av_attempts,
                   4803:             'deg_of_diff'  => $degdiff});
                   4804:     foreach my $key (keys(%dynstore)) {
                   4805:         $accesshash{$key}=$dynstore{$key};
                   4806:     }
                   4807: }
1.361     www      4808:   
1.349     www      4809: sub userrolelog {
                   4810:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4811:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4812:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4813:        $userrolehash
                   4814:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4815:                     =$tend.':'.$tstart;
1.662     raeburn  4816:     }
1.1169    droeschl 4817:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4818:        $userrolehash
                   4819:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4820:                     =$tend.':'.$tstart;
                   4821:     }
1.1334    raeburn  4822:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4823:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4824:        $domainrolehash
                   4825:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4826:                     = $tend.':'.$tstart;
                   4827:     }
1.351     www      4828: }
                   4829: 
1.957     raeburn  4830: sub courserolelog {
                   4831:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4832:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4833:         my $cdom = $1;
                   4834:         my $cnum = $2;
                   4835:         my $sec = $3;
                   4836:         my $namespace = 'rolelog';
                   4837:         my %storehash = (
                   4838:                            role    => $trole,
                   4839:                            start   => $tstart,
                   4840:                            end     => $tend,
                   4841:                            selfenroll => $selfenroll,
                   4842:                            context    => $context,
                   4843:                         );
                   4844:         if ($trole eq 'gr') {
                   4845:             $namespace = 'groupslog';
                   4846:             $storehash{'group'} = $sec;
                   4847:         } else {
                   4848:             $storehash{'section'} = $sec;
                   4849:         }
1.1188    raeburn  4850:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4851:                    $domain,$cnum,$cdom);
1.1184    raeburn  4852:         if (($trole ne 'st') || ($sec ne '')) {
                   4853:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4854:         }
                   4855:     }
                   4856:     return;
                   4857: }
                   4858: 
1.1184    raeburn  4859: sub domainrolelog {
                   4860:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4861:     if ($area =~ m{^/($match_domain)/$}) {
                   4862:         my $cdom = $1;
                   4863:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4864:         my $namespace = 'rolelog';
                   4865:         my %storehash = (
                   4866:                            role    => $trole,
                   4867:                            start   => $tstart,
                   4868:                            end     => $tend,
                   4869:                            context => $context,
                   4870:                         );
1.1188    raeburn  4871:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4872:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4873:     }
                   4874:     return;
                   4875: 
                   4876: }
                   4877: 
                   4878: sub coauthorrolelog {
                   4879:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4880:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4881:         my $audom = $1;
                   4882:         my $auname = $2;
                   4883:         my $namespace = 'rolelog';
                   4884:         my %storehash = (
                   4885:                            role    => $trole,
                   4886:                            start   => $tstart,
                   4887:                            end     => $tend,
                   4888:                            context => $context,
                   4889:                         );
1.1188    raeburn  4890:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4891:                    $domain,$auname,$audom);
1.1184    raeburn  4892:     }
                   4893:     return;
                   4894: }
                   4895: 
1.351     www      4896: sub get_course_adv_roles {
1.948     raeburn  4897:     my ($cid,$codes) = @_;
1.620     albertel 4898:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4899:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4900:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4901:     my %nothide=();
1.800     albertel 4902:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4903:         if ($user !~ /:/) {
                   4904: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4905:         } else {
                   4906:             $nothide{$user}=1;
                   4907:         }
1.470     www      4908:     }
1.1219    raeburn  4909:     my @possdoms = ($coursehash{'domain'});
                   4910:     if ($coursehash{'checkforpriv'}) {
                   4911:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4912:     }
1.351     www      4913:     my %returnhash=();
                   4914:     my %dumphash=
                   4915:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4916:     my $now=time;
1.997     raeburn  4917:     my %privileged;
1.1000    raeburn  4918:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4919: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4920:         if (($tstart) && ($tstart<0)) { next; }
                   4921:         if (($tend) && ($tend<$now)) { next; }
                   4922:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4923:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4924: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4925:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4926:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4927: 	if ($role eq 'cr') { next; }
1.948     raeburn  4928:         if ($codes) {
                   4929:             if ($section) { $role .= ':'.$section; }
                   4930:             if ($returnhash{$role}) {
                   4931:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4932:             } else {
                   4933:                 $returnhash{$role}=$username.':'.$domain;
                   4934:             }
1.351     www      4935:         } else {
1.988     raeburn  4936:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4937:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4938:             if ($returnhash{$key}) {
                   4939: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4940:             } else {
                   4941:                 $returnhash{$key}=$username.':'.$domain;
                   4942:             }
1.351     www      4943:         }
1.948     raeburn  4944:     }
1.400     www      4945:     return %returnhash;
                   4946: }
                   4947: 
                   4948: sub get_my_roles {
1.937     raeburn  4949:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4950:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4951:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4952:     my (%dumphash,%nothide);
1.1086    raeburn  4953:     if ($context eq 'userroles') {
1.1166    raeburn  4954:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4955:     } else {
1.1219    raeburn  4956:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4957:         if ($hidepriv) {
                   4958:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4959:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4960:                 if ($user !~ /:/) {
                   4961:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4962:                 } else {
                   4963:                     $nothide{$user} = 1;
                   4964:                 }
                   4965:             }
                   4966:         }
1.858     raeburn  4967:     }
1.400     www      4968:     my %returnhash=();
                   4969:     my $now=time;
1.999     raeburn  4970:     my %privileged;
1.800     albertel 4971:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4972:         my ($role,$tend,$tstart);
                   4973:         if ($context eq 'userroles') {
1.1149    raeburn  4974:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4975: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4976:         } else {
                   4977:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4978:         }
1.400     www      4979:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4980:         my $status = 'active';
1.939     raeburn  4981:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4982:             $status = 'previous';
                   4983:         } 
                   4984:         if (($tstart) && ($now<$tstart)) {
                   4985:             $status = 'future';
                   4986:         }
                   4987:         if (ref($types) eq 'ARRAY') {
                   4988:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4989:                 next;
                   4990:             } 
                   4991:         } else {
                   4992:             if ($status ne 'active') {
                   4993:                 next;
                   4994:             }
                   4995:         }
1.867     raeburn  4996:         my ($rolecode,$username,$domain,$section,$area);
                   4997:         if ($context eq 'userroles') {
1.1186    raeburn  4998:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4999:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5000:         } else {
                   5001:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5002:         }
1.832     raeburn  5003:         if (ref($roledoms) eq 'ARRAY') {
                   5004:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5005:                 next;
                   5006:             }
                   5007:         }
                   5008:         if (ref($roles) eq 'ARRAY') {
                   5009:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5010:                 if ($role =~ /^cr\//) {
                   5011:                     if (!grep(/^cr$/,@{$roles})) {
                   5012:                         next;
                   5013:                     }
1.1104    raeburn  5014:                 } elsif ($role =~ /^gr\//) {
                   5015:                     if (!grep(/^gr$/,@{$roles})) {
                   5016:                         next;
                   5017:                     }
1.922     raeburn  5018:                 } else {
                   5019:                     next;
                   5020:                 }
1.832     raeburn  5021:             }
1.867     raeburn  5022:         }
1.937     raeburn  5023:         if ($hidepriv) {
1.1219    raeburn  5024:             my @privroles = ('dc','su');
1.999     raeburn  5025:             if ($context eq 'userroles') {
1.1219    raeburn  5026:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5027:             } else {
1.1219    raeburn  5028:                 my $possdoms = [$domain];
                   5029:                 if (ref($roledoms) eq 'ARRAY') {
                   5030:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  5031:                 }
1.1219    raeburn  5032:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5033:                     if (!$nothide{$username.':'.$domain}) {
                   5034:                         next;
                   5035:                     }
                   5036:                 }
1.937     raeburn  5037:             }
                   5038:         }
1.933     raeburn  5039:         if ($withsec) {
                   5040:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5041:                 $tstart.':'.$tend;
                   5042:         } else {
                   5043:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5044:         }
1.832     raeburn  5045:     }
1.373     www      5046:     return %returnhash;
1.399     www      5047: }
                   5048: 
1.1333    raeburn  5049: sub get_all_adhocroles {
                   5050:     my ($dom) = @_;
                   5051:     my @roles_by_num = ();
                   5052:     my %domdefaults = &get_domain_defaults($dom);
                   5053:     my (%description,%access_in_dom,%access_info);
                   5054:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5055:         my $count = 0;
                   5056:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5057:         my %ordered;
                   5058:         foreach my $role (sort(keys(%domcurrent))) {
                   5059:             my ($order,$desc,$access_in_dom);
                   5060:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5061:                 $order = $domcurrent{$role}{'order'};
                   5062:                 $desc = $domcurrent{$role}{'desc'};
                   5063:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5064:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5065:             }
                   5066:             if ($order eq '') {
                   5067:                 $order = $count;
                   5068:             }
                   5069:             $ordered{$order} = $role;
                   5070:             if ($desc ne '') {
                   5071:                 $description{$role} = $desc;
                   5072:             } else {
                   5073:                 $description{$role}= $role;
                   5074:             }
                   5075:             $count++;
                   5076:         }
                   5077:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5078:             push(@roles_by_num,$ordered{$item});
                   5079:         }
                   5080:     }
                   5081:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5082: }
                   5083: 
1.1332    raeburn  5084: sub get_my_adhocroles {
1.1333    raeburn  5085:     my ($cid,$checkreg) = @_;
                   5086:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5087:     if ($env{'request.course.id'} eq $cid) {
                   5088:         $cdom = $env{'course.'.$cid.'.domain'};
                   5089:         $cnum = $env{'course.'.$cid.'.num'};
                   5090:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5091:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5092:         $cdom = $1;
                   5093:         $cnum = $2;
                   5094:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5095:                                      $cdom,$cnum);
                   5096:     }
                   5097:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5098:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5099:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5100:         if ($rosterhash{$user} ne '') {
                   5101:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5102:             return ([],{}) if ($type eq 'auto');
                   5103:         }
                   5104:     }
                   5105:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  5106:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  5107:             my $then=$env{'user.login.time'};
                   5108:             my $update=$env{'user.update.time'};
1.1335    raeburn  5109:             if (!$update) {
                   5110:                 $update = $then;
                   5111:             }
                   5112:             my @liveroles;
1.1334    raeburn  5113:             foreach my $role ('dh','da') {
                   5114:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  5115:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  5116:                     my $limit = $update;
                   5117:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5118:                         $limit = $then;
                   5119:                     }
1.1335    raeburn  5120:                     my $activerole = 1;
                   5121:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5122:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5123:                     if ($activerole) {
                   5124:                         push(@liveroles,$role);
                   5125:                     }
1.1334    raeburn  5126:                 }
1.1332    raeburn  5127:             }
1.1335    raeburn  5128:             if (@liveroles) {
1.1332    raeburn  5129:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  5130:                     my ($accessref,$accessinfo,%access_in_dom);
                   5131:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5132:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5133:                         if (@{$roles_by_num}) {
1.1332    raeburn  5134:                             my %settings;
                   5135:                             if ($env{'request.course.id'} eq $cid) {
                   5136:                                 foreach my $envkey (keys(%env)) {
                   5137:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5138:                                         $settings{$1} = $env{$envkey};
                   5139:                                     }
                   5140:                                 }
                   5141:                             } else {
                   5142:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5143:                             }
                   5144:                             my %setincrs;
                   5145:                             if ($settings{'internal.adhocaccess'}) {
                   5146:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5147:                             }
                   5148:                             my @statuses;
                   5149:                             if ($env{'environment.inststatus'}) {
                   5150:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5151:                             }
                   5152:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  5153:                             if (ref($accessref) eq 'HASH') {
                   5154:                                 %access_in_dom = %{$accessref};
                   5155:                             }
                   5156:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  5157:                                 my ($curraccess,@okstatus,@personnel);
                   5158:                                 if ($setincrs{$role}) {
                   5159:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5160:                                     if ($curraccess eq 'status') {
                   5161:                                         @okstatus = split(/\&/,$rest);
                   5162:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5163:                                         @personnel = split(/\&/,$rest);
                   5164:                                     }
                   5165:                                 } else {
                   5166:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  5167:                                     if (ref($accessinfo) eq 'HASH') {
                   5168:                                         if ($curraccess eq 'status') {
                   5169:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5170:                                                 @okstatus = @{$accessinfo->{$role}};
                   5171:                                             }
                   5172:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5173:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5174:                                                 @personnel = @{$accessinfo->{$role}};
                   5175:                                             }
1.1332    raeburn  5176:                                         }
                   5177:                                     }
                   5178:                                 }
                   5179:                                 if ($curraccess eq 'none') {
                   5180:                                     next;
                   5181:                                 } elsif ($curraccess eq 'all') {
                   5182:                                     push(@possroles,$role);
1.1336    raeburn  5183:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  5184:                                     if (grep(/^dh$/,@liveroles)) {
                   5185:                                         push(@possroles,$role);
                   5186:                                     } else {
                   5187:                                         next;
                   5188:                                     }
1.1336    raeburn  5189:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  5190:                                     if (grep(/^da$/,@liveroles)) {
                   5191:                                         push(@possroles,$role);
                   5192:                                     } else {
                   5193:                                         next;
                   5194:                                     }
1.1332    raeburn  5195:                                 } elsif ($curraccess eq 'status') {
                   5196:                                     if (@okstatus) {
                   5197:                                         if (!@statuses) {
                   5198:                                             if (grep(/^default$/,@okstatus)) {
                   5199:                                                 push(@possroles,$role);
                   5200:                                             }
                   5201:                                         } else {
                   5202:                                             foreach my $status (@okstatus) {
                   5203:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5204:                                                     push(@possroles,$role);
                   5205:                                                     last;
                   5206:                                                 }
                   5207:                                             }
                   5208:                                         }
                   5209:                                     }
                   5210:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5211:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5212:                                         if ($curraccess eq 'exc') {
                   5213:                                             push(@possroles,$role);
                   5214:                                         }
                   5215:                                     } elsif ($curraccess eq 'inc') {
                   5216:                                         push(@possroles,$role);
                   5217:                                     }
                   5218:                                 }
                   5219:                             }
                   5220:                         }
                   5221:                     }
                   5222:                 }
                   5223:             }
                   5224:         }
                   5225:     }
1.1333    raeburn  5226:     unless (ref($description) eq 'HASH') {
                   5227:         if (ref($roles_by_num) eq 'ARRAY') {
                   5228:             my %desc;
                   5229:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5230:             $description = \%desc;
                   5231:         } else {
                   5232:             $description = {};
                   5233:         }
                   5234:     }
                   5235:     return (\@possroles,$description);
1.1332    raeburn  5236: }
                   5237: 
1.399     www      5238: # ----------------------------------------------------- Frontpage Announcements
                   5239: #
                   5240: #
                   5241: 
                   5242: sub postannounce {
                   5243:     my ($server,$text)=@_;
1.844     albertel 5244:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5245:     unless ($text=~/\w/) { $text=''; }
                   5246:     return &reply('setannounce:'.&escape($text),$server);
                   5247: }
                   5248: 
                   5249: sub getannounce {
1.448     albertel 5250: 
1.1359    raeburn  5251:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5252: 	my $announcement='';
1.800     albertel 5253: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5254: 	close($fh);
1.399     www      5255: 	if ($announcement=~/\w/) { 
                   5256: 	    return 
                   5257:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5258:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5259: 	} else {
                   5260: 	    return '';
                   5261: 	}
                   5262:     } else {
                   5263: 	return '';
                   5264:     }
1.351     www      5265: }
1.353     www      5266: 
                   5267: # ---------------------------------------------------------- Course ID routines
                   5268: # Deal with domain's nohist_courseid.db files
                   5269: #
                   5270: 
                   5271: sub courseidput {
1.921     raeburn  5272:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5273:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5274:     my $outcome;
                   5275:     if ($caller eq 'timeonly') {
                   5276:         my $cids = '';
                   5277:         foreach my $item (keys(%$storehash)) {
                   5278:             $cids.=&escape($item).'&';
                   5279:         }
                   5280:         $cids=~s/\&$//;
                   5281:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5282:                           $coursehome);       
                   5283:     } else {
                   5284:         my $items = '';
                   5285:         foreach my $item (keys(%$storehash)) {
                   5286:             $items.= &escape($item).'='.
                   5287:                      &freeze_escape($$storehash{$item}).'&';
                   5288:         }
                   5289:         $items=~s/\&$//;
                   5290:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5291:                           $coursehome);
1.918     raeburn  5292:     }
                   5293:     if ($outcome eq 'unknown_cmd') {
                   5294:         my $what;
                   5295:         foreach my $cid (keys(%$storehash)) {
                   5296:             $what .= &escape($cid).'=';
1.921     raeburn  5297:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5298:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5299:             }
                   5300:             $what =~ s/\:$/&/;
                   5301:         }
                   5302:         $what =~ s/\&$//;  
                   5303:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5304:     } else {
                   5305:         return $outcome;
                   5306:     }
1.353     www      5307: }
                   5308: 
                   5309: sub courseiddump {
1.921     raeburn  5310:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5311:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5312:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  5313:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  5314:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5315:     my $as_hash = 1;
                   5316:     my %returnhash;
                   5317:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5318:     my %libserv = &all_library();
                   5319:     foreach my $tryserver (keys(%libserv)) {
                   5320:         if ( (  $hostidflag == 1 
                   5321: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5322: 	     || (!defined($hostidflag)) ) {
                   5323: 
1.918     raeburn  5324: 	    if (($domfilter eq '') ||
                   5325: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5326:                 my $rep;
                   5327:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5328:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5329:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5330:                                 &escape($descfilter), &escape($instcodefilter), 
                   5331:                                 &escape($ownerfilter), &escape($coursefilter),
                   5332:                                 &escape($typefilter), &escape($regexp_ok), 
                   5333:                                 $as_hash, &escape($selfenrollonly), 
                   5334:                                 &escape($catfilter), $showhidden, $caller, 
                   5335:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5336:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5337:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5338:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5339:                 } else {
                   5340:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5341:                              $sincefilter.':'.&escape($descfilter).':'.
                   5342:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5343:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5344:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5345:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5346:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5347:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5348:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5349:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5350:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5351:                 }
                   5352:                      
1.918     raeburn  5353:                 my @pairs=split(/\&/,$rep);
                   5354:                 foreach my $item (@pairs) {
                   5355:                     my ($key,$value)=split(/\=/,$item,2);
                   5356:                     $key = &unescape($key);
                   5357:                     next if ($key =~ /^error: 2 /);
                   5358:                     my $result = &thaw_unescape($value);
                   5359:                     if (ref($result) eq 'HASH') {
                   5360:                         $returnhash{$key}=$result;
                   5361:                     } else {
1.921     raeburn  5362:                         my @responses = split(/:/,$value);
                   5363:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5364:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5365:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5366:                         }
1.1008    raeburn  5367:                     }
1.353     www      5368:                 }
                   5369:             }
                   5370:         }
                   5371:     }
                   5372:     return %returnhash;
                   5373: }
                   5374: 
1.1055    raeburn  5375: sub courselastaccess {
                   5376:     my ($cdom,$cnum,$hostidref) = @_;
                   5377:     my %returnhash;
                   5378:     if ($cdom && $cnum) {
                   5379:         my $chome = &homeserver($cnum,$cdom);
                   5380:         if ($chome ne 'no_host') {
                   5381:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5382:             &extract_lastaccess(\%returnhash,$rep);
                   5383:         }
                   5384:     } else {
                   5385:         if (!$cdom) { $cdom=''; }
                   5386:         my %libserv = &all_library();
                   5387:         foreach my $tryserver (keys(%libserv)) {
                   5388:             if (ref($hostidref) eq 'ARRAY') {
                   5389:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5390:             } 
                   5391:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5392:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5393:                 &extract_lastaccess(\%returnhash,$rep);
                   5394:             }
                   5395:         }
                   5396:     }
                   5397:     return %returnhash;
                   5398: }
                   5399: 
                   5400: sub extract_lastaccess {
                   5401:     my ($returnhash,$rep) = @_;
                   5402:     if (ref($returnhash) eq 'HASH') {
                   5403:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5404:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5405:                  $rep eq '') {
                   5406:             my @pairs=split(/\&/,$rep);
                   5407:             foreach my $item (@pairs) {
                   5408:                 my ($key,$value)=split(/\=/,$item,2);
                   5409:                 $key = &unescape($key);
                   5410:                 next if ($key =~ /^error: 2 /);
                   5411:                 $returnhash->{$key} = &thaw_unescape($value);
                   5412:             }
                   5413:         }
                   5414:     }
                   5415:     return;
                   5416: }
                   5417: 
1.658     raeburn  5418: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5419: 
                   5420: sub dcmailput {
1.685     raeburn  5421:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5422:     my $status = &Apache::lonnet::critical(
1.740     www      5423:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5424:        &escape($message),$server);
1.662     raeburn  5425:     return $status;
                   5426: }
                   5427: 
1.658     raeburn  5428: sub dcmaildump {
                   5429:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5430:     my %returnhash=();
1.846     albertel 5431: 
                   5432:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5433:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5434:                                                          &escape($enddate).':';
                   5435: 	my @esc_senders=map { &escape($_)} @$senders;
                   5436: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5437: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5438:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5439:             if (($key) && ($value)) {
                   5440:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5441:             }
                   5442:         }
                   5443:     }
                   5444:     return %returnhash;
                   5445: }
1.662     raeburn  5446: # ---------------------------------------------------------- Domain roles
                   5447: 
                   5448: sub get_domain_roles {
                   5449:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5450:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5451:         $startdate = '.';
                   5452:     }
1.1018    raeburn  5453:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5454:         $enddate = '.';
                   5455:     }
1.922     raeburn  5456:     my $rolelist;
                   5457:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5458:         $rolelist = join('&',@{$roles});
1.922     raeburn  5459:     }
1.662     raeburn  5460:     my %personnel = ();
1.841     albertel 5461: 
                   5462:     my %servers = &get_servers($dom,'library');
                   5463:     foreach my $tryserver (keys(%servers)) {
                   5464: 	%{$personnel{$tryserver}}=();
                   5465: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5466: 					    &escape($startdate).':'.
                   5467: 					    &escape($enddate).':'.
                   5468: 					    &escape($rolelist), $tryserver))) {
                   5469: 	    my ($key,$value) = split(/\=/,$line,2);
                   5470: 	    if (($key) && ($value)) {
                   5471: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5472: 	    }
                   5473: 	}
1.662     raeburn  5474:     }
                   5475:     return %personnel;
                   5476: }
1.658     raeburn  5477: 
1.1332    raeburn  5478: sub get_active_domroles {
                   5479:     my ($dom,$roles) = @_;
                   5480:     return () unless (ref($roles) eq 'ARRAY');
                   5481:     my $now = time;
                   5482:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5483:     my %domroles;
                   5484:     foreach my $server (keys(%dompersonnel)) {
                   5485:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5486:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5487:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5488:         }
                   5489:     }
                   5490:     return %domroles;
                   5491: }
                   5492: 
1.1057    www      5493: # ----------------------------------------------------------- Interval timing 
1.149     www      5494: 
1.1153    www      5495: {
                   5496: # Caches needed for speedup of navmaps
                   5497: # We don't want to cache this for very long at all (5 seconds at most)
                   5498: # 
                   5499: # The user for whom we cache
                   5500: my $cachedkey='';
                   5501: # The cached times for this user
                   5502: my %cachedtimes=();
                   5503: # When this was last done
1.1282    raeburn  5504: my $cachedtime='';
1.1153    www      5505: 
                   5506: sub load_all_first_access {
1.1308    raeburn  5507:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5508:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5509:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5510:         (!$ignorecache)) {
1.1154    raeburn  5511:         return;
                   5512:     }
                   5513:     $cachedtime=time;
                   5514:     $cachedkey=$uname.':'.$udom;
                   5515:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5516: }
                   5517: 
1.504     albertel 5518: sub get_first_access {
1.1308    raeburn  5519:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5520:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5521:     if ($argsymb) { $symb=$argsymb; }
                   5522:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5523:     if ($argmap) { $map = $argmap; }
1.926     albertel 5524:     if ($type eq 'course') {
                   5525: 	$res='course';
                   5526:     } elsif ($type eq 'map') {
1.588     albertel 5527: 	$res=&symbread($map);
                   5528:     } else {
                   5529: 	$res=$symb;
                   5530:     }
1.1308    raeburn  5531:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5532:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5533: }
                   5534: 
                   5535: sub set_first_access {
1.1162    raeburn  5536:     my ($type,$interval)=@_;
1.790     albertel 5537:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5538:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5539:     if ($type eq 'course') {
                   5540: 	$res='course';
                   5541:     } elsif ($type eq 'map') {
1.588     albertel 5542: 	$res=&symbread($map);
                   5543:     } else {
                   5544: 	$res=$symb;
                   5545:     }
1.1153    www      5546:     $cachedkey='';
1.1162    raeburn  5547:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  5548:     if ($firstaccess) {
                   5549:         &logthis("First access time already set ($firstaccess) when attempting ".
1.1393    raeburn  5550:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5551:                  "in $courseid");
1.1386    raeburn  5552:         return 'already_set';
                   5553:     } else {
1.1162    raeburn  5554:         my $start = time;
                   5555: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5556:                           $udom,$uname);
                   5557:         if ($putres eq 'ok') {
                   5558:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5559:                  $udom,$uname); 
                   5560:             &appenv(
                   5561:                      {
                   5562:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5563:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5564:                      }
                   5565:                   );
1.1365    raeburn  5566:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5567:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5568:             }
1.1386    raeburn  5569:         } elsif ($putres ne 'refused') {
                   5570:             &logthis("Result: $putres when attempting to set first access time ".
                   5571:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5572:         }
                   5573:         return $putres;
1.505     albertel 5574:     }
                   5575:     return 'already_set';
1.504     albertel 5576: }
1.1153    www      5577: }
1.1282    raeburn  5578: 
1.110     www      5579: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5580: 
                   5581: sub expirespread {
                   5582:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5583:     my $cid=$env{'request.course.id'}; 
1.110     www      5584:     if ($cid) {
                   5585:        my $now=time;
                   5586:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5587:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5588:                             $env{'course.'.$cid.'.num'}.
1.110     www      5589: 	        	    ':nohist_expirationdates:'.
                   5590:                             &escape($key).'='.$now,
1.620     albertel 5591:                             $env{'course.'.$cid.'.home'})
1.110     www      5592:     }
                   5593:     return 'ok';
1.14      www      5594: }
                   5595: 
1.109     www      5596: # ----------------------------------------------------- Devalidate Spreadsheets
                   5597: 
                   5598: sub devalidate {
1.325     www      5599:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5600:     my $cid=$env{'request.course.id'}; 
1.109     www      5601:     if ($cid) {
1.391     matthew  5602:         # delete the stored spreadsheets for
                   5603:         # - the student level sheet of this user in course's homespace
                   5604:         # - the assessment level sheet for this resource 
                   5605:         #   for this user in user's homespace
1.553     albertel 5606: 	# - current conditional state info
1.325     www      5607: 	my $key=$uname.':'.$udom.':';
1.109     www      5608:         my $status=
1.299     matthew  5609: 	    &del('nohist_calculatedsheets',
1.391     matthew  5610: 		 [$key.'studentcalc:'],
1.620     albertel 5611: 		 $env{'course.'.$cid.'.domain'},
                   5612: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5613: 		.' '.
                   5614: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5615: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5616:         unless ($status eq 'ok ok') {
                   5617:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5618:                     $uname.' at '.$udom.' for '.
1.109     www      5619: 		    $symb.': '.$status);
1.133     albertel 5620:         }
1.553     albertel 5621: 	&delenv('user.state.'.$cid);
1.109     www      5622:     }
                   5623: }
                   5624: 
1.265     albertel 5625: sub get_scalar {
                   5626:     my ($string,$end) = @_;
                   5627:     my $value;
                   5628:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5629: 	$value = $1;
                   5630:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5631: 	$value = $1;
                   5632:     }
                   5633:     return &unescape($value);
                   5634: }
                   5635: 
                   5636: sub array2str {
                   5637:   my (@array) = @_;
                   5638:   my $result=&arrayref2str(\@array);
                   5639:   $result=~s/^__ARRAY_REF__//;
                   5640:   $result=~s/__END_ARRAY_REF__$//;
                   5641:   return $result;
                   5642: }
                   5643: 
1.204     albertel 5644: sub arrayref2str {
                   5645:   my ($arrayref) = @_;
1.265     albertel 5646:   my $result='__ARRAY_REF__';
1.204     albertel 5647:   foreach my $elem (@$arrayref) {
1.265     albertel 5648:     if(ref($elem) eq 'ARRAY') {
                   5649:       $result.=&arrayref2str($elem).'&';
                   5650:     } elsif(ref($elem) eq 'HASH') {
                   5651:       $result.=&hashref2str($elem).'&';
                   5652:     } elsif(ref($elem)) {
                   5653:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5654:     } else {
                   5655:       $result.=&escape($elem).'&';
                   5656:     }
                   5657:   }
                   5658:   $result=~s/\&$//;
1.265     albertel 5659:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5660:   return $result;
                   5661: }
                   5662: 
1.168     albertel 5663: sub hash2str {
1.204     albertel 5664:   my (%hash) = @_;
                   5665:   my $result=&hashref2str(\%hash);
1.265     albertel 5666:   $result=~s/^__HASH_REF__//;
                   5667:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5668:   return $result;
                   5669: }
                   5670: 
                   5671: sub hashref2str {
                   5672:   my ($hashref)=@_;
1.265     albertel 5673:   my $result='__HASH_REF__';
1.800     albertel 5674:   foreach my $key (sort(keys(%$hashref))) {
                   5675:     if (ref($key) eq 'ARRAY') {
                   5676:       $result.=&arrayref2str($key).'=';
                   5677:     } elsif (ref($key) eq 'HASH') {
                   5678:       $result.=&hashref2str($key).'=';
                   5679:     } elsif (ref($key)) {
1.265     albertel 5680:       $result.='=';
1.800     albertel 5681:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5682:     } else {
1.1132    raeburn  5683: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5684:     }
                   5685: 
1.800     albertel 5686:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5687:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5688:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5689:       $result.=&hashref2str($hashref->{$key}).'&';
                   5690:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5691:        $result.='&';
1.800     albertel 5692:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5693:     } else {
1.800     albertel 5694:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5695:     }
                   5696:   }
1.168     albertel 5697:   $result=~s/\&$//;
1.265     albertel 5698:   $result .= '__END_HASH_REF__';
1.168     albertel 5699:   return $result;
                   5700: }
                   5701: 
                   5702: sub str2hash {
1.265     albertel 5703:     my ($string)=@_;
                   5704:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5705:     return %$hash;
                   5706: }
                   5707: 
                   5708: sub str2hashref {
1.168     albertel 5709:   my ($string) = @_;
1.265     albertel 5710: 
                   5711:   my %hash;
                   5712: 
                   5713:   if($string !~ /^__HASH_REF__/) {
                   5714:       if (! ($string eq '' || !defined($string))) {
                   5715: 	  $hash{'error'}='Not hash reference';
                   5716:       }
                   5717:       return (\%hash, $string);
                   5718:   }
                   5719: 
                   5720:   $string =~ s/^__HASH_REF__//;
                   5721: 
                   5722:   while($string !~ /^__END_HASH_REF__/) {
                   5723:       #key
                   5724:       my $key='';
                   5725:       if($string =~ /^__HASH_REF__/) {
                   5726:           ($key, $string)=&str2hashref($string);
                   5727:           if(defined($key->{'error'})) {
                   5728:               $hash{'error'}='Bad data';
                   5729:               return (\%hash, $string);
                   5730:           }
                   5731:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5732:           ($key, $string)=&str2arrayref($string);
                   5733:           if($key->[0] eq 'Array reference error') {
                   5734:               $hash{'error'}='Bad data';
                   5735:               return (\%hash, $string);
                   5736:           }
                   5737:       } else {
                   5738:           $string =~ s/^(.*?)=//;
1.267     albertel 5739: 	  $key=&unescape($1);
1.265     albertel 5740:       }
                   5741:       $string =~ s/^=//;
                   5742: 
                   5743:       #value
                   5744:       my $value='';
                   5745:       if($string =~ /^__HASH_REF__/) {
                   5746:           ($value, $string)=&str2hashref($string);
                   5747:           if(defined($value->{'error'})) {
                   5748:               $hash{'error'}='Bad data';
                   5749:               return (\%hash, $string);
                   5750:           }
                   5751:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5752:           ($value, $string)=&str2arrayref($string);
                   5753:           if($value->[0] eq 'Array reference error') {
                   5754:               $hash{'error'}='Bad data';
                   5755:               return (\%hash, $string);
                   5756:           }
                   5757:       } else {
                   5758: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5759:       }
                   5760:       $string =~ s/^&//;
                   5761: 
                   5762:       $hash{$key}=$value;
1.204     albertel 5763:   }
1.265     albertel 5764: 
                   5765:   $string =~ s/^__END_HASH_REF__//;
                   5766: 
                   5767:   return (\%hash, $string);
1.204     albertel 5768: }
                   5769: 
                   5770: sub str2array {
1.265     albertel 5771:     my ($string)=@_;
                   5772:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5773:     return @$array;
                   5774: }
                   5775: 
                   5776: sub str2arrayref {
1.204     albertel 5777:   my ($string) = @_;
1.265     albertel 5778:   my @array;
                   5779: 
                   5780:   if($string !~ /^__ARRAY_REF__/) {
                   5781:       if (! ($string eq '' || !defined($string))) {
                   5782: 	  $array[0]='Array reference error';
                   5783:       }
                   5784:       return (\@array, $string);
                   5785:   }
                   5786: 
                   5787:   $string =~ s/^__ARRAY_REF__//;
                   5788: 
                   5789:   while($string !~ /^__END_ARRAY_REF__/) {
                   5790:       my $value='';
                   5791:       if($string =~ /^__HASH_REF__/) {
                   5792:           ($value, $string)=&str2hashref($string);
                   5793:           if(defined($value->{'error'})) {
                   5794:               $array[0] ='Array reference error';
                   5795:               return (\@array, $string);
                   5796:           }
                   5797:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5798:           ($value, $string)=&str2arrayref($string);
                   5799:           if($value->[0] eq 'Array reference error') {
                   5800:               $array[0] ='Array reference error';
                   5801:               return (\@array, $string);
                   5802:           }
                   5803:       } else {
                   5804: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5805:       }
                   5806:       $string =~ s/^&//;
                   5807: 
                   5808:       push(@array, $value);
1.191     harris41 5809:   }
1.265     albertel 5810: 
                   5811:   $string =~ s/^__END_ARRAY_REF__//;
                   5812: 
                   5813:   return (\@array, $string);
1.168     albertel 5814: }
                   5815: 
1.167     albertel 5816: # -------------------------------------------------------------------Temp Store
                   5817: 
1.168     albertel 5818: sub tmpreset {
                   5819:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5820:   if (!$symb) {
                   5821:     $symb=&symbread();
1.620     albertel 5822:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5823:   }
                   5824:   $symb=escape($symb);
                   5825: 
1.620     albertel 5826:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5827:   $namespace=~s/\//\_/g;
                   5828:   $namespace=~s/\W//g;
                   5829: 
1.620     albertel 5830:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5831:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5832:   if ($domain eq 'public' && $stuname eq 'public') {
                   5833:       $stuname=$ENV{'REMOTE_ADDR'};
                   5834:   }
1.1117    foxr     5835:   my $path=LONCAPA::tempdir();
1.168     albertel 5836:   my %hash;
                   5837:   if (tie(%hash,'GDBM_File',
                   5838: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5839: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5840:     foreach my $key (keys(%hash)) {
1.180     albertel 5841:       if ($key=~ /:$symb/) {
1.168     albertel 5842: 	delete($hash{$key});
                   5843:       }
                   5844:     }
                   5845:   }
                   5846: }
                   5847: 
1.167     albertel 5848: sub tmpstore {
1.168     albertel 5849:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5850: 
                   5851:   if (!$symb) {
                   5852:     $symb=&symbread();
1.620     albertel 5853:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5854:   }
                   5855:   $symb=escape($symb);
                   5856: 
                   5857:   if (!$namespace) {
                   5858:     # I don't think we would ever want to store this for a course.
                   5859:     # it seems this will only be used if we don't have a course.
1.620     albertel 5860:     #$namespace=$env{'request.course.id'};
1.168     albertel 5861:     #if (!$namespace) {
1.620     albertel 5862:       $namespace=$env{'request.state'};
1.168     albertel 5863:     #}
                   5864:   }
                   5865:   $namespace=~s/\//\_/g;
                   5866:   $namespace=~s/\W//g;
1.620     albertel 5867:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5868:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5869:   if ($domain eq 'public' && $stuname eq 'public') {
                   5870:       $stuname=$ENV{'REMOTE_ADDR'};
                   5871:   }
1.168     albertel 5872:   my $now=time;
                   5873:   my %hash;
1.1117    foxr     5874:   my $path=LONCAPA::tempdir();
1.168     albertel 5875:   if (tie(%hash,'GDBM_File',
                   5876: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5877: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5878:     $hash{"version:$symb"}++;
                   5879:     my $version=$hash{"version:$symb"};
                   5880:     my $allkeys=''; 
                   5881:     foreach my $key (keys(%$storehash)) {
                   5882:       $allkeys.=$key.':';
1.591     albertel 5883:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5884:     }
                   5885:     $hash{"$version:$symb:timestamp"}=$now;
                   5886:     $allkeys.='timestamp';
                   5887:     $hash{"$version:keys:$symb"}=$allkeys;
                   5888:     if (untie(%hash)) {
                   5889:       return 'ok';
                   5890:     } else {
                   5891:       return "error:$!";
                   5892:     }
                   5893:   } else {
                   5894:     return "error:$!";
                   5895:   }
                   5896: }
1.167     albertel 5897: 
1.168     albertel 5898: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5899: 
1.168     albertel 5900: sub tmprestore {
                   5901:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5902: 
1.168     albertel 5903:   if (!$symb) {
                   5904:     $symb=&symbread();
1.620     albertel 5905:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5906:   }
                   5907:   $symb=escape($symb);
                   5908: 
1.620     albertel 5909:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5910: 
1.620     albertel 5911:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5912:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5913:   if ($domain eq 'public' && $stuname eq 'public') {
                   5914:       $stuname=$ENV{'REMOTE_ADDR'};
                   5915:   }
1.168     albertel 5916:   my %returnhash;
                   5917:   $namespace=~s/\//\_/g;
                   5918:   $namespace=~s/\W//g;
                   5919:   my %hash;
1.1117    foxr     5920:   my $path=LONCAPA::tempdir();
1.168     albertel 5921:   if (tie(%hash,'GDBM_File',
                   5922: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5923: 	  &GDBM_READER(),0640)) {
1.168     albertel 5924:     my $version=$hash{"version:$symb"};
                   5925:     $returnhash{'version'}=$version;
                   5926:     my $scope;
                   5927:     for ($scope=1;$scope<=$version;$scope++) {
                   5928:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5929:       my @keys=split(/:/,$vkeys);
                   5930:       my $key;
                   5931:       $returnhash{"$scope:keys"}=$vkeys;
                   5932:       foreach $key (@keys) {
1.591     albertel 5933: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5934: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5935:       }
                   5936:     }
1.168     albertel 5937:     if (!(untie(%hash))) {
                   5938:       return "error:$!";
                   5939:     }
                   5940:   } else {
                   5941:     return "error:$!";
                   5942:   }
                   5943:   return %returnhash;
1.167     albertel 5944: }
                   5945: 
1.9       www      5946: # ----------------------------------------------------------------------- Store
                   5947: 
                   5948: sub store {
1.1269    raeburn  5949:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5950:     my $home='';
                   5951: 
1.168     albertel 5952:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5953: 
1.213     www      5954:     $symb=&symbclean($symb);
1.122     albertel 5955:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5956: 
1.620     albertel 5957:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5958:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5959: 
                   5960:     &devalidate($symb,$stuname,$domain);
1.109     www      5961: 
                   5962:     $symb=escape($symb);
1.187     www      5963:     if (!$namespace) { 
1.620     albertel 5964:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5965:           return ''; 
                   5966:        } 
                   5967:     }
1.620     albertel 5968:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5969: 
                   5970:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5971:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5972: 
1.12      www      5973:     my $namevalue='';
1.800     albertel 5974:     foreach my $key (keys(%$storehash)) {
                   5975:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5976:     }
1.12      www      5977:     $namevalue=~s/\&$//;
1.187     www      5978:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5979:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5980: }
                   5981: 
1.47      www      5982: # -------------------------------------------------------------- Critical Store
                   5983: 
                   5984: sub cstore {
1.1269    raeburn  5985:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5986:     my $home='';
                   5987: 
1.168     albertel 5988:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5989: 
1.213     www      5990:     $symb=&symbclean($symb);
1.122     albertel 5991:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5992: 
1.620     albertel 5993:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5994:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5995: 
                   5996:     &devalidate($symb,$stuname,$domain);
1.109     www      5997: 
                   5998:     $symb=escape($symb);
1.187     www      5999:     if (!$namespace) { 
1.620     albertel 6000:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6001:           return ''; 
                   6002:        } 
                   6003:     }
1.620     albertel 6004:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6005: 
                   6006:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6007:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6008: 
1.47      www      6009:     my $namevalue='';
1.800     albertel 6010:     foreach my $key (keys(%$storehash)) {
                   6011:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6012:     }
1.47      www      6013:     $namevalue=~s/\&$//;
1.187     www      6014:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6015:     return critical
1.1269    raeburn  6016:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6017: }
                   6018: 
1.9       www      6019: # --------------------------------------------------------------------- Restore
                   6020: 
                   6021: sub restore {
1.124     www      6022:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6023:     my $home='';
                   6024: 
1.168     albertel 6025:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6026: 
1.122     albertel 6027:     if (!$symb) {
1.1224    raeburn  6028:         return if ($namespace eq 'courserequests');
                   6029:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6030:     } else {
1.1224    raeburn  6031:         unless ($namespace eq 'courserequests') {
                   6032:             $symb=&escape(&symbclean($symb));
                   6033:         }
1.122     albertel 6034:     }
1.188     www      6035:     if (!$namespace) { 
1.620     albertel 6036:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6037:           return ''; 
                   6038:        } 
                   6039:     }
1.620     albertel 6040:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6041:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6042:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6043:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6044: 
1.12      www      6045:     my %returnhash=();
1.800     albertel 6046:     foreach my $line (split(/\&/,$answer)) {
                   6047: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6048:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6049:     }
1.75      www      6050:     my $version;
                   6051:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6052:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6053:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6054:        }
1.75      www      6055:     }
1.13      www      6056:     return %returnhash;
1.34      www      6057: }
                   6058: 
                   6059: # ---------------------------------------------------------- Course Description
1.1118    foxr     6060: #
                   6061: #  
1.34      www      6062: 
                   6063: sub coursedescription {
1.731     albertel 6064:     my ($courseid,$args)=@_;
1.34      www      6065:     $courseid=~s/^\///;
1.49      www      6066:     $courseid=~s/\_/\//g;
1.34      www      6067:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6068:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6069:     my $normalid=$cdomain.'_'.$cnum;
                   6070:     # need to always cache even if we get errors otherwise we keep 
                   6071:     # trying and trying and trying to get the course description.
                   6072:     my %envhash=();
                   6073:     my %returnhash=();
1.731     albertel 6074:     
                   6075:     my $expiretime=600;
                   6076:     if ($env{'request.course.id'} eq $normalid) {
                   6077: 	$expiretime=120;
                   6078:     }
                   6079: 
                   6080:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6081:     if (!$args->{'freshen_cache'}
                   6082: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6083: 	foreach my $key (keys(%env)) {
                   6084: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6085: 	    my ($setting) = $1;
                   6086: 	    $returnhash{$setting} = $env{$key};
                   6087: 	}
                   6088: 	return %returnhash;
                   6089:     }
                   6090: 
1.1118    foxr     6091:     # get the data again
                   6092: 
1.731     albertel 6093:     if (!$args->{'one_time'}) {
                   6094: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6095:     }
1.811     albertel 6096: 
1.34      www      6097:     if ($chome ne 'no_host') {
1.302     albertel 6098:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6099:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6100: 	   my $username = $env{'user.name'}; # Defult username
                   6101: 	   if(defined $args->{'user'}) {
                   6102: 	       $username = $args->{'user'};
                   6103: 	   }
1.129     albertel 6104:            $returnhash{'home'}= $chome;
                   6105: 	   $returnhash{'domain'} = $cdomain;
                   6106: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6107:            if (!defined($returnhash{'type'})) {
                   6108:                $returnhash{'type'} = 'Course';
                   6109:            }
1.130     albertel 6110:            while (my ($name,$value) = each %returnhash) {
1.53      www      6111:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6112:            }
1.270     www      6113:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6114:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6115: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6116:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6117:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6118:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6119:        }
                   6120:     }
1.731     albertel 6121:     if (!$args->{'one_time'}) {
1.949     raeburn  6122: 	&appenv(\%envhash);
1.731     albertel 6123:     }
1.302     albertel 6124:     return %returnhash;
1.461     www      6125: }
                   6126: 
1.1080    raeburn  6127: sub update_released_required {
                   6128:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6129:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6130:         $cid = $env{'request.course.id'};
                   6131:         $cdom = $env{'course.'.$cid.'.domain'};
                   6132:         $cnum = $env{'course.'.$cid.'.num'};
                   6133:         $chome = $env{'course.'.$cid.'.home'};
                   6134:     }
                   6135:     if ($needsrelease) {
                   6136:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6137:         my $needsupdate;
                   6138:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6139:             $needsupdate = 1;
                   6140:         } else {
                   6141:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6142:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6143:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6144:                 $needsupdate = 1;
                   6145:             }
                   6146:         }
                   6147:         if ($needsupdate) {
                   6148:             my %needshash = (
                   6149:                              'internal.releaserequired' => $needsrelease,
                   6150:                             );
                   6151:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6152:             if ($putresult eq 'ok') {
                   6153:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6154:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6155:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6156:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6157:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6158:                 }
                   6159:             }
                   6160:         }
                   6161:     }
                   6162:     return;
                   6163: }
                   6164: 
1.461     www      6165: # -------------------------------------------------See if a user is privileged
                   6166: 
                   6167: sub privileged {
1.1219    raeburn  6168:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6169:     my $now = time;
1.1219    raeburn  6170:     my $roles;
                   6171:     if (ref($possroles) eq 'ARRAY') {
                   6172:         $roles = $possroles; 
                   6173:     } else {
                   6174:         $roles = ['dc','su'];
                   6175:     }
                   6176:     if (ref($possdomains) eq 'ARRAY') {
                   6177:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6178:         foreach my $dom (@{$possdomains}) {
                   6179:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6180:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6181:                 foreach my $role (@{$roles}) {
                   6182:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6183:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6184:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6185:                             return 1 unless (($end && $end < $now) ||
                   6186:                                              ($start && $start > $now));
                   6187:                         }
                   6188:                     }
                   6189:                 }
                   6190:             }
                   6191:         }
                   6192:     } else {
                   6193:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6194:         my $now = time;
1.1170    droeschl 6195: 
1.1275    musolffc 6196:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6197:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  6198:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 6199:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  6200:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6201:             }
1.1219    raeburn  6202:         }
                   6203:     }
                   6204:     return 0;
                   6205: }
1.1170    droeschl 6206: 
1.1219    raeburn  6207: sub privileged_by_domain {
                   6208:     my ($domains,$roles) = @_;
                   6209:     my %privileged = ();
                   6210:     my $cachetime = 60*60*24;
                   6211:     my $now = time;
                   6212:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6213:         return %privileged;
                   6214:     }
                   6215:     foreach my $dom (@{$domains}) {
                   6216:         next if (ref($privileged{$dom}) eq 'HASH');
                   6217:         my $needroles;
                   6218:         foreach my $role (@{$roles}) {
                   6219:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6220:             if (defined($cached)) {
                   6221:                 if (ref($result) eq 'HASH') {
                   6222:                     $privileged{$dom}{$role} = $result;
                   6223:                 }
                   6224:             } else {
                   6225:                 $needroles = 1;
                   6226:             }
                   6227:         }
                   6228:         if ($needroles) {
                   6229:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6230:             $privileged{$dom} = {};
                   6231:             foreach my $server (keys(%dompersonnel)) {
                   6232:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6233:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6234:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6235:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6236:                         next if ($end && $end < $now);
                   6237:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   6238:                             $dompersonnel{$server}{$item};
                   6239:                     }
                   6240:                 }
                   6241:             }
                   6242:             if (ref($privileged{$dom}) eq 'HASH') {
                   6243:                 foreach my $role (@{$roles}) {
                   6244:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6245:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6246:                     } else {
                   6247:                         my %hash = ();
                   6248:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6249:                     }
                   6250:                 }
                   6251:             }
                   6252:         }
                   6253:     }
                   6254:     return %privileged;
1.9       www      6255: }
1.1       albertel 6256: 
1.103     harris41 6257: # -------------------------------------------------------- Get user privileges
1.11      www      6258: 
                   6259: sub rolesinit {
1.1169    droeschl 6260:     my ($domain, $username) = @_;
                   6261:     my %userroles = ('user.login.time' => time);
                   6262:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6263: 
                   6264:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6265:     # also, blocking can be triggered by an activating timer
                   6266:     # it's saved in the user's %env.
                   6267:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6268:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6269:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6270:         %timerintchk, %timerintenv);
                   6271: 
1.1162    raeburn  6272:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6273:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6274:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6275:     }
1.1169    droeschl 6276: 
1.1162    raeburn  6277:     foreach my $key (keys(%timerinterval)) {
                   6278:         my ($cid,$rest) = split(/\0/,$key);
                   6279:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6280:     }
1.1169    droeschl 6281: 
1.11      www      6282:     my %allroles=();
1.1162    raeburn  6283:     my %allgroups=();
1.11      www      6284: 
1.1274    raeburn  6285:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6286:         my $role = $rolesdump{$area};
                   6287:         $area =~ s/\_\w\w$//;
                   6288: 
                   6289:         my ($trole, $tend, $tstart, $group_privs);
                   6290: 
                   6291:         if ($role =~ /^cr/) {
                   6292:         # Custom role, defined by a user 
                   6293:         # e.g., user.role.cr/msu/smith/mynewrole
                   6294:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6295:                 $trole = $1;
                   6296:                 ($tend, $tstart) = split('_', $2);
                   6297:             } else {
                   6298:                 $trole = $role;
                   6299:             }
                   6300:         } elsif ($role =~ m|^gr/|) {
                   6301:         # Role of member in a group, defined within a course/community
                   6302:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6303:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6304:             next if $tstart eq '-1';
                   6305:             ($trole, $group_privs) = split(/\//, $trole);
                   6306:             $group_privs = &unescape($group_privs);
                   6307:         } else {
                   6308:         # Just a normal role, defined in roles.tab
                   6309:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6310:         }
                   6311: 
                   6312:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6313:                  $username);
                   6314:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6315: 
                   6316:         # role expired or not available yet?
                   6317:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6318:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6319: 
                   6320:         next if $area eq '' or $trole eq '';
                   6321: 
                   6322:         my $spec = "$trole.$area";
                   6323:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6324: 
                   6325:         if ($trole =~ /^cr\//) {
                   6326:         # Custom role, defined by a user
                   6327:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6328:         } elsif ($trole eq 'gr') {
                   6329:         # Role of a member in a group, defined within a course/community
                   6330:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6331:             next;
                   6332:         } else {
                   6333:         # Normal role, defined in roles.tab
                   6334:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6335:         }
                   6336: 
                   6337:         my $cid = $tdomain.'_'.$trest;
                   6338:         unless ($firstaccchk{$cid}) {
                   6339:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6340:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6341:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6342:                         $coursetimerstarts{$cid}{$item}; 
                   6343:                 }
                   6344:             }
                   6345:             $firstaccchk{$cid} = 1;
                   6346:         }
                   6347:         unless ($timerintchk{$cid}) {
                   6348:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6349:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6350:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6351:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6352:                 }
1.12      www      6353:             }
1.1169    droeschl 6354:             $timerintchk{$cid} = 1;
1.191     harris41 6355:         }
1.11      www      6356:     }
1.1169    droeschl 6357: 
1.1341    raeburn  6358:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6359:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6360:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6361:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6362: 
1.1162    raeburn  6363:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6364: }
                   6365: 
1.567     raeburn  6366: sub set_arearole {
1.1215    raeburn  6367:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6368:     unless ($nolog) {
1.567     raeburn  6369: # log the associated role with the area
1.1215    raeburn  6370:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6371:     }
1.743     albertel 6372:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6373: }
                   6374: 
                   6375: sub custom_roleprivs {
                   6376:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6377:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6378:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6379:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6380:         my ($rdummy,$roledef)=
                   6381:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6382:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6383:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6384:             if (defined($syspriv)) {
1.1043    raeburn  6385:                 if ($trest =~ /^$match_community$/) {
                   6386:                     $syspriv =~ s/bre\&S//; 
                   6387:                 }
1.567     raeburn  6388:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6389:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6390:             }
                   6391:             if ($tdomain ne '') {
                   6392:                 if (defined($dompriv)) {
                   6393:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6394:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6395:                 }
                   6396:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6397:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6398:                         my $rolename = $1;
                   6399:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6400:                     }
1.567     raeburn  6401:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6402:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6403:                 }
                   6404:             }
                   6405:         }
                   6406:     }
                   6407: }
                   6408: 
1.1332    raeburn  6409: sub course_adhocrole_privs {
                   6410:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6411:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6412:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6413:         my (%currprivs,%storeprivs);
                   6414:         foreach my $item (split(/:/,$coursepriv)) {
                   6415:             my ($priv,$restrict) = split(/\&/,$item);
                   6416:             $currprivs{$priv} = $restrict;
                   6417:         }
                   6418:         my (%possadd,%possremove,%full);
                   6419:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6420:             my ($priv,$restrict)=split(/\&/,$item);
                   6421:             $full{$priv} = $restrict;
                   6422:         }
                   6423:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6424:              next if ($item eq '');
                   6425:              my ($rule,$rest) = split(/=/,$item);
                   6426:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6427:              foreach my $priv (split(/:/,$rest)) {
                   6428:                  if ($priv ne '') {
                   6429:                      if ($rule eq 'off') {
                   6430:                          $possremove{$priv} = 1;
                   6431:                      } else {
                   6432:                          $possadd{$priv} = 1;
                   6433:                      }
                   6434:                  }
                   6435:              }
                   6436:          }
                   6437:          foreach my $priv (sort(keys(%full))) {
                   6438:              if (exists($currprivs{$priv})) {
                   6439:                  unless (exists($possremove{$priv})) {
                   6440:                      $storeprivs{$priv} = $currprivs{$priv};
                   6441:                  }
                   6442:              } elsif (exists($possadd{$priv})) {
                   6443:                  $storeprivs{$priv} = $full{$priv};
                   6444:              }
                   6445:          }
                   6446:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6447:      }
                   6448:      return $coursepriv;
                   6449: }
                   6450: 
1.678     raeburn  6451: sub group_roleprivs {
                   6452:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6453:     my $access = 1;
                   6454:     my $now = time;
                   6455:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6456:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6457:     if ($access) {
1.811     albertel 6458:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6459:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6460:     }
                   6461: }
1.567     raeburn  6462: 
                   6463: sub standard_roleprivs {
                   6464:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6465:     if (defined($pr{$trole.':s'})) {
                   6466:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6467:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6468:     }
                   6469:     if ($tdomain ne '') {
                   6470:         if (defined($pr{$trole.':d'})) {
                   6471:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6472:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6473:         }
                   6474:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6475:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6476:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6477:         }
                   6478:     }
                   6479: }
                   6480: 
                   6481: sub set_userprivs {
1.1064    raeburn  6482:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6483:     my $author=0;
                   6484:     my $adv=0;
1.1341    raeburn  6485:     my $rar=0;
1.678     raeburn  6486:     my %grouproles = ();
                   6487:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6488:         my @groupkeys; 
1.1000    raeburn  6489:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6490:             push(@groupkeys,$role);
                   6491:         }
                   6492:         if (ref($groups_roles) eq 'HASH') {
                   6493:             foreach my $key (keys(%{$groups_roles})) {
                   6494:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6495:                     push(@groupkeys,$key);
                   6496:                 }
                   6497:             }
                   6498:         }
                   6499:         if (@groupkeys > 0) {
                   6500:             foreach my $role (@groupkeys) {
                   6501:                 my ($trole,$area,$sec,$extendedarea);
                   6502:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6503:                     $trole = $1;
                   6504:                     $area = $2;
                   6505:                     $sec = $3;
                   6506:                     $extendedarea = $area.$sec;
                   6507:                     if (exists($$allgroups{$area})) {
                   6508:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6509:                             my $spec = $trole.'.'.$extendedarea;
                   6510:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6511:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6512:                         }
1.678     raeburn  6513:                     }
                   6514:                 }
                   6515:             }
                   6516:         }
                   6517:     }
1.800     albertel 6518:     foreach my $group (keys(%grouproles)) {
                   6519:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6520:     }
1.800     albertel 6521:     foreach my $role (keys(%{$allroles})) {
                   6522:         my %thesepriv;
1.941     raeburn  6523:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6524:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6525:             if ($item ne '') {
                   6526:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6527:                 if ($restrictions eq '') {
                   6528:                     $thesepriv{$privilege}='F';
                   6529:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6530:                     $thesepriv{$privilege}.=$restrictions;
                   6531:                 }
                   6532:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6533:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6534:             }
                   6535:         }
                   6536:         my $thesestr='';
1.1104    raeburn  6537:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6538: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6539: 	}
                   6540:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6541:     }
1.1341    raeburn  6542:     return ($author,$adv,$rar);
1.567     raeburn  6543: }
                   6544: 
1.994     raeburn  6545: sub role_status {
1.1104    raeburn  6546:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6547:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6548:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6549:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6550:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6551:             $$where = '/'.$two;
1.994     raeburn  6552:             $$trolecode=$$role.'.'.$$where;
                   6553:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6554:             $$tstatus='is';
1.1104    raeburn  6555:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6556:                 $$tstatus='future';
1.1034    raeburn  6557:                 if ($$tstart<$now) {
                   6558:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6559:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6560:                             my (%allroles,%allgroups,$group_privs,
                   6561:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6562:                             my %userroles = (
                   6563:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6564:                             );
1.1064    raeburn  6565:                             @rolecodes = ('cm'); 
1.1002    raeburn  6566:                             my $spec=$$role.'.'.$$where;
                   6567:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6568:                             if ($$role =~ /^cr\//) {
                   6569:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6570:                                 push(@rolecodes,'cr');
1.1002    raeburn  6571:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6572:                                 push(@rolecodes,$$role);
1.1002    raeburn  6573:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6574:                                                     $env{'user.name'});
1.1064    raeburn  6575:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6576:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6577:                                 $group_privs = &unescape($group_privs);
                   6578:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6579:                                 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  6580:                                 &get_groups_roles($tdomain,$trest,
                   6581:                                                   \%course_roles,\@rolecodes,
                   6582:                                                   \%groups_roles);
1.1002    raeburn  6583:                             } else {
1.1064    raeburn  6584:                                 push(@rolecodes,$$role);
1.1002    raeburn  6585:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6586:                             }
1.1341    raeburn  6587:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6588:                                                                    \%groups_roles);
1.1064    raeburn  6589:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6590:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6591:                         }
                   6592:                     }
1.1034    raeburn  6593:                     $$tstatus = 'is';
1.1002    raeburn  6594:                 }
1.994     raeburn  6595:             }
                   6596:             if ($$tend) {
1.1104    raeburn  6597:                 if ($$tend<$update) {
1.994     raeburn  6598:                     $$tstatus='expired';
                   6599:                 } elsif ($$tend<$now) {
                   6600:                     $$tstatus='will_not';
                   6601:                 }
                   6602:             }
                   6603:         }
                   6604:     }
                   6605: }
                   6606: 
1.1104    raeburn  6607: sub get_groups_roles {
                   6608:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6609:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6610:                   (ref($rolecodes) eq 'ARRAY') && 
                   6611:                   (ref($groups_roles) eq 'HASH')); 
                   6612:     if (keys(%{$cdom_courseroles}) > 0) {
                   6613:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6614:         if ($cdom ne '' && $cnum ne '') {
                   6615:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6616:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6617:                     my $crsrole = $1;
                   6618:                     my $crssec = $2;
                   6619:                     if ($crsrole =~ /^cr/) {
                   6620:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6621:                             push(@{$rolecodes},'cr');
                   6622:                         }
                   6623:                     } else {
                   6624:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6625:                             push(@{$rolecodes},$crsrole);
                   6626:                         }
                   6627:                     }
                   6628:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6629:                     if ($crssec ne '') {
                   6630:                         $rolekey .= "/$crssec";
                   6631:                     }
                   6632:                     $rolekey .= './';
                   6633:                     $groups_roles->{$rolekey} = $rolecodes;
                   6634:                 }
                   6635:             }
                   6636:         }
                   6637:     }
                   6638:     return;
                   6639: }
                   6640: 
                   6641: sub delete_env_groupprivs {
                   6642:     my ($where,$courseroles,$possroles) = @_;
                   6643:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6644:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6645:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6646:         %{$courseroles->{$udom}} =
                   6647:             &get_my_roles('','','userroles',['active'],
                   6648:                           $possroles,[$udom],1);
                   6649:     }
                   6650:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6651:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6652:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6653:             my $area = '/'.$cdom.'/'.$cnum;
                   6654:             my $privkey = "user.priv.$crsrole.$area";
                   6655:             if ($crssec ne '') {
                   6656:                 $privkey .= '/'.$crssec;
                   6657:             }
                   6658:             $privkey .= ".$area/$group";
                   6659:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6660:         }
                   6661:     }
                   6662:     return;
                   6663: }
                   6664: 
1.994     raeburn  6665: sub check_adhoc_privs {
1.1329    raeburn  6666:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6667:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6668:     if ($sec) {
                   6669:         $cckey .= '/'.$sec;
                   6670:     } 
1.1185    raeburn  6671:     my $setprivs;
1.994     raeburn  6672:     if ($env{$cckey}) {
                   6673:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6674:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6675:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6676:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6677:             $setprivs = 1;
1.994     raeburn  6678:         }
                   6679:     } else {
1.1330    raeburn  6680:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6681:         $setprivs = 1;
1.994     raeburn  6682:     }
1.1185    raeburn  6683:     return $setprivs;
1.994     raeburn  6684: }
                   6685: 
                   6686: sub set_adhoc_privileges {
1.1326    raeburn  6687: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6688:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6689:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6690:     if ($sec ne '') {
                   6691:         $area .= '/'.$sec;
                   6692:     }
1.994     raeburn  6693:     my $spec = $role.'.'.$area;
                   6694:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6695:                                   $env{'user.name'},1);
1.1326    raeburn  6696:     my %rolehash = ();
1.1332    raeburn  6697:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6698:         my $rolename = $1;
1.1326    raeburn  6699:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6700:         my %domdef = &get_domain_defaults($dcdom);
                   6701:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6702:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6703:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6704:             }
                   6705:         }
1.1326    raeburn  6706:     } else {
                   6707:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6708:     }
1.1341    raeburn  6709:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6710:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  6711:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402  ! raeburn  6712:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
        !          6713:             ($caller eq 'tiny')) {
1.1088    raeburn  6714:         &appenv( {'request.role'        => $spec,
                   6715:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6716:                   'request.course.sec'  => $sec,
1.1088    raeburn  6717:                  }
                   6718:                );
                   6719:         my $tadv=0;
                   6720:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6721:         &appenv({'request.role.adv'    => $tadv});
                   6722:     }
1.994     raeburn  6723: }
                   6724: 
1.12      www      6725: # --------------------------------------------------------------- get interface
                   6726: 
                   6727: sub get {
1.131     albertel 6728:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6729:    my $items='';
1.800     albertel 6730:    foreach my $item (@$storearr) {
                   6731:        $items.=&escape($item).'&';
1.191     harris41 6732:    }
1.12      www      6733:    $items=~s/\&$//;
1.620     albertel 6734:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6735:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6736:    my $uhome=&homeserver($uname,$udomain);
                   6737: 
1.133     albertel 6738:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6739:    my @pairs=split(/\&/,$rep);
1.273     albertel 6740:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6741:      return @pairs;
                   6742:    }
1.15      www      6743:    my %returnhash=();
1.42      www      6744:    my $i=0;
1.800     albertel 6745:    foreach my $item (@$storearr) {
                   6746:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6747:       $i++;
1.191     harris41 6748:    }
1.15      www      6749:    return %returnhash;
1.27      www      6750: }
                   6751: 
                   6752: # --------------------------------------------------------------- del interface
                   6753: 
                   6754: sub del {
1.133     albertel 6755:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6756:    my $items='';
1.800     albertel 6757:    foreach my $item (@$storearr) {
                   6758:        $items.=&escape($item).'&';
1.191     harris41 6759:    }
1.984     neumanie 6760: 
1.27      www      6761:    $items=~s/\&$//;
1.620     albertel 6762:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6763:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6764:    my $uhome=&homeserver($uname,$udomain);
                   6765:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6766: }
                   6767: 
                   6768: # -------------------------------------------------------------- dump interface
                   6769: 
1.1180    droeschl 6770: sub unserialize {
                   6771:     my ($rep, $escapedkeys) = @_;
                   6772: 
                   6773:     return {} if $rep =~ /^error/;
                   6774: 
                   6775:     my %returnhash=();
1.1252    raeburn  6776: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6777: 	    my ($key, $value) = split(/=/, $item, 2);
                   6778: 	    $key = unescape($key) unless $escapedkeys;
                   6779: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  6780: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 6781: 	}
                   6782:     #return %returnhash;
                   6783:     return \%returnhash;
                   6784: }        
                   6785: 
                   6786: # see Lond::dump_with_regexp
                   6787: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6788: sub dump {
1.1180    droeschl 6789:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6790:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6791:     if (!$uname) { $uname=$env{'user.name'}; }
                   6792:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6793: 
1.1266    raeburn  6794:     if ($regexp) {
                   6795:         $regexp=&escape($regexp);
                   6796:     } else {
                   6797:         $regexp='.';
                   6798:     }
1.1180    droeschl 6799:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   6800:         # user is hosted on this machine
1.1266    raeburn  6801:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  6802:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 6803:         return %{unserialize($reply, $escapedkeys)};
                   6804:     }
1.1166    raeburn  6805:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6806:     my @pairs=split(/\&/,$rep);
                   6807:     my %returnhash=();
1.1098    foxr     6808:     if (!($rep =~ /^error/ )) {
                   6809: 	foreach my $item (@pairs) {
                   6810: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 6811:         $key = unescape($key) unless $escapedkeys;
                   6812:         #$key = &unescape($key);
1.1098    foxr     6813: 	    next if ($key =~ /^error: 2 /);
                   6814: 	    $returnhash{$key}=&thaw_unescape($value);
                   6815: 	}
1.755     albertel 6816:     }
                   6817:     return %returnhash;
1.407     www      6818: }
                   6819: 
1.1098    foxr     6820: 
1.717     albertel 6821: # --------------------------------------------------------- dumpstore interface
                   6822: 
                   6823: sub dumpstore {
                   6824:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 6825:    # same as dump but keys must be escaped. They may contain colon separated
                   6826:    # lists of values that may themself contain colons (e.g. symbs).
                   6827:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6828: }
                   6829: 
1.407     www      6830: # -------------------------------------------------------------- keys interface
                   6831: 
                   6832: sub getkeys {
                   6833:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6834:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6835:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6836:    my $uhome=&homeserver($uname,$udomain);
                   6837:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6838:    my @keyarray=();
1.800     albertel 6839:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6840:       next if ($key =~ /^error: 2 /);
1.800     albertel 6841:       push(@keyarray,&unescape($key));
1.407     www      6842:    }
                   6843:    return @keyarray;
1.318     matthew  6844: }
                   6845: 
1.319     matthew  6846: # --------------------------------------------------------------- currentdump
                   6847: sub currentdump {
1.328     matthew  6848:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6849:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6850:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6851:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6852:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 6853:    my $rep;
                   6854: 
                   6855:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6856:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6857:                    $courseid)));
                   6858:    } else {
                   6859:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6860:    }
                   6861: 
1.318     matthew  6862:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6863:    #
1.318     matthew  6864:    my %returnhash=();
1.319     matthew  6865:    #
1.1343    raeburn  6866:    if ($rep eq 'unknown_cmd') {
1.319     matthew  6867:        # an old lond will not know currentdump
                   6868:        # Do a dump and make it look like a currentdump
1.822     albertel 6869:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6870:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6871:        my %hash = @tmp;
                   6872:        @tmp=();
1.424     matthew  6873:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6874:    } else {
                   6875:        my @pairs=split(/\&/,$rep);
1.800     albertel 6876:        foreach my $pair (@pairs) {
                   6877:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6878:            my ($symb,$param) = split(/:/,$key);
                   6879:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6880:                                                         &thaw_unescape($value);
1.319     matthew  6881:        }
1.191     harris41 6882:    }
1.12      www      6883:    return %returnhash;
1.424     matthew  6884: }
                   6885: 
                   6886: sub convert_dump_to_currentdump{
                   6887:     my %hash = %{shift()};
                   6888:     my %returnhash;
                   6889:     # Code ripped from lond, essentially.  The only difference
                   6890:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6891:     # we might run in to problems with parameter names =~ /^v\./
                   6892:     while (my ($key,$value) = each(%hash)) {
                   6893:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6894: 	$symb  = &unescape($symb);
                   6895: 	$param = &unescape($param);
1.424     matthew  6896:         next if ($v eq 'version' || $symb eq 'keys');
                   6897:         next if (exists($returnhash{$symb}) &&
                   6898:                  exists($returnhash{$symb}->{$param}) &&
                   6899:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6900:         $returnhash{$symb}->{$param}=$value;
                   6901:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6902:     }
                   6903:     #
                   6904:     # Remove all of the keys in the hashes which keep track of
                   6905:     # the version of the parameter.
                   6906:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6907:         # use a foreach because we are going to delete from the hash.
                   6908:         foreach my $key (keys(%$param_hash)) {
                   6909:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6910:         }
                   6911:     }
                   6912:     return \%returnhash;
1.12      www      6913: }
                   6914: 
1.627     albertel 6915: # ------------------------------------------------------ critical inc interface
                   6916: 
                   6917: sub cinc {
                   6918:     return &inc(@_,'critical');
                   6919: }
                   6920: 
1.449     matthew  6921: # --------------------------------------------------------------- inc interface
                   6922: 
                   6923: sub inc {
1.627     albertel 6924:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6925:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6926:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6927:     my $uhome=&homeserver($uname,$udomain);
                   6928:     my $items='';
                   6929:     if (! ref($store)) {
                   6930:         # got a single value, so use that instead
                   6931:         $items = &escape($store).'=&';
                   6932:     } elsif (ref($store) eq 'SCALAR') {
                   6933:         $items = &escape($$store).'=&';        
                   6934:     } elsif (ref($store) eq 'ARRAY') {
                   6935:         $items = join('=&',map {&escape($_);} @{$store});
                   6936:     } elsif (ref($store) eq 'HASH') {
                   6937:         while (my($key,$value) = each(%{$store})) {
                   6938:             $items.= &escape($key).'='.&escape($value).'&';
                   6939:         }
                   6940:     }
                   6941:     $items=~s/\&$//;
1.627     albertel 6942:     if ($critical) {
                   6943: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6944:     } else {
                   6945: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6946:     }
1.449     matthew  6947: }
                   6948: 
1.12      www      6949: # --------------------------------------------------------------- put interface
                   6950: 
                   6951: sub put {
1.134     albertel 6952:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6953:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6954:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6955:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6956:    my $items='';
1.800     albertel 6957:    foreach my $item (keys(%$storehash)) {
                   6958:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6959:    }
1.12      www      6960:    $items=~s/\&$//;
1.134     albertel 6961:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6962: }
                   6963: 
1.631     albertel 6964: # ------------------------------------------------------------ newput interface
                   6965: 
                   6966: sub newput {
                   6967:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6968:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6969:    if (!$uname) { $uname=$env{'user.name'}; }
                   6970:    my $uhome=&homeserver($uname,$udomain);
                   6971:    my $items='';
                   6972:    foreach my $key (keys(%$storehash)) {
                   6973:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6974:    }
                   6975:    $items=~s/\&$//;
                   6976:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6977: }
                   6978: 
                   6979: # ---------------------------------------------------------  putstore interface
                   6980: 
1.524     raeburn  6981: sub putstore {
1.1269    raeburn  6982:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6983:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6984:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6985:    my $uhome=&homeserver($uname,$udomain);
                   6986:    my $items='';
1.715     albertel 6987:    foreach my $key (keys(%$storehash)) {
                   6988:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6989:    }
1.715     albertel 6990:    $items=~s/\&$//;
1.716     albertel 6991:    my $esc_symb=&escape($symb);
                   6992:    my $esc_v=&escape($version);
1.715     albertel 6993:    my $reply =
1.716     albertel 6994:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6995: 	      $uhome);
1.1269    raeburn  6996:    if (($tolog) && ($reply eq 'ok')) {
                   6997:        my $namevalue='';
                   6998:        foreach my $key (keys(%{$storehash})) {
                   6999:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7000:        }
                   7001:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   7002:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7003:                      '&version='.$esc_v.
                   7004:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7005:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7006:    }
1.715     albertel 7007:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7008:        # gfall back to way things use to be done
1.715     albertel 7009:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7010: 			    $uname);
1.524     raeburn  7011:    }
1.715     albertel 7012:    return $reply;
                   7013: }
                   7014: 
                   7015: sub old_putstore {
1.716     albertel 7016:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7017:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7018:     if (!$uname) { $uname=$env{'user.name'}; }
                   7019:     my $uhome=&homeserver($uname,$udomain);
                   7020:     my %newstorehash;
1.800     albertel 7021:     foreach my $item (keys(%$storehash)) {
                   7022: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7023: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7024:     }
                   7025:     my $items='';
                   7026:     my %allitems = ();
1.800     albertel 7027:     foreach my $item (keys(%newstorehash)) {
                   7028: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7029: 	    my $key = $1.':keys:'.$2;
                   7030: 	    $allitems{$key} .= $3.':';
                   7031: 	}
1.800     albertel 7032: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7033:     }
1.800     albertel 7034:     foreach my $item (keys(%allitems)) {
                   7035: 	$allitems{$item} =~ s/\:$//;
                   7036: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7037:     }
                   7038:     $items=~s/\&$//;
                   7039:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7040: }
                   7041: 
1.47      www      7042: # ------------------------------------------------------ critical put interface
                   7043: 
                   7044: sub cput {
1.134     albertel 7045:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7046:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7047:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7048:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7049:    my $items='';
1.800     albertel 7050:    foreach my $item (keys(%$storehash)) {
                   7051:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7052:    }
1.47      www      7053:    $items=~s/\&$//;
1.134     albertel 7054:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7055: }
                   7056: 
                   7057: # -------------------------------------------------------------- eget interface
                   7058: 
                   7059: sub eget {
1.133     albertel 7060:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7061:    my $items='';
1.800     albertel 7062:    foreach my $item (@$storearr) {
                   7063:        $items.=&escape($item).'&';
1.191     harris41 7064:    }
1.12      www      7065:    $items=~s/\&$//;
1.620     albertel 7066:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7067:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7068:    my $uhome=&homeserver($uname,$udomain);
                   7069:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7070:    my @pairs=split(/\&/,$rep);
                   7071:    my %returnhash=();
1.42      www      7072:    my $i=0;
1.800     albertel 7073:    foreach my $item (@$storearr) {
                   7074:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7075:       $i++;
1.191     harris41 7076:    }
1.12      www      7077:    return %returnhash;
                   7078: }
                   7079: 
1.667     albertel 7080: # ------------------------------------------------------------ tmpput interface
                   7081: sub tmpput {
1.802     raeburn  7082:     my ($storehash,$server,$context)=@_;
1.667     albertel 7083:     my $items='';
1.800     albertel 7084:     foreach my $item (keys(%$storehash)) {
                   7085: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7086:     }
                   7087:     $items=~s/\&$//;
1.802     raeburn  7088:     if (defined($context)) {
                   7089:         $items .= ':'.&escape($context);
                   7090:     }
1.667     albertel 7091:     return &reply("tmpput:$items",$server);
                   7092: }
                   7093: 
                   7094: # ------------------------------------------------------------ tmpget interface
                   7095: sub tmpget {
1.688     albertel 7096:     my ($token,$server)=@_;
                   7097:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7098:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7099:     my %returnhash;
1.1328    raeburn  7100:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7101:         return %returnhash;
                   7102:     }
1.667     albertel 7103:     foreach my $item (split(/\&/,$rep)) {
                   7104: 	my ($key,$value)=split(/=/,$item);
                   7105: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7106:     }
                   7107:     return %returnhash;
                   7108: }
                   7109: 
1.1113    raeburn  7110: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7111: sub tmpdel {
                   7112:     my ($token,$server)=@_;
                   7113:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7114:     return &reply("tmpdel:$token",$server);
                   7115: }
                   7116: 
1.1198    raeburn  7117: # ------------------------------------------------------------ get_timebased_id 
                   7118: 
                   7119: sub get_timebased_id {
                   7120:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7121:         $maxtries) = @_;
                   7122:     my ($newid,$error,$dellock);
                   7123:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   7124:         return ('','ok','invalid call to get suffix');
                   7125:     }
                   7126: 
                   7127: # set defaults for any optional args for which values were not supplied
                   7128:     if ($who eq '') {
                   7129:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7130:     }
                   7131:     if (!$locktries) {
                   7132:         $locktries = 3;
                   7133:     }
                   7134:     if (!$maxtries) {
                   7135:         $maxtries = 10;
                   7136:     }
                   7137:     
                   7138:     if (($cdom eq '') || ($cnum eq '')) {
                   7139:         if ($env{'request.course.id'}) {
                   7140:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7141:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7142:         }
                   7143:         if (($cdom eq '') || ($cnum eq '')) {
                   7144:             return ('','ok','call to get suffix not in course context');
                   7145:         }
                   7146:     }
                   7147: 
                   7148: # construct locking item
                   7149:     my $lockhash = {
                   7150:                       $prefix."\0".'locked_'.$keyid => $who,
                   7151:                    };
                   7152:     my $tries = 0;
                   7153: 
                   7154: # attempt to get lock on nohist_$namespace file
                   7155:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7156:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7157:         $tries ++;
                   7158:         sleep 1;
                   7159:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7160:     }
                   7161: 
                   7162: # attempt to get unique identifier, based on current timestamp
                   7163:     if ($gotlock eq 'ok') {
                   7164:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7165:         my $id = time;
                   7166:         $newid = $id;
1.1268    raeburn  7167:         if ($idtype eq 'addcode') {
                   7168:             $newid .= &sixnum_code();
                   7169:         }
1.1198    raeburn  7170:         my $idtries = 0;
                   7171:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7172:             if ($idtype eq 'concat') {
                   7173:                 $newid = $id.$idtries;
1.1268    raeburn  7174:             } elsif ($idtype eq 'addcode') {
                   7175:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  7176:             } else {
                   7177:                 $newid ++;
                   7178:             }
                   7179:             $idtries ++;
                   7180:         }
                   7181:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7182:             my %new_item =  (
                   7183:                               $prefix."\0".$newid => $who,
                   7184:                             );
                   7185:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7186:                                                  $cdom,$cnum);
                   7187:             if ($putresult ne 'ok') {
                   7188:                 undef($newid);
                   7189:                 $error = 'error saving new item: '.$putresult;
                   7190:             }
                   7191:         } else {
1.1268    raeburn  7192:              undef($newid);
1.1198    raeburn  7193:              $error = ('error: no unique suffix available for the new item ');
                   7194:         }
                   7195: #  remove lock
                   7196:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7197:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7198:     } else {
                   7199:         $error = "error: could not obtain lockfile\n";
                   7200:         $dellock = 'ok';
1.1276    raeburn  7201:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7202:             $dellock = 'nolock';
                   7203:         }
1.1198    raeburn  7204:     }
                   7205:     return ($newid,$dellock,$error);
                   7206: }
                   7207: 
1.1268    raeburn  7208: sub sixnum_code {
                   7209:     my $code;
                   7210:     for (0..6) {
                   7211:         $code .= int( rand(9) );
                   7212:     }
                   7213:     return $code;
                   7214: }
                   7215: 
1.765     albertel 7216: # -------------------------------------------------- portfolio access checking
                   7217: 
                   7218: sub portfolio_access {
1.1270    raeburn  7219:     my ($requrl,$clientip) = @_;
1.765     albertel 7220:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  7221:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7222:     if ($result) {
                   7223:         my %setters;
                   7224:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7225:             my ($startblock,$endblock) =
                   7226:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7227:             if ($startblock && $endblock) {
                   7228:                 return 'B';
                   7229:             }
                   7230:         } else {
                   7231:             my ($startblock,$endblock) =
                   7232:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7233:             if ($startblock && $endblock) {
                   7234:                 return 'B';
                   7235:             }
                   7236:         }
                   7237:     }
1.765     albertel 7238:     if ($result eq 'ok') {
1.766     albertel 7239:        return 'F';
1.765     albertel 7240:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7241:        return 'A';
1.765     albertel 7242:     }
1.766     albertel 7243:     return '';
1.765     albertel 7244: }
                   7245: 
                   7246: sub get_portfolio_access {
1.1270    raeburn  7247:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7248: 
                   7249:     if (!ref($access_hash)) {
                   7250: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7251: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7252: 						   $file_name);
                   7253: 	$access_hash = $access_controls{$file_name};
                   7254:     }
                   7255: 
1.1270    raeburn  7256:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7257:     my $now = time;
                   7258:     if (ref($access_hash) eq 'HASH') {
                   7259:         foreach my $key (keys(%{$access_hash})) {
                   7260:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7261:             if ($start > $now) {
                   7262:                 next;
                   7263:             }
                   7264:             if ($end && $end<$now) {
                   7265:                 next;
                   7266:             }
                   7267:             if ($scope eq 'public') {
                   7268:                 $public = $key;
                   7269:                 last;
                   7270:             } elsif ($scope eq 'guest') {
                   7271:                 $guest = $key;
                   7272:             } elsif ($scope eq 'domains') {
                   7273:                 push(@domains,$key);
                   7274:             } elsif ($scope eq 'users') {
                   7275:                 push(@users,$key);
                   7276:             } elsif ($scope eq 'course') {
                   7277:                 push(@courses,$key);
                   7278:             } elsif ($scope eq 'group') {
                   7279:                 push(@groups,$key);
1.1270    raeburn  7280:             } elsif ($scope eq 'ip') {
                   7281:                 push(@ips,$key);
1.765     albertel 7282:             }
                   7283:         }
                   7284:         if ($public) {
                   7285:             return 'ok';
1.1270    raeburn  7286:         } elsif (@ips > 0) {
                   7287:             my $allowed;
                   7288:             foreach my $ipkey (@ips) {
                   7289:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7290:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7291:                         $allowed = 1;
                   7292:                         last; 
                   7293:                     }
                   7294:                 }
                   7295:             }
                   7296:             if ($allowed) {
                   7297:                 return 'ok';
                   7298:             }
1.765     albertel 7299:         }
                   7300:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7301:             if ($guest) {
                   7302:                 return $guest;
                   7303:             }
                   7304:         } else {
                   7305:             if (@domains > 0) {
                   7306:                 foreach my $domkey (@domains) {
                   7307:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7308:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7309:                             return 'ok';
                   7310:                         }
                   7311:                     }
                   7312:                 }
                   7313:             }
                   7314:             if (@users > 0) {
                   7315:                 foreach my $userkey (@users) {
1.865     raeburn  7316:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7317:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7318:                             if (ref($item) eq 'HASH') {
                   7319:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7320:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7321:                                     return 'ok';
                   7322:                                 }
                   7323:                             }
                   7324:                         }
                   7325:                     } 
1.765     albertel 7326:                 }
                   7327:             }
                   7328:             my %roleshash;
                   7329:             my @courses_and_groups = @courses;
                   7330:             push(@courses_and_groups,@groups); 
                   7331:             if (@courses_and_groups > 0) {
                   7332:                 my (%allgroups,%allroles); 
                   7333:                 my ($start,$end,$role,$sec,$group);
                   7334:                 foreach my $envkey (%env) {
1.1060    raeburn  7335:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7336:                         my $cid = $2.'_'.$3; 
                   7337:                         if ($1 eq 'gr') {
                   7338:                             $group = $4;
                   7339:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7340:                         } else {
                   7341:                             if ($4 eq '') {
                   7342:                                 $sec = 'none';
                   7343:                             } else {
                   7344:                                 $sec = $4;
                   7345:                             }
                   7346:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7347:                         }
1.811     albertel 7348:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7349:                         my $cid = $2.'_'.$3;
                   7350:                         if ($4 eq '') {
                   7351:                             $sec = 'none';
                   7352:                         } else {
                   7353:                             $sec = $4;
                   7354:                         }
                   7355:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7356:                     }
                   7357:                 }
                   7358:                 if (keys(%allroles) == 0) {
                   7359:                     return;
                   7360:                 }
                   7361:                 foreach my $key (@courses_and_groups) {
                   7362:                     my %content = %{$$access_hash{$key}};
                   7363:                     my $cnum = $content{'number'};
                   7364:                     my $cdom = $content{'domain'};
                   7365:                     my $cid = $cdom.'_'.$cnum;
                   7366:                     if (!exists($allroles{$cid})) {
                   7367:                         next;
                   7368:                     }    
                   7369:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7370:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7371:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7372:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7373:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7374:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7375:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7376:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7377:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7378:                                         if (grep/^all$/,@sections) {
                   7379:                                             return 'ok';
                   7380:                                         } else {
                   7381:                                             if (grep/^$sec$/,@sections) {
                   7382:                                                 return 'ok';
                   7383:                                             }
                   7384:                                         }
                   7385:                                     }
                   7386:                                 }
                   7387:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7388:                                     if (grep/^none$/,@groups) {
                   7389:                                         return 'ok';
                   7390:                                     }
                   7391:                                 } else {
                   7392:                                     if (grep/^all$/,@groups) {
                   7393:                                         return 'ok';
                   7394:                                     } 
                   7395:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7396:                                         if (grep/^$group$/,@groups) {
                   7397:                                             return 'ok';
                   7398:                                         }
                   7399:                                     }
                   7400:                                 } 
                   7401:                             }
                   7402:                         }
                   7403:                     }
                   7404:                 }
                   7405:             }
                   7406:             if ($guest) {
                   7407:                 return $guest;
                   7408:             }
                   7409:         }
                   7410:     }
                   7411:     return;
                   7412: }
                   7413: 
                   7414: sub course_group_datechecker {
                   7415:     my ($dates,$now,$status) = @_;
                   7416:     my ($start,$end) = split(/\./,$dates);
                   7417:     if (!$start && !$end) {
                   7418:         return 'ok';
                   7419:     }
                   7420:     if (grep/^active$/,@{$status}) {
                   7421:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7422:             return 'ok';
                   7423:         }
                   7424:     }
                   7425:     if (grep/^previous$/,@{$status}) {
                   7426:         if ($end > $now ) {
                   7427:             return 'ok';
                   7428:         }
                   7429:     }
                   7430:     if (grep/^future$/,@{$status}) {
                   7431:         if ($start > $now) {
                   7432:             return 'ok';
                   7433:         }
                   7434:     }
                   7435:     return; 
                   7436: }
                   7437: 
                   7438: sub parse_portfolio_url {
                   7439:     my ($url) = @_;
                   7440: 
                   7441:     my ($type,$udom,$unum,$group,$file_name);
                   7442:     
1.823     albertel 7443:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7444: 	$type = 1;
                   7445:         $udom = $1;
                   7446:         $unum = $2;
                   7447:         $file_name = $3;
1.823     albertel 7448:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7449: 	$type = 2;
                   7450:         $udom = $1;
                   7451:         $unum = $2;
                   7452:         $group = $3;
                   7453:         $file_name = $3.'/'.$4;
                   7454:     }
                   7455:     if (wantarray) {
                   7456: 	return ($type,$udom,$unum,$file_name,$group);
                   7457:     }
                   7458:     return $type;
                   7459: }
                   7460: 
                   7461: sub is_portfolio_url {
                   7462:     my ($url) = @_;
                   7463:     return scalar(&parse_portfolio_url($url));
                   7464: }
                   7465: 
1.798     raeburn  7466: sub is_portfolio_file {
                   7467:     my ($file) = @_;
1.820     raeburn  7468:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7469:         return 1;
                   7470:     }
                   7471:     return;
                   7472: }
                   7473: 
1.976     raeburn  7474: sub usertools_access {
1.1084    raeburn  7475:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7476:     my ($access,%tools);
                   7477:     if ($context eq '') {
                   7478:         $context = 'tools';
                   7479:     }
                   7480:     if ($context eq 'requestcourses') {
                   7481:         %tools = (
                   7482:                       official   => 1,
                   7483:                       unofficial => 1,
1.1006    raeburn  7484:                       community  => 1,
1.1246    raeburn  7485:                       textbook   => 1,
1.1305    raeburn  7486:                       placement  => 1,
1.1368    raeburn  7487:                       lti        => 1,
1.985     raeburn  7488:                  );
1.1183    raeburn  7489:     } elsif ($context eq 'requestauthor') {
                   7490:         %tools = (
                   7491:                       requestauthor => 1,
                   7492:                  );
1.985     raeburn  7493:     } else {
                   7494:         %tools = (
                   7495:                       aboutme   => 1,
                   7496:                       blog      => 1,
1.1177    raeburn  7497:                       webdav    => 1,
1.985     raeburn  7498:                       portfolio => 1,
                   7499:                  );
                   7500:     }
1.976     raeburn  7501:     return if (!defined($tools{$tool}));
                   7502: 
1.1242    raeburn  7503:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7504:         $udom = $env{'user.domain'};
                   7505:         $uname = $env{'user.name'};
                   7506:     }
                   7507: 
1.978     raeburn  7508:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7509:         if ($action ne 'reload') {
1.985     raeburn  7510:             if ($context eq 'requestcourses') {
                   7511:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7512:             } elsif ($context eq 'requestauthor') {
                   7513:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7514:             } else {
                   7515:                 return $env{'environment.availabletools.'.$tool};
                   7516:             }
                   7517:         }
1.976     raeburn  7518:     }
                   7519: 
1.1183    raeburn  7520:     my ($toolstatus,$inststatus,$envkey);
                   7521:     if ($context eq 'requestauthor') {
                   7522:         $envkey = $context; 
                   7523:     } else {
                   7524:         $envkey = $context.'.'.$tool;
                   7525:     }
1.976     raeburn  7526: 
1.985     raeburn  7527:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7528:          ($action ne 'reload')) {
1.1183    raeburn  7529:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7530:         $inststatus = $env{'environment.inststatus'};
                   7531:     } else {
1.1084    raeburn  7532:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7533:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7534:             $inststatus = $userenvref->{'inststatus'};
                   7535:         } else {
1.1183    raeburn  7536:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7537:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7538:             $inststatus = $userenv{'inststatus'};
                   7539:         }
1.976     raeburn  7540:     }
                   7541: 
                   7542:     if ($toolstatus ne '') {
                   7543:         if ($toolstatus) {
                   7544:             $access = 1;
                   7545:         } else {
                   7546:             $access = 0;
                   7547:         }
                   7548:         return $access;
                   7549:     }
                   7550: 
1.1084    raeburn  7551:     my ($is_adv,%domdef);
                   7552:     if (ref($is_advref) eq 'HASH') {
                   7553:         $is_adv = $is_advref->{'is_adv'};
                   7554:     } else {
                   7555:         $is_adv = &is_advanced_user($udom,$uname);
                   7556:     }
                   7557:     if (ref($domdefref) eq 'HASH') {
                   7558:         %domdef = %{$domdefref};
                   7559:     } else {
                   7560:         %domdef = &get_domain_defaults($udom);
                   7561:     }
1.976     raeburn  7562:     if (ref($domdef{$tool}) eq 'HASH') {
                   7563:         if ($is_adv) {
                   7564:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7565:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7566:                     $access = 1;
                   7567:                 } else {
                   7568:                     $access = 0;
                   7569:                 }
                   7570:                 return $access;
                   7571:             }
                   7572:         }
                   7573:         if ($inststatus ne '') {
                   7574:             my ($hasaccess,$hasnoaccess);
                   7575:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7576:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7577:                     if ($domdef{$tool}{$affiliation}) {
                   7578:                         $hasaccess = 1;
                   7579:                     } else {
                   7580:                         $hasnoaccess = 1;
                   7581:                     }
                   7582:                 }
                   7583:             }
                   7584:             if ($hasaccess || $hasnoaccess) {
                   7585:                 if ($hasaccess) {
                   7586:                     $access = 1;
                   7587:                 } elsif ($hasnoaccess) {
                   7588:                     $access = 0; 
                   7589:                 }
                   7590:                 return $access;
                   7591:             }
                   7592:         } else {
                   7593:             if ($domdef{$tool}{'default'} ne '') {
                   7594:                 if ($domdef{$tool}{'default'}) {
                   7595:                     $access = 1;
                   7596:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7597:                     $access = 0;
                   7598:                 }
                   7599:                 return $access;
                   7600:             }
                   7601:         }
                   7602:     } else {
1.1177    raeburn  7603:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7604:             $access = 1;
                   7605:         } else {
                   7606:             $access = 0;
                   7607:         }
1.976     raeburn  7608:         return $access;
                   7609:     }
                   7610: }
                   7611: 
1.1050    raeburn  7612: sub is_course_owner {
                   7613:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7614:     if (($udom eq '') || ($uname eq '')) {
                   7615:         $udom = $env{'user.domain'};
                   7616:         $uname = $env{'user.name'};
                   7617:     }
                   7618:     unless (($udom eq '') || ($uname eq '')) {
                   7619:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7620:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7621:                 return 1;
                   7622:             } else {
                   7623:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7624:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7625:                     return 1;
                   7626:                 }
                   7627:             }
                   7628:         }
                   7629:     }
                   7630:     return;
                   7631: }
                   7632: 
1.976     raeburn  7633: sub is_advanced_user {
                   7634:     my ($udom,$uname) = @_;
1.1085    raeburn  7635:     if ($udom ne '' && $uname ne '') {
                   7636:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7637:             if (wantarray) {
                   7638:                 return ($env{'user.adv'},$env{'user.author'});
                   7639:             } else {
                   7640:                 return $env{'user.adv'};
                   7641:             }
1.1085    raeburn  7642:         }
                   7643:     }
1.976     raeburn  7644:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7645:     my %allroles;
1.1128    raeburn  7646:     my ($is_adv,$is_author);
1.976     raeburn  7647:     foreach my $role (keys(%roleshash)) {
                   7648:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7649:         my $area = '/'.$tdomain.'/'.$trest;
                   7650:         if ($sec ne '') {
                   7651:             $area .= '/'.$sec;
                   7652:         }
                   7653:         if (($area ne '') && ($trole ne '')) {
                   7654:             my $spec=$trole.'.'.$area;
                   7655:             if ($trole =~ /^cr\//) {
                   7656:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7657:             } elsif ($trole ne 'gr') {
                   7658:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7659:             }
1.1128    raeburn  7660:             if ($trole eq 'au') {
                   7661:                 $is_author = 1;
                   7662:             }
1.976     raeburn  7663:         }
                   7664:     }
                   7665:     foreach my $role (keys(%allroles)) {
                   7666:         last if ($is_adv);
                   7667:         foreach my $item (split(/:/,$allroles{$role})) {
                   7668:             if ($item ne '') {
                   7669:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7670:                 if ($privilege eq 'adv') {
                   7671:                     $is_adv = 1;
                   7672:                     last;
                   7673:                 }
                   7674:             }
                   7675:         }
                   7676:     }
1.1128    raeburn  7677:     if (wantarray) {
                   7678:         return ($is_adv,$is_author);
                   7679:     }
1.976     raeburn  7680:     return $is_adv;
                   7681: }
1.798     raeburn  7682: 
1.1035    raeburn  7683: sub check_can_request {
1.1368    raeburn  7684:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  7685:     my $canreq = 0;
1.1368    raeburn  7686:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7687:         $uname = $env{'user.name'};
                   7688:         $udom = $env{'user.domain'};
                   7689:     }
1.1035    raeburn  7690:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7691:     my @options = ('approval','validate','autolimit');
                   7692:     my $optregex = join('|',@options);
                   7693:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7694:         foreach my $type (@{$types}) {
1.1368    raeburn  7695:             if (&usertools_access($uname,$udom,$type,undef,
                   7696:                                   'requestcourses')) {
1.1035    raeburn  7697:                 $canreq ++;
1.1036    raeburn  7698:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  7699:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  7700:                 }
1.1368    raeburn  7701:                 if ($dom eq $udom) {
1.1035    raeburn  7702:                     $can_request->{$type} = 1;
                   7703:                 }
                   7704:             }
1.1368    raeburn  7705:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   7706:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  7707:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7708:                 if (@curr > 0) {
1.1036    raeburn  7709:                     foreach my $item (@curr) {
                   7710:                         if (ref($request_domains) eq 'HASH') {
                   7711:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7712:                             if ($otherdom ne '') {
                   7713:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7714:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7715:                                         push(@{$request_domains->{$type}},$otherdom);
                   7716:                                     }
                   7717:                                 } else {
                   7718:                                     push(@{$request_domains->{$type}},$otherdom);
                   7719:                                 }
                   7720:                             }
                   7721:                         }
                   7722:                     }
1.1368    raeburn  7723:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  7724:                         $canreq ++;
1.1035    raeburn  7725:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7726:                             $can_request->{$type} = 1;
                   7727:                         }
                   7728:                     }
                   7729:                 }
                   7730:             }
                   7731:         }
                   7732:     }
                   7733:     return $canreq;
                   7734: }
                   7735: 
1.341     www      7736: # ---------------------------------------------- Custom access rule evaluation
                   7737: 
                   7738: sub customaccess {
                   7739:     my ($priv,$uri)=@_;
1.807     albertel 7740:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7741:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7742:     $udom = &LONCAPA::clean_domain($udom);
                   7743:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7744:     my $access=0;
1.800     albertel 7745:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7746: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7747: 	if ($type eq 'user') {
                   7748: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7749: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7750: 		if ($tdom) {
                   7751: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7752: 		}
1.896     albertel 7753: 		if ($tuname) {
                   7754: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7755: 		}
                   7756: 		$access=($effect eq 'allow');
                   7757: 		last;
                   7758: 	    }
                   7759: 	} else {
                   7760: 	    if ($role) {
                   7761: 		if ($role ne $urole) { next; }
                   7762: 	    }
                   7763: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7764: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7765: 		if ($tdom) {
                   7766: 		    if ($tdom ne $udom) { next; }
                   7767: 		}
                   7768: 		if ($tcrs) {
                   7769: 		    if ($tcrs ne $ucrs) { next; }
                   7770: 		}
                   7771: 		if ($tsec) {
                   7772: 		    if ($tsec ne $usec) { next; }
                   7773: 		}
                   7774: 		$access=($effect eq 'allow');
                   7775: 		last;
                   7776: 	    }
                   7777: 	    if ($realm eq '' && $role eq '') {
                   7778: 		$access=($effect eq 'allow');
                   7779: 	    }
1.402     bowersj2 7780: 	}
1.341     www      7781:     }
                   7782:     return $access;
                   7783: }
                   7784: 
1.103     harris41 7785: # ------------------------------------------------- Check for a user privilege
1.12      www      7786: 
                   7787: sub allowed {
1.1281    raeburn  7788:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7789:     my $ver_orguri=$uri;
1.439     www      7790:     $uri=&deversion($uri);
1.152     www      7791:     my $orguri=$uri;
1.52      www      7792:     $uri=&declutter($uri);
1.809     raeburn  7793: 
1.810     raeburn  7794:     if ($priv eq 'evb') {
                   7795: # Evade communication block restrictions for specified role in a course
                   7796:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7797:             return $1;
                   7798:         } else {
                   7799:             return;
                   7800:         }
                   7801:     }
                   7802: 
1.620     albertel 7803:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7804: # Free bre access to adm and meta resources
1.1343    raeburn  7805:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7806: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7807: 	&& ($priv eq 'bre')) {
1.14      www      7808: 	return 'F';
1.159     www      7809:     }
                   7810: 
1.545     banghart 7811: # Free bre access to user's own portfolio contents
1.714     raeburn  7812:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7813:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7814: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7815:         my %setters;
                   7816:         my ($startblock,$endblock) = 
                   7817:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7818:         if ($startblock && $endblock) {
                   7819:             return 'B';
                   7820:         } else {
                   7821:             return 'F';
                   7822:         }
1.545     banghart 7823:     }
                   7824: 
1.762     raeburn  7825: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7826:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7827:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7828:         if (exists($env{'request.course.id'})) {
                   7829:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7830:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7831:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7832:                 my $courseprivid=$env{'request.course.id'};
                   7833:                 $courseprivid=~s/\_/\//;
                   7834:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7835:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7836:                     return $1; 
1.762     raeburn  7837:                 } else {
                   7838:                     if ($env{'request.course.sec'}) {
                   7839:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7840:                     }
                   7841:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7842:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7843:                         return $2;
                   7844:                     }
1.714     raeburn  7845:                 }
                   7846:             }
                   7847:         }
                   7848:     }
                   7849: 
1.159     www      7850: # Free bre to public access
                   7851: 
                   7852:     if ($priv eq 'bre') {
1.1362    raeburn  7853:         my $copyright;
                   7854:         unless ($uri =~ /ext\.tool/) {
                   7855:             $copyright=&metadata($uri,'copyright');
                   7856:         }
1.620     albertel 7857: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7858:            return 'F'; 
                   7859:         }
1.238     www      7860:         if ($copyright eq 'priv') {
                   7861:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7862: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7863: 		return '';
                   7864:             }
                   7865:         }
                   7866:         if ($copyright eq 'domain') {
                   7867:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7868: 	    unless (($env{'user.domain'} eq $1) ||
                   7869:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7870: 		return '';
                   7871:             }
1.262     matthew  7872:         }
1.620     albertel 7873:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7874:             # Library role, so allow browsing of resources in this domain.
                   7875:             return 'F';
1.238     www      7876:         }
1.341     www      7877:         if ($copyright eq 'custom') {
                   7878: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7879:         }
1.14      www      7880:     }
1.264     matthew  7881:     # Domain coordinator is trying to create a course
1.620     albertel 7882:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7883:         # uri is the requested domain in this case.
                   7884:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7885:         # a role of dc for the domain in question.
1.620     albertel 7886:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7887:     }
1.29      www      7888: 
1.52      www      7889:     my $thisallowed='';
                   7890:     my $statecond=0;
                   7891:     my $courseprivid='';
                   7892: 
1.1039    raeburn  7893:     my $ownaccess;
1.1043    raeburn  7894:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7895:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7896:         if ($uri eq '') {
                   7897:             $ownaccess = 1;
                   7898:         } else {
                   7899:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7900:                 my $udom = $env{'user.domain'};
                   7901:                 my $uname = $env{'user.name'};
                   7902:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7903:                     $ownaccess = 1;
1.1040    raeburn  7904:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7905:                     unless ($uri =~ m{\.\./}) {
                   7906:                         $ownaccess = 1;
                   7907:                     }
                   7908:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7909:                     my $now = time;
                   7910:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7911:                         my $adom = $1;
                   7912:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7913:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7914:                                 my ($start,$end) = split('.',$env{$key});
                   7915:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7916:                                     $ownaccess = 1;
                   7917:                                     last;
                   7918:                                 }
                   7919:                             }
                   7920:                         }
                   7921:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7922:                         my $adom = $1;
                   7923:                         my $aname = $2;
1.1042    raeburn  7924:                         foreach my $role ('ca','aa') { 
                   7925:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7926:                                 my ($start,$end) =
                   7927:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7928:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7929:                                     $ownaccess = 1;
                   7930:                                     last;
                   7931:                                 }
1.1039    raeburn  7932:                             }
                   7933:                         }
                   7934:                     }
                   7935:                 }
                   7936:             }
                   7937:         }
                   7938:     }
                   7939: 
1.52      www      7940: # Course
                   7941: 
1.620     albertel 7942:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7943:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7944:             $thisallowed.=$1;
                   7945:         }
1.52      www      7946:     }
1.29      www      7947: 
1.52      www      7948: # Domain
                   7949: 
1.620     albertel 7950:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7951:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7952:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7953:             $thisallowed.=$1;
                   7954:         }
1.12      www      7955:     }
1.52      www      7956: 
1.1141    raeburn  7957: # User who is not author or co-author might still be able to edit
                   7958: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7959:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7960:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7961:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7962:             $thisallowed.=$1;
                   7963:         }
                   7964:     }
                   7965: 
1.52      www      7966: # Course: uri itself is a course
1.66      www      7967:     my $courseuri=$uri;
                   7968:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7969:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7970: 
1.620     albertel 7971:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7972:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7973:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7974:             $thisallowed.=$1;
                   7975:         }
1.12      www      7976:     }
1.29      www      7977: 
1.665     albertel 7978: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7979: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7980:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7981: 	$thisallowed='';
1.671     raeburn  7982:         my ($match)=&is_on_map($uri);
                   7983:         if ($match) {
                   7984:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7985:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7986:                 my $value = $1;
1.1402  ! raeburn  7987:                 my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
        !          7988:                 if ($deeplinkblock) {
        !          7989:                     $thisallowed='D';
        !          7990:                 } elsif ($noblockcheck) {
1.1281    raeburn  7991:                     $thisallowed.=$value;
1.1162    raeburn  7992:                 } else {
1.1281    raeburn  7993:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7994:                     if (@blockers > 0) {
                   7995:                         $thisallowed = 'B';
                   7996:                     } else {
                   7997:                         $thisallowed.=$value;
                   7998:                     }
1.1162    raeburn  7999:                 }
1.671     raeburn  8000:             }
                   8001:         } else {
1.705     albertel 8002:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8003:             if ($refuri) {
                   8004:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8005:                     $thisallowed='F';
1.671     raeburn  8006:                 } else {
                   8007:                     $refuri=&declutter($refuri);
                   8008:                     my ($match) = &is_on_map($refuri);
                   8009:                     if ($match) {
1.1402  ! raeburn  8010:                         my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
        !          8011:                         if ($deeplinkblock) {
        !          8012:                             $thisallowed='D';
        !          8013:                         } elsif ($noblockcheck) {
1.1281    raeburn  8014:                             $thisallowed='F';
1.1162    raeburn  8015:                         } else {
1.1281    raeburn  8016:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   8017:                             if (@blockers > 0) {
                   8018:                                 $thisallowed = 'B';
                   8019:                             } else {
                   8020:                                 $thisallowed='F';
                   8021:                             }
1.1162    raeburn  8022:                         }
1.671     raeburn  8023:                     }
1.669     raeburn  8024:                 }
1.671     raeburn  8025:             }
                   8026:         }
1.314     www      8027:     }
1.492     albertel 8028: 
1.766     albertel 8029:     if ($priv eq 'bre'
                   8030: 	&& $thisallowed ne 'F' 
                   8031: 	&& $thisallowed ne '2'
                   8032: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  8033: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8034:     }
1.1250    raeburn  8035: 
1.52      www      8036: # Full access at system, domain or course-wide level? Exit.
1.29      www      8037:     if ($thisallowed=~/F/) {
                   8038: 	return 'F';
                   8039:     }
                   8040: 
1.52      www      8041: # If this is generating or modifying users, exit with special codes
1.29      www      8042: 
1.643     www      8043:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8044: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8045: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8046: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8047: 	    unless ($auname) { return $thisallowed; }
                   8048: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8049: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8050: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8051: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8052: 	}
1.52      www      8053: 	return $thisallowed;
                   8054:     }
                   8055: #
1.103     harris41 8056: # Gathered so far: system, domain and course wide privileges
1.52      www      8057: #
                   8058: # Course: See if uri or referer is an individual resource that is part of 
                   8059: # the course
                   8060: 
1.620     albertel 8061:     if ($env{'request.course.id'}) {
1.232     www      8062: 
1.620     albertel 8063:        $courseprivid=$env{'request.course.id'};
                   8064:        if ($env{'request.course.sec'}) {
                   8065:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8066:        }
                   8067:        $courseprivid=~s/\_/\//;
                   8068:        my $checkreferer=1;
1.232     www      8069:        my ($match,$cond)=&is_on_map($uri);
                   8070:        if ($match) {
                   8071:            $statecond=$cond;
1.620     albertel 8072:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8073:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8074:                my $value = $1;
                   8075:                if ($priv eq 'bre') {
1.1281    raeburn  8076:                    if ($noblockcheck) {
                   8077:                        $thisallowed.=$value;
1.1162    raeburn  8078:                    } else {
1.1281    raeburn  8079:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   8080:                        if (@blockers > 0) {
                   8081:                            $thisallowed = 'B';
                   8082:                        } else {
                   8083:                            $thisallowed.=$value;
                   8084:                        }
1.1162    raeburn  8085:                    }
                   8086:                } else {
                   8087:                    $thisallowed.=$value;
                   8088:                }
1.52      www      8089:                $checkreferer=0;
                   8090:            }
1.29      www      8091:        }
1.83      www      8092:        
1.148     www      8093:        if ($checkreferer) {
1.620     albertel 8094: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8095:             unless ($refuri) {
1.800     albertel 8096:                 foreach my $key (keys(%env)) {
                   8097: 		    if ($key=~/^httpref\..*\*/) {
                   8098: 			my $pattern=$key;
1.156     www      8099:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8100:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8101:                         $pattern=~s/\//\\\//g;
1.152     www      8102:                         if ($orguri=~/$pattern/) {
1.800     albertel 8103: 			    $refuri=$env{$key};
1.148     www      8104:                         }
                   8105:                     }
1.191     harris41 8106:                 }
1.148     www      8107:             }
1.232     www      8108: 
1.148     www      8109:          if ($refuri) { 
1.152     www      8110: 	  $refuri=&declutter($refuri);
1.232     www      8111:           my ($match,$cond)=&is_on_map($refuri);
                   8112:             if ($match) {
                   8113:               my $refstatecond=$cond;
1.620     albertel 8114:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8115:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8116:                   my $value = $1;
                   8117:                   if ($priv eq 'bre') {
1.1402  ! raeburn  8118:                       my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
        !          8119:                       if ($deeplinkblock) {
        !          8120:                           $thisallowed = 'D';
        !          8121:                       } elsif ($noblockcheck) {
1.1281    raeburn  8122:                           $thisallowed.=$value;
1.1162    raeburn  8123:                       } else {
1.1281    raeburn  8124:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   8125:                           if (@blockers > 0) {
                   8126:                               $thisallowed = 'B';
                   8127:                           } else {
                   8128:                               $thisallowed.=$value;
                   8129:                           }
1.1162    raeburn  8130:                       }
                   8131:                   } else {
                   8132:                       $thisallowed.=$value;
                   8133:                   }
1.53      www      8134:                   $uri=$refuri;
                   8135:                   $statecond=$refstatecond;
1.52      www      8136:               }
                   8137:           }
1.148     www      8138:         }
1.29      www      8139:        }
1.52      www      8140:    }
1.29      www      8141: 
1.52      www      8142: #
1.103     harris41 8143: # Gathered now: all privileges that could apply, and condition number
1.52      www      8144: # 
                   8145: #
                   8146: # Full or no access?
                   8147: #
1.29      www      8148: 
1.52      www      8149:     if ($thisallowed=~/F/) {
                   8150: 	return 'F';
                   8151:     }
1.29      www      8152: 
1.52      www      8153:     unless ($thisallowed) {
                   8154:         return '';
                   8155:     }
1.29      www      8156: 
1.52      www      8157: # Restrictions exist, deal with them
                   8158: #
                   8159: #   C:according to course preferences
                   8160: #   R:according to resource settings
                   8161: #   L:unless locked
                   8162: #   X:according to user session state
                   8163: #
                   8164: 
                   8165: # Possibly locked functionality, check all courses
1.54      www      8166: # Locks might take effect only after 10 minutes cache expiration for other
                   8167: # courses, and 2 minutes for current course
1.52      www      8168: 
                   8169:     my $envkey;
                   8170:     if ($thisallowed=~/L/) {
1.1000    raeburn  8171:         foreach $envkey (keys(%env)) {
1.54      www      8172:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8173:                my $courseid=$2;
                   8174:                my $roleid=$1.'.'.$2;
1.92      www      8175:                $courseid=~s/^\///;
1.54      www      8176:                my $expiretime=600;
1.620     albertel 8177:                if ($env{'request.role'} eq $roleid) {
1.54      www      8178: 		  $expiretime=120;
                   8179:                }
                   8180: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8181:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8182:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8183: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8184:                }
1.620     albertel 8185:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8186:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8187: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8188:                        &log($env{'user.domain'},$env{'user.name'},
                   8189:                             $env{'user.home'},
1.57      www      8190:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8191:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8192:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8193: 		       return '';
                   8194:                    }
                   8195:                }
1.620     albertel 8196:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8197:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8198: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8199:                        &log($env{'user.domain'},$env{'user.name'},
                   8200:                             $env{'user.home'},
1.57      www      8201:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8202:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8203:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8204: 		       return '';
                   8205:                    }
                   8206:                }
                   8207: 	   }
1.29      www      8208:        }
1.52      www      8209:     }
                   8210:    
                   8211: #
                   8212: # Rest of the restrictions depend on selected course
                   8213: #
                   8214: 
1.620     albertel 8215:     unless ($env{'request.course.id'}) {
1.766     albertel 8216: 	if ($thisallowed eq 'A') {
                   8217: 	    return 'A';
1.814     raeburn  8218:         } elsif ($thisallowed eq 'B') {
                   8219:             return 'B';
1.766     albertel 8220: 	} else {
                   8221: 	    return '1';
                   8222: 	}
1.52      www      8223:     }
1.29      www      8224: 
1.52      www      8225: #
                   8226: # Now user is definitely in a course
                   8227: #
1.53      www      8228: 
                   8229: 
                   8230: # Course preferences
                   8231: 
                   8232:    if ($thisallowed=~/C/) {
1.620     albertel 8233:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8234:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8235:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8236: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  8237: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8238: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8239: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8240: 			$env{'request.course.id'});
                   8241: 	   }
1.237     www      8242:            return '';
                   8243:        }
                   8244: 
1.620     albertel 8245:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8246: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  8247: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8248: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8249: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8250: 			$env{'request.course.id'});
                   8251: 	   }
1.54      www      8252:            return '';
                   8253:        }
1.53      www      8254:    }
                   8255: 
                   8256: # Resource preferences
                   8257: 
                   8258:    if ($thisallowed=~/R/) {
1.620     albertel 8259:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8260:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8261: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8262: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8263: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8264: 	   }
                   8265: 	   return '';
1.54      www      8266:        }
1.53      www      8267:    }
1.30      www      8268: 
1.246     www      8269: # Restricted by state or randomout?
1.30      www      8270: 
1.52      www      8271:    if ($thisallowed=~/X/) {
1.620     albertel 8272:       if ($env{'acc.randomout'}) {
1.579     albertel 8273: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8274:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8275:             return ''; 
                   8276:          }
1.247     www      8277:       }
                   8278:       if (&condval($statecond)) {
1.52      www      8279: 	 return '2';
                   8280:       } else {
                   8281:          return '';
                   8282:       }
                   8283:    }
1.30      www      8284: 
1.766     albertel 8285:     if ($thisallowed eq 'A') {
                   8286: 	return 'A';
1.814     raeburn  8287:     } elsif ($thisallowed eq 'B') {
                   8288:         return 'B';
1.1402  ! raeburn  8289:     } elsif ($thisallowed eq 'D') {
        !          8290:         return 'D';
1.766     albertel 8291:     }
1.52      www      8292:    return 'F';
1.232     www      8293: }
1.1162    raeburn  8294: 
1.1192    raeburn  8295: # ------------------------------------------- Check construction space access
                   8296: 
                   8297: sub constructaccess {
                   8298:     my ($url,$setpriv)=@_;
                   8299: 
                   8300: # We do not allow editing of previous versions of files
                   8301:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8302: 
                   8303: # Get username and domain from URL
                   8304:     my ($ownername,$ownerdomain,$ownerhome);
                   8305: 
                   8306:     ($ownerdomain,$ownername) =
1.1325    raeburn  8307:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  8308: 
                   8309: # The URL does not really point to any authorspace, forget it
                   8310:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8311: 
                   8312: # Now we need to see if the user has access to the authorspace of
                   8313: # $ownername at $ownerdomain
                   8314: 
                   8315:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8316: # Real author for this?
                   8317:        $ownerhome = $env{'user.home'};
                   8318:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8319:           return ($ownername,$ownerdomain,$ownerhome);
                   8320:        }
                   8321:     } else {
                   8322: # Co-author for this?
                   8323:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8324:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8325:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8326:             return ($ownername,$ownerdomain,$ownerhome);
                   8327:         }
1.1312    raeburn  8328:         if ($env{'request.course.id'}) {
                   8329:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   8330:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   8331:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   8332:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   8333:                     return ($ownername,$ownerdomain,$ownerhome);
                   8334:                 }
                   8335:             }
                   8336:         }
1.1192    raeburn  8337:     }
                   8338: 
                   8339: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8340: # we might as well leave
                   8341:    unless ($setpriv) { return ''; }
                   8342: 
                   8343: # Backdoor access?
                   8344:     my $allowed=&allowed('eco',$ownerdomain);
                   8345: # Nope
                   8346:     unless ($allowed) { return ''; }
                   8347: # Looks like we may have access, but could be locked by the owner of the construction space
                   8348:     if ($allowed eq 'U') {
                   8349:         my %blocked=&get('environment',['domcoord.author'],
                   8350:                          $ownerdomain,$ownername);
                   8351: # Is blocked by owner
                   8352:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8353:     }
                   8354:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8355: # Grant temporary access
                   8356:         my $then=$env{'user.login.time'};
1.1209    raeburn  8357:         my $update=$env{'user.update.time'};
1.1192    raeburn  8358:         if (!$update) { $update = $then; }
                   8359:         my $refresh=$env{'user.refresh.time'};
                   8360:         if (!$refresh) { $refresh = $update; }
                   8361:         my $now = time;
                   8362:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8363:                            $now,'ca','constructaccess');
                   8364:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8365:         return($ownername,$ownerdomain,$ownerhome);
                   8366:     }
                   8367: # No business here
                   8368:     return '';
                   8369: }
                   8370: 
1.1282    raeburn  8371: # ----------------------------------------------------------- Content Blocking
                   8372: 
                   8373: {
                   8374: # Caches for faster Course Contents display where content blocking
                   8375: # is in operation (i.e., interval param set) for timed quiz.
                   8376: #
                   8377: # User for whom data are being temporarily cached.
                   8378: my $cacheduser='';
                   8379: # Cached blockers for this user (a hash of blocking items). 
                   8380: my %cachedblockers=();
                   8381: # When the data were last cached.
                   8382: my $cachedlast='';
                   8383: 
                   8384: sub load_all_blockers {
                   8385:     my ($uname,$udom,$blocks)=@_;
                   8386:     if (($uname ne '') && ($udom ne '')) { 
                   8387:         if (($cacheduser eq $uname.':'.$udom) &&
                   8388:             (abs($cachedlast-time)<5)) {
                   8389:             return;
                   8390:         }
                   8391:     }
                   8392:     $cachedlast=time;
                   8393:     $cacheduser=$uname.':'.$udom;
                   8394:     %cachedblockers = &get_commblock_resources($blocks);
                   8395: }
                   8396: 
1.1162    raeburn  8397: sub get_comm_blocks {
                   8398:     my ($cdom,$cnum) = @_;
                   8399:     if ($cdom eq '' || $cnum eq '') {
                   8400:         return unless ($env{'request.course.id'});
                   8401:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8402:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8403:     }
                   8404:     my %commblocks;
                   8405:     my $hashid=$cdom.'_'.$cnum;
                   8406:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8407:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8408:         %commblocks = %{$blocksref};
                   8409:     } else {
                   8410:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8411:         my $cachetime = 600;
                   8412:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8413:     }
                   8414:     return %commblocks;
                   8415: }
                   8416: 
1.1282    raeburn  8417: sub get_commblock_resources {
                   8418:     my ($blocks) = @_;
                   8419:     my %blockers = ();
                   8420:     return %blockers unless ($env{'request.course.id'});
                   8421:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8422:     my %commblocks;
                   8423:     if (ref($blocks) eq 'HASH') {
                   8424:         %commblocks = %{$blocks};
                   8425:     } else {
                   8426:         %commblocks = &get_comm_blocks();
                   8427:     }
1.1282    raeburn  8428:     return %blockers unless (keys(%commblocks) > 0); 
                   8429:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8430:     return %blockers unless (ref($navmap));
1.1162    raeburn  8431:     my $now = time;
                   8432:     foreach my $block (keys(%commblocks)) {
                   8433:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8434:             my ($start,$end) = ($1,$2);
                   8435:             if ($start <= $now && $end >= $now) {
                   8436:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8437:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8438:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8439:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8440:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8441:                             }
                   8442:                         }
                   8443:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8444:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8445:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8446:                             }
                   8447:                         }
                   8448:                     }
                   8449:                 }
                   8450:             }
                   8451:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8452:             my $item = $1;
1.1163    raeburn  8453:             my @to_test;
1.1162    raeburn  8454:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8455:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  8456:                     my @interval;
                   8457:                     my $type = 'map';
                   8458:                     if ($item eq 'course') {
                   8459:                         $type = 'course';
                   8460:                         @interval=&EXT("resource.0.interval");
                   8461:                     } else {
                   8462:                         if ($item =~ /___\d+___/) {
                   8463:                             $type = 'resource';
                   8464:                             @interval=&EXT("resource.0.interval",$item);
                   8465:                             if (ref($navmap)) {                        
                   8466:                                 my $res = $navmap->getBySymb($item); 
                   8467:                                 push(@to_test,$res);
                   8468:                             }
1.1162    raeburn  8469:                         } else {
1.1282    raeburn  8470:                             my $mapsymb = &symbread($item,1);
                   8471:                             if ($mapsymb) {
                   8472:                                 if (ref($navmap)) {
                   8473:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8474:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8475:                                     foreach my $res (@to_test) {
                   8476:                                         my $symb = $res->symb();
                   8477:                                         next if ($symb eq $mapsymb);
                   8478:                                         if ($symb ne '') {
                   8479:                                             @interval=&EXT("resource.0.interval",$symb);
                   8480:                                             if ($interval[1] eq 'map') {
                   8481:                                                 last;
1.1162    raeburn  8482:                                             }
                   8483:                                         }
                   8484:                                     }
                   8485:                                 }
                   8486:                             }
                   8487:                         }
1.1282    raeburn  8488:                     }
1.1310    raeburn  8489:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8490:                         my $timelimit = $1; 
1.1282    raeburn  8491:                         my $first_access;
                   8492:                         if ($type eq 'resource') {
                   8493:                             $first_access=&get_first_access($interval[1],$item);
                   8494:                         } elsif ($type eq 'map') {
                   8495:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8496:                         } else {
                   8497:                             $first_access=&get_first_access($interval[1]);
                   8498:                         }
                   8499:                         if ($first_access) {
1.1292    raeburn  8500:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8501:                             if ($timesup > $now) {
                   8502:                                 my $activeblock;
                   8503:                                 foreach my $res (@to_test) {
1.1283    raeburn  8504:                                     if ($res->answerable()) {
1.1282    raeburn  8505:                                         $activeblock = 1;
                   8506:                                         last;
                   8507:                                     }
                   8508:                                 }
                   8509:                                 if ($activeblock) {
                   8510:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8511:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8512:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8513:                                          }
                   8514:                                     }
                   8515:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8516:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8517:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8518:                                         }
1.1162    raeburn  8519:                                     }
                   8520:                                 }
                   8521:                             }
                   8522:                         }
                   8523:                     }
                   8524:                 }
                   8525:             }
                   8526:         }
                   8527:     }
1.1282    raeburn  8528:     return %blockers;
1.1162    raeburn  8529: }
                   8530: 
1.1282    raeburn  8531: sub has_comm_blocking {
                   8532:     my ($priv,$symb,$uri,$blocks) = @_;
                   8533:     my @blockers;
                   8534:     return unless ($env{'request.course.id'});
                   8535:     return unless ($priv eq 'bre');
                   8536:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8537:     return if ($env{'request.state'} eq 'construct');
                   8538:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8539:     return unless (keys(%cachedblockers) > 0);
                   8540:     my (%possibles,@symbs);
                   8541:     if (!$symb) {
                   8542:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8543:     }
1.1282    raeburn  8544:     if ($symb) {
                   8545:         @symbs = ($symb);
                   8546:     } elsif (keys(%possibles)) { 
                   8547:         @symbs = keys(%possibles);
                   8548:     }
                   8549:     my $noblock;
                   8550:     foreach my $symb (@symbs) {
                   8551:         last if ($noblock);
                   8552:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8553:         foreach my $block (keys(%cachedblockers)) {
                   8554:             if ($block =~ /^firstaccess____(.+)$/) {
                   8555:                 my $item = $1;
                   8556:                 if (($item eq $map) || ($item eq $symb)) {
                   8557:                     $noblock = 1;
                   8558:                     last;
                   8559:                 }
                   8560:             }
                   8561:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8562:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8563:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8564:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8565:                             push(@blockers,$block);
                   8566:                         }
                   8567:                     }
                   8568:                 }
1.1162    raeburn  8569:             }
1.1282    raeburn  8570:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8571:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8572:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8573:                         push(@blockers,$block);
                   8574:                     }
                   8575:                 }
1.1162    raeburn  8576:             }
                   8577:         }
                   8578:     }
1.1282    raeburn  8579:     return if ($noblock);
                   8580:     return @blockers;
                   8581: }
1.1162    raeburn  8582: }
                   8583: 
1.1402  ! raeburn  8584: sub deeplink_check {
        !          8585:     my ($priv,$symb,$uri) = @_;
        !          8586:     return unless ($env{'request.course.id'});
        !          8587:     return unless ($priv eq 'bre');
        !          8588:     return if ($env{'request.state'} eq 'construct');
        !          8589:     return if ($env{'request.role.adv'});
        !          8590:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
        !          8591:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
        !          8592:     my (%possibles,@symbs);
        !          8593:     if (!$symb) {
        !          8594:         $symb = &symbread($uri,1,1,1,\%possibles);
        !          8595:     }
        !          8596:     if ($symb) {
        !          8597:         @symbs = ($symb);
        !          8598:     } elsif (keys(%possibles)) {
        !          8599:         @symbs = keys(%possibles);
        !          8600:     }
        !          8601: 
        !          8602:     my ($login,$switchrole,$allow);
        !          8603:     if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
        !          8604:         my $key = $1;
        !          8605:         my $tinyurl;
        !          8606:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
        !          8607:         if (defined($cached)) {
        !          8608:              $tinyurl = $result;
        !          8609:         } else {
        !          8610:              my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
        !          8611:              my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
        !          8612:              if ($currtiny{$key} ne '') {
        !          8613:                  $tinyurl = $currtiny{$key};
        !          8614:                  &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
        !          8615:              }
        !          8616:         }
        !          8617:         if ($tinyurl ne '') {
        !          8618:             my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
        !          8619:             if ($cnumreq eq $cnum) {
        !          8620:                 $login = $posslogin;
        !          8621:             } else {
        !          8622:                 $switchrole = 1;
        !          8623:             }
        !          8624:         }
        !          8625:     }
        !          8626:     foreach my $symb (@symbs) {
        !          8627:         last if ($allow);
        !          8628:         my $deeplink = &EXT("resource.0.deeplink",$symb);
        !          8629:         if ($deeplink eq '') {
        !          8630:             $allow = 1;
        !          8631:         } else {
        !          8632:             my ($listed,$scope,$access) = split(/,/,$deeplink);
        !          8633:             if ($access eq 'any') {
        !          8634:                 $allow = 1;
        !          8635:             } elsif ($login) {
        !          8636:                 if ($access eq 'only') {
        !          8637:                     if ($scope eq 'res') {
        !          8638:                         if ($symb eq $login) {
        !          8639:                             $allow = 1;
        !          8640:                         }
        !          8641:                     } elsif ($scope eq 'map') {
        !          8642: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
        !          8643:                     } elsif ($scope eq 'rec') {
        !          8644: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
        !          8645:                     }
        !          8646:                 } else {
        !          8647:                     my ($acctype,$item) = split(/:/,$access);
        !          8648:                     if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
        !          8649:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
        !          8650:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
        !          8651:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
        !          8652:                                 $allow = 1;
        !          8653:                             }
        !          8654:                         }
        !          8655:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
        !          8656:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
        !          8657:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
        !          8658:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
        !          8659:                                 $allow = 1;
        !          8660:                             }
        !          8661:                         }
        !          8662:                     }
        !          8663:                 }
        !          8664:             }
        !          8665:         }
        !          8666:     }
        !          8667:     return if ($allow);
        !          8668:     return 1;
        !          8669: }
        !          8670: 
1.1282    raeburn  8671: # -------------------------------- Deversion and split uri into path an filename   
                   8672: 
1.1133    foxr     8673: #
1.1282    raeburn  8674: #   Removes the version from a URI and
1.1133    foxr     8675: #   splits it in to its filename and path to the filename.
                   8676: #   Seems like File::Basename could have done this more clearly.
                   8677: #   Parameters:
                   8678: #      $uri   - input URI
                   8679: #   Returns:
                   8680: #     Two element list consisting of 
                   8681: #     $pathname  - the URI up to and excluding the trailing /
                   8682: #     $filename  - The part of the URI following the last /
                   8683: #  NOTE:
                   8684: #    Another realization of this is simply:
                   8685: #    use File::Basename;
                   8686: #    ...
                   8687: #    $uri = shift;
                   8688: #    $filename = basename($uri);
                   8689: #    $path     = dirname($uri);
                   8690: #    return ($filename, $path);
                   8691: #
                   8692: #     The implementation below is probably faster however.
                   8693: #
1.710     albertel 8694: sub split_uri_for_cond {
                   8695:     my $uri=&deversion(&declutter(shift));
                   8696:     my @uriparts=split(/\//,$uri);
                   8697:     my $filename=pop(@uriparts);
                   8698:     my $pathname=join('/',@uriparts);
                   8699:     return ($pathname,$filename);
                   8700: }
1.232     www      8701: # --------------------------------------------------- Is a resource on the map?
                   8702: 
                   8703: sub is_on_map {
1.710     albertel 8704:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8705:     #Trying to find the conditional for the file
1.620     albertel 8706:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8707: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8708:     if ($match) {
1.289     bowersj2 8709: 	return (1,$1);
                   8710:     } else {
1.434     www      8711: 	return (0,0);
1.289     bowersj2 8712:     }
1.12      www      8713: }
                   8714: 
1.427     www      8715: # --------------------------------------------------------- Get symb from alias
                   8716: 
                   8717: sub get_symb_from_alias {
                   8718:     my $symb=shift;
                   8719:     my ($map,$resid,$url)=&decode_symb($symb);
                   8720: # Already is a symb
                   8721:     if ($url) { return $symb; }
                   8722: # Must be an alias
                   8723:     my $aliassymb='';
                   8724:     my %bighash;
1.620     albertel 8725:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8726:                             &GDBM_READER(),0640)) {
                   8727:         my $rid=$bighash{'mapalias_'.$symb};
                   8728: 	if ($rid) {
                   8729: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8730: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8731: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8732: 	}
                   8733:         untie %bighash;
                   8734:     }
                   8735:     return $aliassymb;
                   8736: }
                   8737: 
1.12      www      8738: # ----------------------------------------------------------------- Define Role
                   8739: 
                   8740: sub definerole {
                   8741:   if (allowed('mcr','/')) {
1.1326    raeburn  8742:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8743:     foreach my $role (split(':',$sysrole)) {
                   8744: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8745:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8746:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8747: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8748:                return "refused:s:$crole&$cqual"; 
                   8749:             }
                   8750:         }
1.191     harris41 8751:     }
1.800     albertel 8752:     foreach my $role (split(':',$domrole)) {
                   8753: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8754:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8755:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8756: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8757:                return "refused:d:$crole&$cqual"; 
                   8758:             }
                   8759:         }
1.191     harris41 8760:     }
1.800     albertel 8761:     foreach my $role (split(':',$courole)) {
                   8762: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8763:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8764:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8765: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8766:                return "refused:c:$crole&$cqual"; 
                   8767:             }
                   8768:         }
1.191     harris41 8769:     }
1.1326    raeburn  8770:     my $uhome;
                   8771:     if (($uname ne '') && ($udom ne '')) {
                   8772:         $uhome = &homeserver($uname,$udom);
                   8773:         return $uhome if ($uhome eq 'no_host');
                   8774:     } else {
                   8775:         $uname = $env{'user.name'};
                   8776:         $udom = $env{'user.domain'};
                   8777:         $uhome = $env{'user.home'};
                   8778:     }
1.620     albertel 8779:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  8780:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8781:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  8782:     return reply($command,$uhome);
1.12      www      8783:   } else {
                   8784:     return 'refused';
                   8785:   }
1.105     harris41 8786: }
                   8787: 
                   8788: # ---------------- Make a metadata query against the network of library servers
                   8789: 
                   8790: sub metadata_query {
1.1237    raeburn  8791:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8792:     my %rhash;
1.845     albertel 8793:     my %libserv = &all_library();
1.244     matthew  8794:     my @server_list = (defined($server_array) ? @$server_array
                   8795:                                               : keys(%libserv) );
                   8796:     for my $server (@server_list) {
1.1237    raeburn  8797:         my $domains = ''; 
                   8798:         if (ref($domains_hash) eq 'HASH') {
                   8799:             $domains = $domains_hash->{$server}; 
                   8800:         }
1.118     harris41 8801: 	unless ($custom or $customshow) {
1.1237    raeburn  8802: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8803: 	    $rhash{$server}=$reply;
                   8804: 	}
                   8805: 	else {
                   8806: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  8807: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8808: 			     $server);
                   8809: 	    $rhash{$server}=$reply;
                   8810: 	}
1.112     harris41 8811:     }
1.118     harris41 8812:     return \%rhash;
1.240     www      8813: }
                   8814: 
                   8815: # ----------------------------------------- Send log queries and wait for reply
                   8816: 
                   8817: sub log_query {
                   8818:     my ($uname,$udom,$query,%filters)=@_;
                   8819:     my $uhome=&homeserver($uname,$udom);
                   8820:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8821:     my $uhost=&hostname($uhome);
1.800     albertel 8822:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8823:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8824:                        $uhome);
1.479     albertel 8825:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8826:     return get_query_reply($queryid);
                   8827: }
                   8828: 
1.818     raeburn  8829: # -------------------------- Update MySQL table for portfolio file
                   8830: 
                   8831: sub update_portfolio_table {
1.821     raeburn  8832:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8833:     if ($group ne '') {
                   8834:         $file_name =~s /^\Q$group\E//;
                   8835:     }
1.818     raeburn  8836:     my $homeserver = &homeserver($uname,$udom);
                   8837:     my $queryid=
1.821     raeburn  8838:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8839:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8840:     my $reply = &get_query_reply($queryid);
                   8841:     return $reply;
                   8842: }
                   8843: 
1.899     raeburn  8844: # -------------------------- Update MySQL allusers table
                   8845: 
                   8846: sub update_allusers_table {
                   8847:     my ($uname,$udom,$names) = @_;
                   8848:     my $homeserver = &homeserver($uname,$udom);
                   8849:     my $queryid=
                   8850:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8851:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8852:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8853:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8854:                'generation='.&escape($names->{'generation'}).'%%'.
                   8855:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8856:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8857:     return;
1.899     raeburn  8858: }
                   8859: 
1.508     raeburn  8860: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8861: 
                   8862: sub fetch_enrollment_query {
1.511     raeburn  8863:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  8864:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8865:     my $maxtries = 1;
1.508     raeburn  8866:     if ($context eq 'automated') {
                   8867:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  8868:         $sleep = 2;
                   8869:         $loopmax = 100;
1.547     raeburn  8870:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8871:     } else {
                   8872:         $homeserver = &homeserver($cnum,$dom);
                   8873:     }
1.838     albertel 8874:     my $host=&hostname($homeserver);
1.506     raeburn  8875:     my $cmd = '';
1.1000    raeburn  8876:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8877:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8878:     }
                   8879:     $cmd =~ s/%%$//;
                   8880:     $cmd = &escape($cmd);
                   8881:     my $query = 'fetchenrollment';
1.620     albertel 8882:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8883:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8884:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8885:         return 'error: '.$queryid;
                   8886:     }
1.1317    raeburn  8887:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8888:     my $tries = 1;
                   8889:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  8890:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8891:         $tries ++;
                   8892:     }
1.526     raeburn  8893:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8894:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8895:     } else {
1.901     albertel 8896:         my @responses = split(/:/,$reply);
1.1322    raeburn  8897:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8898:             foreach my $line (@responses) {
                   8899:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8900:                 $$replyref{$key} = $value;
                   8901:             }
                   8902:         } else {
1.1117    foxr     8903:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8904:             foreach my $line (@responses) {
                   8905:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8906:                 $$replyref{$key} = $value;
                   8907:                 if ($value > 0) {
1.800     albertel 8908:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8909:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8910:                         my $destname = $pathname.'/'.$filename;
                   8911:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8912:                         if ($xml_classlist =~ /^error/) {
                   8913:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8914:                         } else {
1.1359    raeburn  8915:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8916:                                 print FILE &unescape($xml_classlist);
                   8917:                                 close(FILE);
1.526     raeburn  8918:                             } else {
                   8919:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8920:                             }
                   8921:                         }
                   8922:                     }
                   8923:                 }
                   8924:             }
                   8925:         }
                   8926:         return 'ok';
                   8927:     }
                   8928:     return 'error';
                   8929: }
                   8930: 
1.242     www      8931: sub get_query_reply {
1.1317    raeburn  8932:     my ($queryid,$sleep,$loopmax) = @_;;
                   8933:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8934:         $sleep = 0.2;
                   8935:     }
                   8936:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8937:         $loopmax = 100;
                   8938:     }
1.1117    foxr     8939:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8940:     my $reply='';
1.1317    raeburn  8941:     for (1..$loopmax) {
                   8942: 	sleep($sleep);
1.240     www      8943:         if (-e $replyfile.'.end') {
1.1359    raeburn  8944: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8945: 		$reply = join('',<$fh>);
                   8946: 		close($fh);
1.240     www      8947: 	   } else { return 'error: reply_file_error'; }
1.242     www      8948:            return &unescape($reply);
                   8949: 	}
1.240     www      8950:     }
1.242     www      8951:     return 'timeout:'.$queryid;
1.240     www      8952: }
                   8953: 
                   8954: sub courselog_query {
1.241     www      8955: #
                   8956: # possible filters:
                   8957: # url: url or symb
                   8958: # username
                   8959: # domain
                   8960: # action: view, submit, grade
                   8961: # start: timestamp
                   8962: # end: timestamp
                   8963: #
1.240     www      8964:     my (%filters)=@_;
1.620     albertel 8965:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8966:     if ($filters{'url'}) {
                   8967: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8968:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8969:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8970:     }
1.620     albertel 8971:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8972:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8973:     return &log_query($cname,$cdom,'courselog',%filters);
                   8974: }
                   8975: 
                   8976: sub userlog_query {
1.858     raeburn  8977: #
                   8978: # possible filters:
                   8979: # action: log check role
                   8980: # start: timestamp
                   8981: # end: timestamp
                   8982: #
1.240     www      8983:     my ($uname,$udom,%filters)=@_;
                   8984:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8985: }
                   8986: 
1.506     raeburn  8987: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8988: 
                   8989: sub auto_run {
1.508     raeburn  8990:     my ($cnum,$cdom) = @_;
1.876     raeburn  8991:     my $response = 0;
                   8992:     my $settings;
                   8993:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8994:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8995:         $settings = $domconfig{'autoenroll'};
                   8996:         if ($settings->{'run'} eq '1') {
                   8997:             $response = 1;
                   8998:         }
                   8999:     } else {
1.934     raeburn  9000:         my $homeserver;
                   9001:         if (&is_course($cdom,$cnum)) {
                   9002:             $homeserver = &homeserver($cnum,$cdom);
                   9003:         } else {
                   9004:             $homeserver = &domain($cdom,'primary');
                   9005:         }
                   9006:         if ($homeserver ne 'no_host') {
                   9007:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9008:         }
1.876     raeburn  9009:     }
1.506     raeburn  9010:     return $response;
                   9011: }
1.776     albertel 9012: 
1.506     raeburn  9013: sub auto_get_sections {
1.508     raeburn  9014:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9015:     my $homeserver;
                   9016:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9017:         $homeserver = &homeserver($cnum,$cdom);
                   9018:     }
                   9019:     if (!defined($homeserver)) { 
                   9020:         if ($cdom =~ /^$match_domain$/) {
                   9021:             $homeserver = &domain($cdom,'primary');
                   9022:         }
                   9023:     }
                   9024:     my @secs;
                   9025:     if (defined($homeserver)) {
                   9026:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9027:         unless ($response eq 'refused') {
                   9028:             @secs = split(/:/,$response);
                   9029:         }
1.506     raeburn  9030:     }
                   9031:     return @secs;
                   9032: }
1.776     albertel 9033: 
1.506     raeburn  9034: sub auto_new_course {
1.1099    raeburn  9035:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9036:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9037:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9038:     return $response;
                   9039: }
1.776     albertel 9040: 
1.506     raeburn  9041: sub auto_validate_courseID {
1.508     raeburn  9042:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9043:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9044:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9045:     return $response;
                   9046: }
1.776     albertel 9047: 
1.1007    raeburn  9048: sub auto_validate_instcode {
1.1020    raeburn  9049:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9050:     my ($homeserver,$response);
                   9051:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9052:         $homeserver = &homeserver($cnum,$cdom);
                   9053:     }
                   9054:     if (!defined($homeserver)) {
                   9055:         if ($cdom =~ /^$match_domain$/) {
                   9056:             $homeserver = &domain($cdom,'primary');
                   9057:         }
                   9058:     }
1.1065    raeburn  9059:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9060:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  9061:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9062:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9063: }
                   9064: 
1.506     raeburn  9065: sub auto_create_password {
1.873     raeburn  9066:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9067:     my ($homeserver,$response);
1.506     raeburn  9068:     my $create_passwd = 0;
                   9069:     my $authchk = '';
1.873     raeburn  9070:     if ($udom =~ /^$match_domain$/) {
                   9071:         $homeserver = &domain($udom,'primary');
                   9072:     }
                   9073:     if ($homeserver eq '') {
                   9074:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9075:             $homeserver = &homeserver($cnum,$cdom);
                   9076:         }
                   9077:     }
                   9078:     if ($homeserver eq '') {
                   9079:         $authchk = 'nodomain';
1.506     raeburn  9080:     } else {
1.873     raeburn  9081:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9082:         if ($response eq 'refused') {
                   9083:             $authchk = 'refused';
                   9084:         } else {
1.901     albertel 9085:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9086:         }
1.506     raeburn  9087:     }
                   9088:     return ($authparam,$create_passwd,$authchk);
                   9089: }
                   9090: 
1.706     raeburn  9091: sub auto_photo_permission {
                   9092:     my ($cnum,$cdom,$students) = @_;
                   9093:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9094:     my ($outcome,$perm_reqd,$conditions) = 
                   9095: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9096:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9097: 	return (undef,undef);
                   9098:     }
1.706     raeburn  9099:     return ($outcome,$perm_reqd,$conditions);
                   9100: }
                   9101: 
                   9102: sub auto_checkphotos {
                   9103:     my ($uname,$udom,$pid) = @_;
                   9104:     my $homeserver = &homeserver($uname,$udom);
                   9105:     my ($result,$resulttype);
                   9106:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9107: 				   &escape($uname).':'.&escape($pid),
                   9108: 				   $homeserver));
1.709     albertel 9109:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9110: 	return (undef,undef);
                   9111:     }
1.706     raeburn  9112:     if ($outcome) {
                   9113:         ($result,$resulttype) = split(/:/,$outcome);
                   9114:     } 
                   9115:     return ($result,$resulttype);
                   9116: }
                   9117: 
                   9118: sub auto_photochoice {
                   9119:     my ($cnum,$cdom) = @_;
                   9120:     my $homeserver = &homeserver($cnum,$cdom);
                   9121:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9122: 						       &escape($cdom),
                   9123: 						       $homeserver)));
1.709     albertel 9124:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9125: 	return (undef,undef);
                   9126:     }
1.706     raeburn  9127:     return ($update,$comment);
                   9128: }
                   9129: 
                   9130: sub auto_photoupdate {
                   9131:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9132:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9133:     my $host=&hostname($homeserver);
1.706     raeburn  9134:     my $cmd = '';
                   9135:     my $maxtries = 1;
1.800     albertel 9136:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9137:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9138:     }
                   9139:     $cmd =~ s/%%$//;
                   9140:     $cmd = &escape($cmd);
                   9141:     my $query = 'institutionalphotos';
                   9142:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9143:     unless ($queryid=~/^\Q$host\E\_/) {
                   9144:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9145:         return 'error: '.$queryid;
                   9146:     }
                   9147:     my $reply = &get_query_reply($queryid);
                   9148:     my $tries = 1;
                   9149:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9150:         $reply = &get_query_reply($queryid);
                   9151:         $tries ++;
                   9152:     }
                   9153:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9154:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9155:     } else {
                   9156:         my @responses = split(/:/,$reply);
                   9157:         my $outcome = shift(@responses); 
                   9158:         foreach my $item (@responses) {
                   9159:             my ($key,$value) = split(/=/,$item);
                   9160:             $$photo{$key} = $value;
                   9161:         }
                   9162:         return $outcome;
                   9163:     }
                   9164:     return 'error';
                   9165: }
                   9166: 
1.521     raeburn  9167: sub auto_instcode_format {
1.793     albertel 9168:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9169: 	$cat_order) = @_;
1.521     raeburn  9170:     my $courses = '';
1.772     raeburn  9171:     my @homeservers;
1.521     raeburn  9172:     if ($caller eq 'global') {
1.841     albertel 9173: 	my %servers = &get_servers($codedom,'library');
                   9174: 	foreach my $tryserver (keys(%servers)) {
                   9175: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9176: 		push(@homeservers,$tryserver);
                   9177: 	    }
1.584     raeburn  9178:         }
1.1022    raeburn  9179:     } elsif ($caller eq 'requests') {
                   9180:         if ($codedom =~ /^$match_domain$/) {
                   9181:             my $chome = &domain($codedom,'primary');
                   9182:             unless ($chome eq 'no_host') {
                   9183:                 push(@homeservers,$chome);
                   9184:             }
                   9185:         }
1.521     raeburn  9186:     } else {
1.772     raeburn  9187:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9188:     }
1.793     albertel 9189:     foreach my $code (keys(%{$instcodes})) {
                   9190:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9191:     }
                   9192:     chop($courses);
1.772     raeburn  9193:     my $ok_response = 0;
                   9194:     my $response;
                   9195:     while (@homeservers > 0 && $ok_response == 0) {
                   9196:         my $server = shift(@homeservers); 
                   9197:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9198:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9199:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9200: 		split(/:/,$response);
1.772     raeburn  9201:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9202:             push(@{$codetitles},&str2array($codetitles_str));
                   9203:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9204:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9205:             $ok_response = 1;
                   9206:         }
                   9207:     }
                   9208:     if ($ok_response) {
1.521     raeburn  9209:         return 'ok';
1.772     raeburn  9210:     } else {
                   9211:         return $response;
1.521     raeburn  9212:     }
                   9213: }
                   9214: 
1.792     raeburn  9215: sub auto_instcode_defaults {
                   9216:     my ($domain,$returnhash,$code_order) = @_;
                   9217:     my @homeservers;
1.841     albertel 9218: 
                   9219:     my %servers = &get_servers($domain,'library');
                   9220:     foreach my $tryserver (keys(%servers)) {
                   9221: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9222: 	    push(@homeservers,$tryserver);
                   9223: 	}
1.792     raeburn  9224:     }
1.841     albertel 9225: 
1.792     raeburn  9226:     my $response;
1.841     albertel 9227:     foreach my $server (@homeservers) {
1.792     raeburn  9228:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9229:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9230: 	
                   9231: 	foreach my $pair (split(/\&/,$response)) {
                   9232: 	    my ($name,$value)=split(/\=/,$pair);
                   9233: 	    if ($name eq 'code_order') {
                   9234: 		@{$code_order} = split(/\&/,&unescape($value));
                   9235: 	    } else {
                   9236: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9237: 	    }
                   9238: 	}
                   9239: 	return 'ok';
1.792     raeburn  9240:     }
1.841     albertel 9241: 
                   9242:     return $response;
1.1003    raeburn  9243: }
                   9244: 
                   9245: sub auto_possible_instcodes {
1.1007    raeburn  9246:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9247:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9248:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9249:         return;
                   9250:     }
1.1003    raeburn  9251:     my (@homeservers,$uhome);
                   9252:     if (defined(&domain($domain,'primary'))) {
                   9253:         $uhome=&domain($domain,'primary');
                   9254:         push(@homeservers,&domain($domain,'primary'));
                   9255:     } else {
                   9256:         my %servers = &get_servers($domain,'library');
                   9257:         foreach my $tryserver (keys(%servers)) {
                   9258:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9259:                 push(@homeservers,$tryserver);
                   9260:             }
                   9261:         }
                   9262:     }
                   9263:     my $response;
                   9264:     foreach my $server (@homeservers) {
                   9265:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9266:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9267:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9268:             split(':',$response);
                   9269:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9270:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9271:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9272:             my ($name,$value)=split('=',$item);
                   9273:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9274:         }
                   9275:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9276:             my ($name,$value)=split('=',$item);
                   9277:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9278:         }
                   9279:         return 'ok';
                   9280:     }
                   9281:     return $response;
                   9282: }
1.792     raeburn  9283: 
1.1010    raeburn  9284: sub auto_courserequest_checks {
                   9285:     my ($dom) = @_;
1.1020    raeburn  9286:     my ($homeserver,%validations);
                   9287:     if ($dom =~ /^$match_domain$/) {
                   9288:         $homeserver = &domain($dom,'primary');
                   9289:     }
                   9290:     unless ($homeserver eq 'no_host') {
                   9291:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9292:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9293:             my @items = split(/&/,$response);
                   9294:             foreach my $item (@items) {
                   9295:                 my ($key,$value) = split('=',$item);
                   9296:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9297:             }
                   9298:         }
                   9299:     }
1.1010    raeburn  9300:     return %validations; 
                   9301: }
                   9302: 
1.1020    raeburn  9303: sub auto_courserequest_validation {
1.1255    raeburn  9304:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9305:     my ($homeserver,$response);
                   9306:     if ($dom =~ /^$match_domain$/) {
                   9307:         $homeserver = &domain($dom,'primary');
                   9308:     }
1.1255    raeburn  9309:     unless ($homeserver eq 'no_host') {
                   9310:         my $customdata;
                   9311:         if (ref($custominfo) eq 'HASH') {
                   9312:             $customdata = &freeze_escape($custominfo);
                   9313:         }
1.1020    raeburn  9314:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9315:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  9316:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9317:                                     $customdata,$homeserver));
1.1020    raeburn  9318:     }
                   9319:     return $response;
                   9320: }
                   9321: 
1.777     albertel 9322: sub auto_validate_class_sec {
1.918     raeburn  9323:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9324:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9325:     my $ownerlist;
                   9326:     if (ref($owners) eq 'ARRAY') {
                   9327:         $ownerlist = join(',',@{$owners});
                   9328:     } else {
                   9329:         $ownerlist = $owners;
                   9330:     }
1.773     raeburn  9331:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9332:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9333:     return $response;
                   9334: }
                   9335: 
1.1367    raeburn  9336: sub auto_validate_instclasses {
                   9337:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9338:     my ($homeserver,%validations);
                   9339:     $homeserver = &homeserver($cnum,$cdom);
                   9340:     unless ($homeserver eq 'no_host') {
                   9341:         my $ownerlist;
                   9342:         if (ref($owners) eq 'ARRAY') {
                   9343:             $ownerlist = join(',',@{$owners});
                   9344:         } else {
                   9345:             $ownerlist = $owners;
                   9346:         }
                   9347:         if (ref($classesref) eq 'HASH') {
                   9348:             my $classes = &freeze_escape($classesref);
                   9349:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9350:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9351:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9352:                 my @items = split(/&/,$response);
                   9353:                 foreach my $item (@items) {
                   9354:                     my ($key,$value) = split('=',$item);
                   9355:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9356:                 }
                   9357:             }
                   9358:         }
                   9359:     }
                   9360:     return %validations;
                   9361: }
                   9362: 
1.1248    raeburn  9363: sub auto_crsreq_update {
                   9364:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  9365:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  9366:     my ($homeserver,%crsreqresponse);
                   9367:     if ($cdom =~ /^$match_domain$/) {
                   9368:         $homeserver = &domain($cdom,'primary');
                   9369:     }
                   9370:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9371:         my $info;
                   9372:         if (ref($inbound) eq 'HASH') {
                   9373:             $info = &freeze_escape($inbound);
                   9374:         }
                   9375:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9376:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9377:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  9378:                             &escape($title).':'.&escape($code).':'.
                   9379:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   9380:                             $homeserver);
1.1248    raeburn  9381:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9382:             my @items = split(/&/,$response);
                   9383:             foreach my $item (@items) {
                   9384:                 my ($key,$value) = split('=',$item);
                   9385:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9386:             }
                   9387:         }
                   9388:     }
                   9389:     return \%crsreqresponse;
                   9390: }
                   9391: 
1.1305    raeburn  9392: sub auto_export_grades {
1.1309    raeburn  9393:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9394:     my ($homeserver,%exportresponse);
                   9395:     if ($cdom =~ /^$match_domain$/) {
                   9396:         $homeserver = &domain($cdom,'primary');
                   9397:     }
                   9398:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9399:         my $info;
                   9400:         if (ref($inforef) eq 'HASH') {
                   9401:             $info = &freeze_escape($inforef);
                   9402:         }
                   9403:         if (ref($gradesref) eq 'HASH') {
                   9404:             my $grades = &freeze_escape($gradesref);
                   9405:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9406:                                 $info.':'.$grades,$homeserver);
                   9407:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9408:                 my @items = split(/&/,$response);
                   9409:                 foreach my $item (@items) {
                   9410:                     my ($key,$value) = split('=',$item);
                   9411:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9412:                 }
                   9413:             }
                   9414:         }
                   9415:     }
                   9416:     return \%exportresponse;
1.1305    raeburn  9417: }
                   9418: 
1.1287    raeburn  9419: sub check_instcode_cloning {
                   9420:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9421:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9422:         return;
                   9423:     }
                   9424:     my $canclone;
                   9425:     if (@{$code_order} > 0) {
                   9426:         my $instcoderegexp ='^';
                   9427:         my @clonecodes = split(/\&/,$cloner);
                   9428:         foreach my $item (@{$code_order}) {
                   9429:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9430:                 foreach my $pair (@clonecodes) {
                   9431:                     my ($key,$val) = split(/\=/,$pair,2);
                   9432:                     $val = &unescape($val);
                   9433:                     if ($key eq $item) {
                   9434:                         $instcoderegexp .= '('.$val.')';
                   9435:                         last;
                   9436:                     }
                   9437:                 }
                   9438:             } else {
                   9439:                 $instcoderegexp .= $codedefaults->{$item};
                   9440:             }
                   9441:         }
                   9442:         $instcoderegexp .= '$';
                   9443:         my (@from,@to);
                   9444:         eval {
                   9445:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9446:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9447:         };
                   9448:         if ((@from > 0) && (@to > 0)) {
                   9449:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9450:             if (!@diffs) {
                   9451:                 $canclone = 1;
                   9452:             }
                   9453:         }
                   9454:     }
                   9455:     return $canclone;
                   9456: }
                   9457: 
                   9458: sub default_instcode_cloning {
                   9459:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9460:     my (%codedefaults,@code_order,$canclone);
                   9461:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9462:         %codedefaults = %{$codedefaultsref};
                   9463:         @code_order = @{$codeorderref};
                   9464:     } elsif ($clonedom) {
                   9465:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9466:     }
                   9467:     if (($domdefclone) && (@code_order)) {
                   9468:         my @clonecodes = split(/\+/,$domdefclone);
                   9469:         my $instcoderegexp ='^';
                   9470:         foreach my $item (@code_order) {
                   9471:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9472:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9473:             } else {
                   9474:                 $instcoderegexp .= $codedefaults{$item};
                   9475:             }
                   9476:         }
                   9477:         $instcoderegexp .= '$';
                   9478:         my (@from,@to);
                   9479:         eval {
                   9480:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9481:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9482:         };
                   9483:         if ((@from > 0) && (@to > 0)) {
                   9484:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9485:             if (!@diffs) {
                   9486:                 $canclone = 1;
                   9487:             }
                   9488:         }
                   9489:     }
                   9490:     return $canclone;
                   9491: }
                   9492: 
1.679     raeburn  9493: # ------------------------------------------------------- Course Group routines
                   9494: 
                   9495: sub get_coursegroups {
1.809     raeburn  9496:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9497:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9498: }
                   9499: 
1.679     raeburn  9500: sub modify_coursegroup {
                   9501:     my ($cdom,$cnum,$groupsettings) = @_;
                   9502:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9503: }
                   9504: 
1.809     raeburn  9505: sub toggle_coursegroup_status {
                   9506:     my ($cdom,$cnum,$group,$action) = @_;
                   9507:     my ($from_namespace,$to_namespace);
                   9508:     if ($action eq 'delete') {
                   9509:         $from_namespace = 'coursegroups';
                   9510:         $to_namespace = 'deleted_groups';
                   9511:     } else {
                   9512:         $from_namespace = 'deleted_groups';
                   9513:         $to_namespace = 'coursegroups';
                   9514:     }
                   9515:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9516:     if (my $tmp = &error(%curr_group)) {
                   9517:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9518:         return ('read error',$tmp);
                   9519:     } else {
                   9520:         my %savedsettings = %curr_group; 
1.809     raeburn  9521:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9522:         my $deloutcome;
                   9523:         if ($result eq 'ok') {
1.809     raeburn  9524:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9525:         } else {
                   9526:             return ('write error',$result);
                   9527:         }
                   9528:         if ($deloutcome eq 'ok') {
                   9529:             return 'ok';
                   9530:         } else {
                   9531:             return ('delete error',$deloutcome);
                   9532:         }
                   9533:     }
                   9534: }
                   9535: 
1.679     raeburn  9536: sub modify_group_roles {
1.957     raeburn  9537:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9538:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9539:     my $role = 'gr/'.&escape($userprivs);
                   9540:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9541:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9542:     if ($result eq 'ok') {
                   9543:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9544:     }
1.679     raeburn  9545:     return $result;
                   9546: }
                   9547: 
                   9548: sub modify_coursegroup_membership {
                   9549:     my ($cdom,$cnum,$membership) = @_;
                   9550:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9551:     return $result;
                   9552: }
                   9553: 
1.682     raeburn  9554: sub get_active_groups {
                   9555:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9556:     my $now = time;
                   9557:     my %groups = ();
                   9558:     foreach my $key (keys(%env)) {
1.811     albertel 9559:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9560:             my ($start,$end) = split(/\./,$env{$key});
                   9561:             if (($end!=0) && ($end<$now)) { next; }
                   9562:             if (($start!=0) && ($start>$now)) { next; }
                   9563:             if ($1 eq $cdom && $2 eq $cnum) {
                   9564:                 $groups{$3} = $env{$key} ;
                   9565:             }
                   9566:         }
                   9567:     }
                   9568:     return %groups;
                   9569: }
                   9570: 
1.683     raeburn  9571: sub get_group_membership {
                   9572:     my ($cdom,$cnum,$group) = @_;
                   9573:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9574: }
                   9575: 
                   9576: sub get_users_groups {
                   9577:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9578:     my @usersgroups;
1.683     raeburn  9579:     my $cachetime=1800;
                   9580: 
                   9581:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9582:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9583:     if (defined($cached)) {
1.734     albertel 9584:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9585:     } else {  
                   9586:         $grouplist = '';
1.816     raeburn  9587:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9588:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9589:         my $access_end = $env{'course.'.$courseid.
                   9590:                               '.default_enrollment_end_date'};
                   9591:         my $now = time;
                   9592:         foreach my $key (keys(%roleshash)) {
                   9593:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9594:                 my $group = $1;
                   9595:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9596:                     my $start = $2;
                   9597:                     my $end = $1;
                   9598:                     if ($start == -1) { next; } # deleted from group
                   9599:                     if (($start!=0) && ($start>$now)) { next; }
                   9600:                     if (($end!=0) && ($end<$now)) {
                   9601:                         if ($access_end && $access_end < $now) {
                   9602:                             if ($access_end - $end < 86400) {
                   9603:                                 push(@usersgroups,$group);
1.733     raeburn  9604:                             }
                   9605:                         }
1.817     raeburn  9606:                         next;
1.733     raeburn  9607:                     }
1.817     raeburn  9608:                     push(@usersgroups,$group);
1.683     raeburn  9609:                 }
                   9610:             }
                   9611:         }
1.817     raeburn  9612:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9613:         $grouplist = join(':',@usersgroups);
                   9614:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9615:     }
1.733     raeburn  9616:     return @usersgroups;
1.683     raeburn  9617: }
                   9618: 
                   9619: sub devalidate_getgroups_cache {
                   9620:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9621:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9622: 
1.683     raeburn  9623:     my $hashid="$udom:$uname:$courseid";
                   9624:     &devalidate_cache_new('getgroups',$hashid);
                   9625: }
                   9626: 
1.12      www      9627: # ------------------------------------------------------------------ Plain Text
                   9628: 
                   9629: sub plaintext {
1.988     raeburn  9630:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9631:     if ($short =~ m{^cr/}) {
1.758     albertel 9632: 	return (split('/',$short))[-1];
                   9633:     }
1.742     raeburn  9634:     if (!defined($cid)) {
                   9635:         $cid = $env{'request.course.id'};
                   9636:     }
                   9637:     my %rolenames = (
1.1008    raeburn  9638:                       Course    => 'std',
                   9639:                       Community => 'alt1',
1.1305    raeburn  9640:                       Placement => 'std',
1.742     raeburn  9641:                     );
1.1037    raeburn  9642:     if ($cid ne '') {
                   9643:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9644:             unless ($forcedefault) {
                   9645:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9646:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9647:                 return &Apache::lonlocal::mt($roletext);
                   9648:             }
                   9649:         }
                   9650:     }
                   9651:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9652:         (defined($rolenames{$type})) && 
                   9653:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9654:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9655:     } elsif ($cid ne '') {
                   9656:         my $crstype = $env{'course.'.$cid.'.type'};
                   9657:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9658:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9659:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9660:         }
1.742     raeburn  9661:     }
1.1037    raeburn  9662:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9663: }
                   9664: 
                   9665: # ----------------------------------------------------------------- Assign Role
                   9666: 
                   9667: sub assignrole {
1.957     raeburn  9668:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9669:         $context)=@_;
1.21      www      9670:     my $mrole;
                   9671:     if ($role =~ /^cr\//) {
1.393     www      9672:         my $cwosec=$url;
1.811     albertel 9673:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9674: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9675:            my $refused = 1;
                   9676:            if ($context eq 'requestcourses') {
                   9677:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9678:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9679:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9680:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9681:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9682:                            if ($crsenv{'internal.courseowner'} eq
                   9683:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9684:                                $refused = '';
                   9685:                            }
                   9686:                        }
                   9687:                    }
                   9688:                }
                   9689:            }
                   9690:            if ($refused) {
                   9691:                &logthis('Refused custom assignrole: '.
                   9692:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9693:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9694:                return 'refused';
                   9695:            }
1.104     www      9696:         }
1.21      www      9697:         $mrole='cr';
1.678     raeburn  9698:     } elsif ($role =~ /^gr\//) {
                   9699:         my $cwogrp=$url;
1.811     albertel 9700:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9701:         unless (&allowed('mdg',$cwogrp)) {
                   9702:             &logthis('Refused group assignrole: '.
                   9703:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9704:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9705:             return 'refused';
                   9706:         }
                   9707:         $mrole='gr';
1.21      www      9708:     } else {
1.82      www      9709:         my $cwosec=$url;
1.811     albertel 9710:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9711:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9712:             my $refused;
                   9713:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9714:                 if (!(&allowed('c'.$role,$url))) {
                   9715:                     $refused = 1;
                   9716:                 }
                   9717:             } else {
                   9718:                 $refused = 1;
                   9719:             }
1.947     raeburn  9720:             if ($refused) {
1.1045    raeburn  9721:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377    raeburn  9722:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  9723:                     my %crsenv;
                   9724:                     if ($role eq 'cc' || $role eq 'co') {
                   9725:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9726:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9727:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9728:                                 if ($crsenv{'internal.courseowner'} eq 
                   9729:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9730:                                     $refused = '';
                   9731:                                 }
                   9732:                             }
                   9733:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9734:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9735:                                 if ($crsenv{'internal.courseowner'} eq 
                   9736:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9737:                                     $refused = '';
                   9738:                                 }
                   9739:                             }
                   9740:                         }
                   9741:                     }
1.1368    raeburn  9742:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   9743:                     if ($role eq 'st') {
                   9744:                         $refused = '';
1.1377    raeburn  9745:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  9746:                         $refused = '';
                   9747:                     }
1.1017    raeburn  9748:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9749:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9750:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9751:                         my $wrongcc;
                   9752:                         if ($cnum =~ /^$match_community$/) {
                   9753:                             $wrongcc = 1 if ($role eq 'cc');
                   9754:                         } else {
                   9755:                             $wrongcc = 1 if ($role eq 'co');
                   9756:                         }
                   9757:                         unless ($wrongcc) {
                   9758:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9759:                             if ($crsenv{'internal.courseowner'} eq 
                   9760:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9761:                                 $refused = '';
                   9762:                             }
1.1017    raeburn  9763:                         }
                   9764:                     }
1.1183    raeburn  9765:                 } elsif ($context eq 'requestauthor') {
                   9766:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   9767:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9768:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9769:                             $refused = '';
                   9770:                         } else {
                   9771:                             my %domdefaults = &get_domain_defaults($udom);
                   9772:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9773:                                 my $checkbystatus;
                   9774:                                 if ($env{'user.adv'}) { 
                   9775:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9776:                                     if ($disposition eq 'automatic') {
                   9777:                                         $refused = '';
                   9778:                                     } elsif ($disposition eq '') {
                   9779:                                         $checkbystatus = 1;
                   9780:                                     } 
                   9781:                                 } else {
                   9782:                                     $checkbystatus = 1;
                   9783:                                 }
                   9784:                                 if ($checkbystatus) {
                   9785:                                     if ($env{'environment.inststatus'}) {
                   9786:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9787:                                         foreach my $type (@inststatuses) {
                   9788:                                             if (($type ne '') &&
                   9789:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9790:                                                 $refused = '';
                   9791:                                             }
                   9792:                                         }
                   9793:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9794:                                         $refused = '';
                   9795:                                     }
                   9796:                                 }
                   9797:                             }
                   9798:                         }
                   9799:                     }
1.1017    raeburn  9800:                 }
                   9801:                 if ($refused) {
1.947     raeburn  9802:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9803:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9804: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9805:                     return 'refused';
                   9806:                 }
1.932     raeburn  9807:             }
1.1131    raeburn  9808:         } elsif ($role eq 'au') {
                   9809:             if ($url ne '/'.$udom.'/') {
                   9810:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9811:                          ' to assign author role for '.$uname.':'.$udom.
                   9812:                          ' in domain: '.$url.' refused (wrong domain).');
                   9813:                 return 'refused';
                   9814:             }
1.104     www      9815:         }
1.21      www      9816:         $mrole=$role;
                   9817:     }
1.620     albertel 9818:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9819:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9820:     if ($end) { $command.='_'.$end; }
1.21      www      9821:     if ($start) {
                   9822: 	if ($end) { 
1.81      www      9823:            $command.='_'.$start; 
1.21      www      9824:         } else {
1.81      www      9825:            $command.='_0_'.$start;
1.21      www      9826:         }
                   9827:     }
1.739     raeburn  9828:     my $origstart = $start;
                   9829:     my $origend = $end;
1.957     raeburn  9830:     my $delflag;
1.357     www      9831: # actually delete
                   9832:     if ($deleteflag) {
1.373     www      9833: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9834: # modify command to delete the role
1.620     albertel 9835:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9836:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9837: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9838: # set start and finish to negative values for userrolelog
                   9839:            $start=-1;
                   9840:            $end=-1;
1.957     raeburn  9841:            $delflag = 1;
1.357     www      9842:         }
                   9843:     }
                   9844: # send command
1.349     www      9845:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9846: # log new user role if status is ok
1.349     www      9847:     if ($answer eq 'ok') {
1.663     raeburn  9848: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  9849:         if (($role eq 'cc') || ($role eq 'in') ||
                   9850:             ($role eq 'ep') || ($role eq 'ad') ||
                   9851:             ($role eq 'ta') || ($role eq 'st') ||
                   9852:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9853:             ($role eq 'co')) {
1.1200    raeburn  9854: # for course roles, perform group memberships changes triggered by role change.
                   9855:             unless ($role =~ /^gr/) {
                   9856:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9857:                                                  $origstart,$selfenroll,$context);
                   9858:             }
1.1184    raeburn  9859:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9860:                            $selfenroll,$context);
                   9861:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  9862:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9863:                  ($role eq 'da')) {
1.1184    raeburn  9864:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9865:                            $context);
                   9866:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9867:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9868:                              $context); 
                   9869:         }
1.1053    raeburn  9870:         if ($role eq 'cc') {
                   9871:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9872:         }
1.349     www      9873:     }
                   9874:     return $answer;
1.169     harris41 9875: }
                   9876: 
1.1053    raeburn  9877: sub autoupdate_coowners {
                   9878:     my ($url,$end,$start,$uname,$udom) = @_;
                   9879:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9880:     if (($cdom ne '') && ($cnum ne '')) {
                   9881:         my $now = time;
                   9882:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9883:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9884:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9885:             my $instcode = $coursehash{'internal.coursecode'};
                   9886:             if ($instcode ne '') {
1.1056    raeburn  9887:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9888:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9889:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9890:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9891:                         if ($result eq 'valid') {
                   9892:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9893:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9894:                                     push(@newcoowners,$coowner);
                   9895:                                 }
                   9896:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9897:                                     push(@newcoowners,$uname.':'.$udom);
                   9898:                                 }
                   9899:                                 @newcoowners = sort(@newcoowners);
                   9900:                             } else {
                   9901:                                 push(@newcoowners,$uname.':'.$udom);
                   9902:                             }
                   9903:                         } else {
                   9904:                             if ($coursehash{'internal.co-owners'}) {
                   9905:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9906:                                     unless ($coowner eq $uname.':'.$udom) {
                   9907:                                         push(@newcoowners,$coowner);
                   9908:                                     }
                   9909:                                 }
                   9910:                                 unless (@newcoowners > 0) {
                   9911:                                     $delcoowners = 1;
                   9912:                                     $coowners = '';
                   9913:                                 }
                   9914:                             }
                   9915:                         }
                   9916:                         if (@newcoowners || $delcoowners) {
                   9917:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9918:                                             $delcoowners,@newcoowners);
                   9919:                         }
                   9920:                     }
                   9921:                 }
                   9922:             }
                   9923:         }
                   9924:     }
                   9925: }
                   9926: 
                   9927: sub store_coowners {
                   9928:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9929:     my $cid = $cdom.'_'.$cnum;
                   9930:     my ($coowners,$delresult,$putresult);
                   9931:     if (@newcoowners) {
                   9932:         $coowners = join(',',@newcoowners);
                   9933:         my %coownershash = (
                   9934:                             'internal.co-owners' => $coowners,
                   9935:                            );
                   9936:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9937:         if ($putresult eq 'ok') {
                   9938:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9939:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9940:             }
                   9941:         }
                   9942:     }
                   9943:     if ($delcoowners) {
                   9944:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9945:         if ($delresult eq 'ok') {
                   9946:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9947:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9948:             }
                   9949:         }
                   9950:     }
                   9951:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9952:         my %crsinfo =
                   9953:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9954:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9955:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9956:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9957:         }
                   9958:     }
                   9959: }
                   9960: 
1.169     harris41 9961: # -------------------------------------------------- Modify user authentication
1.197     www      9962: # Overrides without validation
                   9963: 
1.169     harris41 9964: sub modifyuserauth {
                   9965:     my ($udom,$uname,$umode,$upass)=@_;
                   9966:     my $uhome=&homeserver($uname,$udom);
1.197     www      9967:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9968:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9969:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9970:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9971:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9972: 		     &escape($upass),$uhome);
1.620     albertel 9973:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9974:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9975:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9976:     &log($udom,,$uname,$uhome,
1.620     albertel 9977:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9978:                                      $env{'user.name'}.', '.$umode.
1.197     www      9979:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9980:     unless ($reply eq 'ok') {
1.197     www      9981:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9982: 	return 'error: '.$reply;
                   9983:     }   
1.170     harris41 9984:     return 'ok';
1.80      www      9985: }
                   9986: 
1.81      www      9987: # --------------------------------------------------------------- Modify a user
1.80      www      9988: 
1.81      www      9989: sub modifyuser {
1.206     matthew  9990:     my ($udom,    $uname, $uid,
                   9991:         $umode,   $upass, $first,
                   9992:         $middle,  $last,  $gene,
1.1058    raeburn  9993:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9994:     $udom= &LONCAPA::clean_domain($udom);
                   9995:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9996:     my $showcandelete = 'none';
                   9997:     if (ref($candelete) eq 'ARRAY') {
                   9998:         if (@{$candelete} > 0) {
                   9999:             $showcandelete = join(', ',@{$candelete});
                   10000:         }
                   10001:     }
1.81      www      10002:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10003:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10004: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10005:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10006:                                      ' desiredhome not specified'). 
1.620     albertel 10007:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10008:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10009:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10010:     my $newuser;
                   10011:     if ($uhome eq 'no_host') {
                   10012:         $newuser = 1;
1.1368    raeburn  10013:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   10014:                 ($umode eq 'lti')) {
                   10015:             return 'error: more information needed to create new user';
                   10016:         }
1.1075    raeburn  10017:     }
1.80      www      10018: # ----------------------------------------------------------------- Create User
1.406     albertel 10019:     if (($uhome eq 'no_host') && 
1.1368    raeburn  10020: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      10021:         my $unhome='';
1.844     albertel 10022:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10023:             $unhome = $desiredhome;
1.620     albertel 10024: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10025: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10026:         } else { # load balancing routine for determining $unhome
1.81      www      10027:             my $loadm=10000000;
1.841     albertel 10028: 	    my %servers = &get_servers($udom,'library');
                   10029: 	    foreach my $tryserver (keys(%servers)) {
                   10030: 		my $answer=reply('load',$tryserver);
                   10031: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10032: 		    $loadm=$answer;
                   10033: 		    $unhome=$tryserver;
                   10034: 		}
1.80      www      10035: 	    }
                   10036:         }
                   10037:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10038: 	    return 'error: unable to find a home server for '.$uname.
                   10039:                    ' in domain '.$udom;
1.80      www      10040:         }
                   10041:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10042:                          &escape($upass),$unhome);
                   10043: 	unless ($reply eq 'ok') {
                   10044:             return 'error: '.$reply;
                   10045:         }   
1.230     stredwic 10046:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10047:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10048: 	    return 'error: unable verify users home machine.';
1.80      www      10049:         }
1.209     matthew  10050:     }   # End of creation of new user
1.80      www      10051: # ---------------------------------------------------------------------- Add ID
                   10052:     if ($uid) {
                   10053:        $uid=~tr/A-Z/a-z/;
                   10054:        my %uidhash=&idrget($udom,$uname);
1.196     www      10055:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10056:          && (!$forceid)) {
1.80      www      10057: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10058: 	      return 'error: user id "'.$uid.'" does not match '.
                   10059:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10060:           }
                   10061:        } else {
1.1300    raeburn  10062: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      10063:        }
                   10064:     }
                   10065: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10066:     my @tmp=&get('environment',
1.899     raeburn  10067: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10068:                     'permanentemail','inststatus'],
1.134     albertel 10069: 		   $udom,$uname);
1.1075    raeburn  10070:     my (%names,%oldnames);
1.313     matthew  10071:     if ($tmp[0] =~ m/^error:.*/) { 
                   10072:         %names=(); 
                   10073:     } else {
                   10074:         %names = @tmp;
1.1075    raeburn  10075:         %oldnames = %names;
1.313     matthew  10076:     }
1.388     www      10077: #
1.1058    raeburn  10078: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10079: # of users did not contain them), do not overwrite existing values
                   10080: # unless field is in $candelete array ref.  
                   10081: #
                   10082: 
                   10083:     my @fields = ('firstname','middlename','lastname','generation',
                   10084:                   'permanentemail','id');
                   10085:     my %newvalues;
                   10086:     if (ref($candelete) eq 'ARRAY') {
                   10087:         foreach my $field (@fields) {
                   10088:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10089:                 if ($field eq 'firstname') {
                   10090:                     $names{$field} = $first;
                   10091:                 } elsif ($field eq 'middlename') {
                   10092:                     $names{$field} = $middle;
                   10093:                 } elsif ($field eq 'lastname') {
                   10094:                     $names{$field} = $last;
                   10095:                 } elsif ($field eq 'generation') { 
                   10096:                     $names{$field} = $gene;
                   10097:                 } elsif ($field eq 'permanentemail') {
                   10098:                     $names{$field} = $email;
                   10099:                 } elsif ($field eq 'id') {
                   10100:                     $names{$field}  = $uid;
                   10101:                 }
                   10102:             }
                   10103:         }
                   10104:     }
1.388     www      10105:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10106:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10107:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10108:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10109:     if ($email) {
                   10110:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10111:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10112:     }
1.899     raeburn  10113:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10114:     if (defined($inststatus)) {
                   10115:         $names{'inststatus'} = '';
                   10116:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10117:         if (ref($usertypes) eq 'HASH') {
                   10118:             my @okstatuses; 
                   10119:             foreach my $item (split(/:/,$inststatus)) {
                   10120:                 if (defined($usertypes->{$item})) {
                   10121:                     push(@okstatuses,$item);  
                   10122:                 }
                   10123:             }
                   10124:             if (@okstatuses) {
                   10125:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10126:             }
                   10127:         }
                   10128:     }
1.1075    raeburn  10129:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10130:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10131:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10132:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10133:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10134:     } else {
                   10135:         $logmsg .= ' during self creation';
                   10136:     }
1.1075    raeburn  10137:     my $changed;
                   10138:     if ($newuser) {
                   10139:         $changed = 1;
                   10140:     } else {
                   10141:         foreach my $field (@fields) {
                   10142:             if ($names{$field} ne $oldnames{$field}) {
                   10143:                 $changed = 1;
                   10144:                 last;
                   10145:             }
                   10146:         }
                   10147:     }
                   10148:     unless ($changed) {
                   10149:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10150:         &logthis($logmsg);
                   10151:         return 'ok';
                   10152:     }
                   10153:     my $reply = &put('environment', \%names, $udom,$uname);
                   10154:     if ($reply ne 'ok') { 
                   10155:         return 'error: '.$reply;
                   10156:     }
1.1087    raeburn  10157:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10158:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10159:     }
1.1075    raeburn  10160:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10161:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10162:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10163:     &logthis($logmsg);
1.134     albertel 10164:     return 'ok';
1.80      www      10165: }
                   10166: 
1.81      www      10167: # -------------------------------------------------------------- Modify student
1.80      www      10168: 
1.81      www      10169: sub modifystudent {
                   10170:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10171:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  10172:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10173:     if (!$cid) {
1.620     albertel 10174: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10175: 	    return 'not_in_class';
                   10176: 	}
1.80      www      10177:     }
                   10178: # --------------------------------------------------------------- Make the user
1.81      www      10179:     my $reply=&modifyuser
1.209     matthew  10180: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10181:          $desiredhome,$email,$inststatus);
1.80      www      10182:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10183:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  10184:     # student's environment
1.297     matthew  10185:     $uid = undef if (!$forceid);
1.455     albertel 10186:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  10187:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  10188:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10189:     return $reply;
                   10190: }
                   10191: 
                   10192: sub modify_student_enrollment {
1.1216    raeburn  10193:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  10194:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10195:     my ($cdom,$cnum,$chome);
                   10196:     if (!$cid) {
1.620     albertel 10197: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10198: 	    return 'not_in_class';
                   10199: 	}
1.620     albertel 10200: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10201: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10202:     } else {
                   10203: 	($cdom,$cnum)=split(/_/,$cid);
                   10204:     }
1.620     albertel 10205:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10206:     if (!$chome) {
1.457     raeburn  10207: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10208:     }
1.455     albertel 10209:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10210:     # Make sure the user exists
1.81      www      10211:     my $uhome=&homeserver($uname,$udom);
                   10212:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10213: 	return 'error: no such user';
                   10214:     }
1.297     matthew  10215:     # Get student data if we were not given enough information
                   10216:     if (!defined($first)  || $first  eq '' || 
                   10217:         !defined($last)   || $last   eq '' || 
                   10218:         !defined($uid)    || $uid    eq '' || 
                   10219:         !defined($middle) || $middle eq '' || 
                   10220:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10221:         # They did not supply us with enough data to enroll the student, so
                   10222:         # we need to pick up more information.
1.297     matthew  10223:         my %tmp = &get('environment',
1.294     matthew  10224:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10225:                        ,$udom,$uname);
                   10226: 
1.800     albertel 10227:         #foreach my $key (keys(%tmp)) {
                   10228:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10229:         #}
1.294     matthew  10230:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10231:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10232:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10233:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10234:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10235:     }
1.556     albertel 10236:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10237:     my $user = "$uname:$udom";
                   10238:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10239:     my $reply=cput('classlist',
1.1148    raeburn  10240: 		   {$user => 
1.1314    raeburn  10241: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10242: 		   $cdom,$cnum);
1.1148    raeburn  10243:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10244:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10245:     } else { 
1.81      www      10246: 	return 'error: '.$reply;
                   10247:     }
1.297     matthew  10248:     # Add student role to user
1.83      www      10249:     my $uurl='/'.$cid;
1.81      www      10250:     $uurl=~s/\_/\//g;
                   10251:     if ($usec) {
                   10252: 	$uurl.='/'.$usec;
                   10253:     }
1.1148    raeburn  10254:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10255:                              $selfenroll,$context);
                   10256:     if ($result ne 'ok') {
                   10257:         if ($old_entry{$user} ne '') {
                   10258:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10259:         } else {
                   10260:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10261:         }
                   10262:     }
                   10263:     return $result; 
1.21      www      10264: }
                   10265: 
1.556     albertel 10266: sub format_name {
                   10267:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10268:     my $name;
                   10269:     if ($first ne 'lastname') {
                   10270: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10271:     } else {
                   10272: 	if ($lastname=~/\S/) {
                   10273: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10274: 	    $name=~s/\s+,/,/;
                   10275: 	} else {
                   10276: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10277: 	}
                   10278:     }
                   10279:     $name=~s/^\s+//;
                   10280:     $name=~s/\s+$//;
                   10281:     $name=~s/\s+/ /g;
                   10282:     return $name;
                   10283: }
                   10284: 
1.84      www      10285: # ------------------------------------------------- Write to course preferences
                   10286: 
                   10287: sub writecoursepref {
                   10288:     my ($courseid,%prefs)=@_;
                   10289:     $courseid=~s/^\///;
                   10290:     $courseid=~s/\_/\//g;
                   10291:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10292:     my $chome=homeserver($cnum,$cdomain);
                   10293:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10294: 	return 'error: no such course';
                   10295:     }
                   10296:     my $cstring='';
1.800     albertel 10297:     foreach my $pref (keys(%prefs)) {
                   10298: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10299:     }
1.84      www      10300:     $cstring=~s/\&$//;
                   10301:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10302: }
                   10303: 
                   10304: # ---------------------------------------------------------- Make/modify course
                   10305: 
                   10306: sub createcourse {
1.741     raeburn  10307:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10308:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10309:     $url=&declutter($url);
                   10310:     my $cid='';
1.1028    raeburn  10311:     if ($context eq 'requestcourses') {
                   10312:         my $can_create = 0;
                   10313:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10314:         if ($udom eq $ownerdom) {
                   10315:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10316:                                   $context)) {
                   10317:                 $can_create = 1;
                   10318:             }
                   10319:         } else {
                   10320:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10321:                                            $category);
                   10322:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10323:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10324:                 if (@curr > 0) {
                   10325:                     my @options = qw(approval validate autolimit);
                   10326:                     my $optregex = join('|',@options);
                   10327:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10328:                         $can_create = 1;
                   10329:                     }
                   10330:                 }
                   10331:             }
                   10332:         }
                   10333:         if ($can_create) {
                   10334:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10335:                 unless (&allowed('ccc',$udom)) {
                   10336:                     return 'refused'; 
                   10337:                 }
1.1017    raeburn  10338:             }
                   10339:         } else {
                   10340:             return 'refused';
                   10341:         }
1.1028    raeburn  10342:     } elsif (!&allowed('ccc',$udom)) {
                   10343:         return 'refused';
1.84      www      10344:     }
1.1011    raeburn  10345: # --------------------------------------------------------------- Get Unique ID
                   10346:     my $uname;
                   10347:     if ($cnum =~ /^$match_courseid$/) {
                   10348:         my $chome=&homeserver($cnum,$udom,'true');
                   10349:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10350:             $uname = $cnum;
                   10351:         } else {
1.1038    raeburn  10352:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10353:         }
                   10354:     } else {
1.1038    raeburn  10355:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10356:     }
                   10357:     return $uname if ($uname =~ /^error/);
                   10358: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10359:     if (!defined($course_server)) {
                   10360:         if (defined(&domain($udom,'primary'))) {
                   10361:             $course_server = &domain($udom,'primary');
                   10362:         } else {
                   10363:             $course_server = $env{'user.home'}; 
                   10364:         }
                   10365:     }
                   10366:     my %host_servers =
                   10367:         &Apache::lonnet::get_servers($udom,'library');
                   10368:     unless ($host_servers{$course_server}) {
                   10369:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10370:     }
1.84      www      10371: # ------------------------------------------------------------- Make the course
                   10372:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10373:                       $course_server);
1.84      www      10374:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10375:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10376:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10377: 	return 'error: no such course';
                   10378:     }
1.271     www      10379: # ----------------------------------------------------------------- Course made
1.516     raeburn  10380: # log existence
1.1029    raeburn  10381:     my $now = time;
1.918     raeburn  10382:     my $newcourse = {
                   10383:                     $udom.'_'.$uname => {
1.921     raeburn  10384:                                      description => $description,
                   10385:                                      inst_code   => $inst_code,
                   10386:                                      owner       => $course_owner,
                   10387:                                      type        => $crstype,
1.1029    raeburn  10388:                                      creator     => $env{'user.name'}.':'.
                   10389:                                                     $env{'user.domain'},
                   10390:                                      created     => $now,
                   10391:                                      context     => $context,
1.918     raeburn  10392:                                                 },
                   10393:                     };
1.921     raeburn  10394:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10395: # set toplevel url
1.271     www      10396:     my $topurl=$url;
                   10397:     unless ($nonstandard) {
                   10398: # ------------------------------------------ For standard courses, make top url
                   10399:         my $mapurl=&clutter($url);
1.278     www      10400:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10401:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10402: <map>
                   10403: <resource id="1" type="start"></resource>
                   10404: <resource id="2" src="$mapurl"></resource>
                   10405: <resource id="3" type="finish"></resource>
                   10406: <link index="1" from="1" to="2"></link>
                   10407: <link index="2" from="2" to="3"></link>
                   10408: </map>
                   10409: ENDINITMAP
                   10410:         $topurl=&declutter(
1.638     albertel 10411:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10412:                           );
                   10413:     }
                   10414: # ----------------------------------------------------------- Write preferences
1.84      www      10415:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10416:                      ('description'              => $description,
                   10417:                       'url'                      => $topurl,
                   10418:                       'internal.creator'         => $env{'user.name'}.':'.
                   10419:                                                     $env{'user.domain'},
                   10420:                       'internal.created'         => $now,
                   10421:                       'internal.creationcontext' => $context)
                   10422:                     );
1.84      www      10423:     return '/'.$udom.'/'.$uname;
                   10424: }
                   10425: 
1.1011    raeburn  10426: # ------------------------------------------------------------------- Create ID
                   10427: sub generate_coursenum {
1.1038    raeburn  10428:     my ($udom,$crstype) = @_;
1.1011    raeburn  10429:     my $domdesc = &domain($udom);
                   10430:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10431:     my $first;
                   10432:     if ($crstype eq 'Community') {
                   10433:         $first = '0';
                   10434:     } else {
                   10435:         $first = int(1+rand(9)); 
                   10436:     } 
                   10437:     my $uname=$first.
1.1011    raeburn  10438:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10439:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10440:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10441: # ----------------------------------------------- Make sure that does not exist
                   10442:     my $uhome=&homeserver($uname,$udom,'true');
                   10443:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10444:         if ($crstype eq 'Community') {
                   10445:             $first = '0';
                   10446:         } else {
                   10447:             $first = int(1+rand(9));
                   10448:         }
                   10449:         $uname=$first.
1.1011    raeburn  10450:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10451:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10452:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10453:         $uhome=&homeserver($uname,$udom,'true');
                   10454:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10455:             return 'error: unable to generate unique course-ID';
                   10456:         }
                   10457:     }
                   10458:     return $uname;
                   10459: }
                   10460: 
1.813     albertel 10461: sub is_course {
1.1167    droeschl 10462:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10463:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   10464: 
1.1381    raeburn  10465:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10466:     my $uhome=&homeserver($cnum,$cdom);
                   10467:     my $iscourse;
                   10468:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  10469:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  10470:     } else {
                   10471:         my $hashid = $cdom.':'.$cnum;
                   10472:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10473:         unless (defined($cached)) {
                   10474:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10475:                                         $cnum,undef,undef,'.');
                   10476:             $iscourse = 0;
                   10477:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10478:                 $iscourse = 1;
                   10479:             }
                   10480:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10481:         }
                   10482:     }
                   10483:     return unless ($iscourse);
1.1167    droeschl 10484:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10485: }
                   10486: 
1.1015    raeburn  10487: sub store_userdata {
                   10488:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10489:     my $result;
1.1016    raeburn  10490:     if ($datakey ne '') {
1.1013    raeburn  10491:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10492:             if ($udom eq '' || $uname eq '') {
                   10493:                 $udom = $env{'user.domain'};
                   10494:                 $uname = $env{'user.name'};
                   10495:             }
                   10496:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10497:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10498:                 $result = 'error: no_host';
                   10499:             } else {
                   10500:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10501:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10502: 
                   10503:                 my $namevalue='';
                   10504:                 foreach my $key (keys(%{$storehash})) {
                   10505:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10506:                 }
                   10507:                 $namevalue=~s/\&$//;
1.1224    raeburn  10508:                 unless ($namespace eq 'courserequests') {
                   10509:                     $datakey = &escape($datakey);
                   10510:                 }
1.1105    raeburn  10511:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10512:                                   $namevalue,$uhome);
1.1013    raeburn  10513:             }
                   10514:         } else {
                   10515:             $result = 'error: data to store was not a hash reference'; 
                   10516:         }
                   10517:     } else {
                   10518:         $result= 'error: invalid requestkey'; 
                   10519:     }
                   10520:     return $result;
                   10521: }
                   10522: 
1.21      www      10523: # ---------------------------------------------------------- Assign Custom Role
                   10524: 
                   10525: sub assigncustomrole {
1.957     raeburn  10526:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10527:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10528:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10529: }
                   10530: 
                   10531: # ----------------------------------------------------------------- Revoke Role
                   10532: 
                   10533: sub revokerole {
1.957     raeburn  10534:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10535:     my $now=time;
1.965     raeburn  10536:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10537: }
                   10538: 
                   10539: # ---------------------------------------------------------- Revoke Custom Role
                   10540: 
                   10541: sub revokecustomrole {
1.957     raeburn  10542:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10543:     my $now=time;
1.357     www      10544:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10545:            $deleteflag,$selfenroll,$context);
1.17      www      10546: }
                   10547: 
1.533     banghart 10548: # ------------------------------------------------------------ Disk usage
1.535     albertel 10549: sub diskusage {
1.955     raeburn  10550:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10551:     $directorypath =~ s/\/$//;
                   10552:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10553:                        .&escape($getpropath).':'.&escape($uname).':'
                   10554:                        .&escape($udom),homeserver($uname,$udom));
                   10555:     if ($listing eq 'unknown_cmd') {
                   10556:         if ($getpropath) {
                   10557:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10558:         }
                   10559:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10560:     }
1.514     albertel 10561:     return $listing;
1.512     banghart 10562: }
                   10563: 
1.566     banghart 10564: sub is_locked {
1.1096    raeburn  10565:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10566:     my @check;
                   10567:     my $is_locked;
1.1093    raeburn  10568:     push (@check,$file_name);
1.613     albertel 10569:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10570: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10571:     my ($tmp)=keys(%locked);
                   10572:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10573:     
1.566     banghart 10574:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10575:         $is_locked = 'false';
                   10576:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10577:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10578:                $is_locked = 'true';
1.1096    raeburn  10579:                if (ref($which) eq 'ARRAY') {
                   10580:                    push(@{$which},$entry);
                   10581:                } else {
                   10582:                    last;
                   10583:                }
1.745     raeburn  10584:            }
                   10585:        }
1.566     banghart 10586:     } else {
                   10587:         $is_locked = 'false';
                   10588:     }
1.1093    raeburn  10589:     return $is_locked;
1.566     banghart 10590: }
                   10591: 
1.759     albertel 10592: sub declutter_portfile {
                   10593:     my ($file) = @_;
1.833     albertel 10594:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10595:     return $file;
                   10596: }
                   10597: 
1.559     banghart 10598: # ------------------------------------------------------------- Mark as Read Only
                   10599: 
                   10600: sub mark_as_readonly {
                   10601:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10602:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10603:     my ($tmp)=keys(%current_permissions);
                   10604:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10605:     foreach my $file (@{$files}) {
1.759     albertel 10606: 	$file = &declutter_portfile($file);
1.561     banghart 10607:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10608:     }
1.613     albertel 10609:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10610:     return;
                   10611: }
                   10612: 
1.572     banghart 10613: # ------------------------------------------------------------Save Selected Files
                   10614: 
                   10615: sub save_selected_files {
                   10616:     my ($user, $path, @files) = @_;
                   10617:     my $filename = $user."savedfiles";
1.573     banghart 10618:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  10619:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10620:     foreach my $file (@files) {
1.620     albertel 10621:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10622:     }
                   10623:     foreach my $file (@other_files) {
1.574     banghart 10624:         print (OUT $file."\n");
1.572     banghart 10625:     }
1.574     banghart 10626:     close (OUT);
1.572     banghart 10627:     return 'ok';
                   10628: }
                   10629: 
1.574     banghart 10630: sub clear_selected_files {
                   10631:     my ($user) = @_;
                   10632:     my $filename = $user."savedfiles";
1.1359    raeburn  10633:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10634:     print (OUT undef);
                   10635:     close (OUT);
                   10636:     return ("ok");    
                   10637: }
                   10638: 
1.572     banghart 10639: sub files_in_path {
                   10640:     my ($user, $path) = @_;
                   10641:     my $filename = $user."savedfiles";
                   10642:     my %return_files;
1.1359    raeburn  10643:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10644:     while (my $line_in = <IN>) {
1.574     banghart 10645:         chomp ($line_in);
                   10646:         my @paths_and_file = split (m!/!, $line_in);
                   10647:         my $file_part = pop (@paths_and_file);
                   10648:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10649:         $path_part.='/';
                   10650:         my $path_and_file = $path_part.$file_part;
                   10651:         if ($path_part eq $path) {
                   10652:             $return_files{$file_part}= 'selected';
                   10653:         }
                   10654:     }
1.574     banghart 10655:     close (IN);
                   10656:     return (\%return_files);
1.572     banghart 10657: }
                   10658: 
                   10659: # called in portfolio select mode, to show files selected NOT in current directory
                   10660: sub files_not_in_path {
                   10661:     my ($user, $path) = @_;
                   10662:     my $filename = $user."savedfiles";
                   10663:     my @return_files;
                   10664:     my $path_part;
1.1359    raeburn  10665:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10666:     while (my $line = <IN>) {
1.572     banghart 10667:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10668:         my @paths_and_file = split(m|/|, $line);
                   10669:         my $file_part = pop(@paths_and_file);
                   10670:         chomp($file_part);
                   10671:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10672:         $path_part .= '/';
                   10673:         my $path_and_file = $path_part.$file_part;
                   10674:         if ($path_part ne $path) {
1.800     albertel 10675:             push(@return_files, ($path_and_file));
1.572     banghart 10676:         }
                   10677:     }
1.800     albertel 10678:     close(OUT);
1.574     banghart 10679:     return (@return_files);
1.572     banghart 10680: }
                   10681: 
1.1273    raeburn  10682: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   10683:  
                   10684: sub portfiles_versioning {
                   10685:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   10686:     my $portfolio_root = '/userfiles/portfolio';
                   10687:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   10688:     foreach my $file (@{$portfiles}) {
                   10689:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   10690:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   10691:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   10692:         my $getpropath = 1;
                   10693:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   10694:                                              $stu_name,$getpropath);
                   10695:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   10696:         my $new_answer = 
                   10697:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   10698:         if ($new_answer ne 'problem getting file') {
                   10699:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   10700:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   10701:                               [$symb,$env{'request.course.id'},'graded']);
                   10702:         }
                   10703:     }
                   10704: }
                   10705: 
                   10706: sub get_next_version {
                   10707:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   10708:     my $version;
                   10709:     if (ref($dir_list) eq 'ARRAY') {
                   10710:         foreach my $row (@{$dir_list}) {
                   10711:             my ($file) = split(/\&/,$row,2);
                   10712:             my ($file_name,$file_version,$file_ext) =
                   10713:                 &file_name_version_ext($file);
                   10714:             if (($file_name eq $answer_name) &&
                   10715:                 ($file_ext eq $answer_ext)) {
                   10716:                      # gets here if filename and extension match,
                   10717:                      # regardless of version
                   10718:                 if ($file_version ne '') {
                   10719:                     # a versioned file is found  so save it for later
                   10720:                     if ($file_version > $version) {
                   10721:                         $version = $file_version;
                   10722:                     }
                   10723:                 }
                   10724:             }
                   10725:         }
                   10726:     }
                   10727:     $version ++;
                   10728:     return($version);
                   10729: }
                   10730: 
                   10731: sub version_selected_portfile {
                   10732:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   10733:     my ($answer_name,$answer_ver,$answer_ext) =
                   10734:         &file_name_version_ext($file_name);
                   10735:     my $new_answer;
                   10736:     $env{'form.copy'} =
                   10737:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   10738:     if($env{'form.copy'} eq '-1') {
                   10739:         $new_answer = 'problem getting file';
                   10740:     } else {
                   10741:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   10742:         my $copy_result = 
                   10743:             &finishuserfileupload($stu_name,$domain,'copy',
                   10744:                                   '/portfolio'.$directory.$new_answer);
                   10745:     }
                   10746:     undef($env{'form.copy'});
                   10747:     return ($new_answer);
                   10748: }
                   10749: 
                   10750: sub file_name_version_ext {
                   10751:     my ($file)=@_;
                   10752:     my @file_parts = split(/\./, $file);
                   10753:     my ($name,$version,$ext);
                   10754:     if (@file_parts > 1) {
                   10755:         $ext=pop(@file_parts);
                   10756:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   10757:             $version=pop(@file_parts);
                   10758:         }
                   10759:         $name=join('.',@file_parts);
                   10760:     } else {
                   10761:         $name=join('.',@file_parts);
                   10762:     }
                   10763:     return($name,$version,$ext);
                   10764: }
                   10765: 
1.745     raeburn  10766: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10767: 
1.745     raeburn  10768: sub get_portfile_permissions {
                   10769:     my ($domain,$user) = @_;
1.613     albertel 10770:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10771:     my ($tmp)=keys(%current_permissions);
                   10772:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10773:     return \%current_permissions;
                   10774: }
                   10775: 
                   10776: #---------------------------------------------Get portfolio file access controls
                   10777: 
1.749     raeburn  10778: sub get_access_controls {
1.745     raeburn  10779:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10780:     my %access;
                   10781:     my $real_file = $file;
                   10782:     $file =~ s/\.meta$//;
1.745     raeburn  10783:     if (defined($file)) {
1.749     raeburn  10784:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10785:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10786:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10787:             }
                   10788:         }
1.745     raeburn  10789:     } else {
1.749     raeburn  10790:         foreach my $key (keys(%{$current_permissions})) {
                   10791:             if ($key =~ /\0accesscontrol$/) {
                   10792:                 if (defined($group)) {
                   10793:                     if ($key !~ m-^\Q$group\E/-) {
                   10794:                         next;
                   10795:                     }
                   10796:                 }
                   10797:                 my ($fullpath) = split(/\0/,$key);
                   10798:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10799:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10800:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10801:                     }
                   10802:                 }
                   10803:             }
                   10804:         }
                   10805:     }
                   10806:     return %access;
                   10807: }
                   10808: 
                   10809: sub modify_access_controls {
                   10810:     my ($file_name,$changes,$domain,$user)=@_;
                   10811:     my ($outcome,$deloutcome);
                   10812:     my %store_permissions;
                   10813:     my %new_values;
                   10814:     my %new_control;
                   10815:     my %translation;
                   10816:     my @deletions = ();
                   10817:     my $now = time;
                   10818:     if (exists($$changes{'activate'})) {
                   10819:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10820:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10821:             my $numnew = scalar(@newitems);
                   10822:             for (my $i=0; $i<$numnew; $i++) {
                   10823:                 my $newkey = $newitems[$i];
                   10824:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10825:                 if ($newkey =~ /^\d+:/) { 
                   10826:                     $newkey =~ s/^(\d+)/$newid/;
                   10827:                     $translation{$1} = $newid;
                   10828:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10829:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10830:                     $translation{$1} = $newid;
                   10831:                 }
1.749     raeburn  10832:                 $new_values{$file_name."\0".$newkey} = 
                   10833:                                           $$changes{'activate'}{$newitems[$i]};
                   10834:                 $new_control{$newkey} = $now;
                   10835:             }
                   10836:         }
                   10837:     }
                   10838:     my %todelete;
                   10839:     my %changed_items;
                   10840:     foreach my $action ('delete','update') {
                   10841:         if (exists($$changes{$action})) {
                   10842:             if (ref($$changes{$action}) eq 'HASH') {
                   10843:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10844:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10845:                     if ($action eq 'delete') { 
                   10846:                         $todelete{$itemnum} = 1;
                   10847:                     } else {
                   10848:                         $changed_items{$itemnum} = $key;
                   10849:                     }
                   10850:                 }
1.745     raeburn  10851:             }
                   10852:         }
1.749     raeburn  10853:     }
                   10854:     # get lock on access controls for file.
                   10855:     my $lockhash = {
                   10856:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10857:                                                        ':'.$env{'user.domain'},
                   10858:                    }; 
                   10859:     my $tries = 0;
                   10860:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10861:    
1.1288    damieng  10862:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10863:         $tries ++;
1.1289    damieng  10864:         sleep(0.1);
1.749     raeburn  10865:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10866:     }
                   10867:     if ($gotlock eq 'ok') {
                   10868:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10869:         my ($tmp)=keys(%curr_permissions);
                   10870:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10871:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10872:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10873:             if (ref($curr_controls) eq 'HASH') {
                   10874:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10875:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10876:                     if (defined($todelete{$itemnum})) {
                   10877:                         push(@deletions,$file_name."\0".$control_item);
                   10878:                     } else {
                   10879:                         if (defined($changed_items{$itemnum})) {
                   10880:                             $new_control{$changed_items{$itemnum}} = $now;
                   10881:                             push(@deletions,$file_name."\0".$control_item);
                   10882:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10883:                         } else {
                   10884:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10885:                         }
                   10886:                     }
1.745     raeburn  10887:                 }
                   10888:             }
                   10889:         }
1.970     raeburn  10890:         my ($group);
                   10891:         if (&is_course($domain,$user)) {
                   10892:             ($group,my $file) = split(/\//,$file_name,2);
                   10893:         }
1.749     raeburn  10894:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10895:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10896:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10897:         #  remove lock
                   10898:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10899:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10900:         my $sqlresult =
1.970     raeburn  10901:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10902:                                     $group);
1.749     raeburn  10903:     } else {
                   10904:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10905:     }
1.749     raeburn  10906:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10907: }
                   10908: 
1.827     raeburn  10909: sub make_public_indefinitely {
1.1271    raeburn  10910:     my (@requrl) = @_;
                   10911:     return &automated_portfile_access('public',\@requrl);
                   10912: }
                   10913: 
                   10914: sub automated_portfile_access {
                   10915:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  10916:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   10917:         return 'invalid';
                   10918:     }
1.1271    raeburn  10919:     my %urls;
                   10920:     if (ref($addsref) eq 'ARRAY') {
                   10921:         foreach my $requrl (@{$addsref}) {
                   10922:             if (&is_portfolio_url($requrl)) {
                   10923:                 unless (exists($urls{$requrl})) {
                   10924:                     $urls{$requrl} = 'add';
                   10925:                 }
                   10926:             }
                   10927:         }
                   10928:     }
                   10929:     if (ref($delsref) eq 'ARRAY') {
                   10930:         foreach my $requrl (@{$delsref}) { 
                   10931:             if (&is_portfolio_url($requrl)) {
                   10932:                 unless (exists($urls{$requrl})) {
                   10933:                     $urls{$requrl} = 'delete'; 
                   10934:                 }
                   10935:             }
                   10936:         }
                   10937:     }
                   10938:     unless (keys(%urls)) {
                   10939:         return 'invalid';
                   10940:     }
                   10941:     my $ip;
                   10942:     if ($accesstype eq 'ip') {
                   10943:         if (ref($info) eq 'HASH') {
                   10944:             if ($info->{'ip'} ne '') {
                   10945:                 $ip = $info->{'ip'};
                   10946:             }
                   10947:         }
                   10948:         if ($ip eq '') {
                   10949:             return 'invalid';
                   10950:         }
                   10951:     }
                   10952:     my $errors;
1.827     raeburn  10953:     my $now = time;
1.1271    raeburn  10954:     my %current_perms;
                   10955:     foreach my $requrl (sort(keys(%urls))) {
                   10956:         my $action;
                   10957:         if ($urls{$requrl} eq 'add') {
                   10958:             $action = 'activate';
                   10959:         } else {
                   10960:             $action = 'none';
                   10961:         }
                   10962:         my $aclnum = 0;
1.827     raeburn  10963:         my (undef,$udom,$unum,$file_name,$group) =
                   10964:             &parse_portfolio_url($requrl);
1.1271    raeburn  10965:         unless (exists($current_perms{$unum.':'.$udom})) {
                   10966:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   10967:         }
                   10968:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  10969:                                                    $group,$file_name);
                   10970:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10971:             my ($num,$scope,$end,$start) = 
                   10972:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  10973:             if ($scope eq $accesstype) {
                   10974:                 if (($start <= $now) && ($end == 0)) {
                   10975:                     if ($accesstype eq 'ip') {
                   10976:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   10977:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   10978:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   10979:                                     if ($urls{$requrl} eq 'add') {
                   10980:                                         $action = 'none';
                   10981:                                         last;
                   10982:                                     } else {
                   10983:                                         $action = 'delete';
                   10984:                                         $aclnum = $num;
                   10985:                                         last;
                   10986:                                     }
                   10987:                                 }
                   10988:                             }
                   10989:                         }
                   10990:                     } elsif ($accesstype eq 'public') {
                   10991:                         if ($urls{$requrl} eq 'add') {
                   10992:                             $action = 'none';
                   10993:                             last;
                   10994:                         } else {
                   10995:                             $action = 'delete';
                   10996:                             $aclnum = $num;
                   10997:                             last;
                   10998:                         }
                   10999:                     }
                   11000:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  11001:                     $action = 'update';
                   11002:                     $aclnum = $num;
1.1271    raeburn  11003:                     last;
1.827     raeburn  11004:                 }
                   11005:             }
                   11006:         }
                   11007:         if ($action eq 'none') {
1.1271    raeburn  11008:             next;
1.827     raeburn  11009:         } else {
                   11010:             my %changes;
                   11011:             my $newend = 0;
                   11012:             my $newstart = $now;
1.1271    raeburn  11013:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  11014:             $changes{$action}{$newkey} = {
1.1271    raeburn  11015:                 type => $accesstype,
1.827     raeburn  11016:                 time => {
                   11017:                     start => $newstart,
                   11018:                     end   => $newend,
                   11019:                 },
                   11020:             };
1.1271    raeburn  11021:             if ($accesstype eq 'ip') {
                   11022:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   11023:             }
1.827     raeburn  11024:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11025:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  11026:             unless ($outcome eq 'ok') {
                   11027:                 $errors .= $outcome.' ';
                   11028:             }
1.827     raeburn  11029:         }
1.1271    raeburn  11030:     }
                   11031:     if ($errors) {
                   11032:         $errors =~ s/\s$//;
                   11033:         return $errors;
1.827     raeburn  11034:     } else {
1.1271    raeburn  11035:         return 'ok';
1.827     raeburn  11036:     }
                   11037: }
                   11038: 
1.745     raeburn  11039: #------------------------------------------------------Get Marked as Read Only
                   11040: 
                   11041: sub get_marked_as_readonly {
                   11042:     my ($domain,$user,$what,$group) = @_;
                   11043:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11044:     my @readonly_files;
1.629     banghart 11045:     my $cmp1=$what;
                   11046:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11047:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11048:         if (defined($group)) {
                   11049:             if ($file_name !~ m-^\Q$group\E/-) {
                   11050:                 next;
                   11051:             }
                   11052:         }
1.561     banghart 11053:         if (ref($value) eq "ARRAY"){
                   11054:             foreach my $stored_what (@{$value}) {
1.629     banghart 11055:                 my $cmp2=$stored_what;
1.759     albertel 11056:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11057:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11058:                 }
1.629     banghart 11059:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11060:                     push(@readonly_files, $file_name);
1.745     raeburn  11061:                     last;
1.563     banghart 11062:                 } elsif (!defined($what)) {
                   11063:                     push(@readonly_files, $file_name);
1.745     raeburn  11064:                     last;
1.561     banghart 11065:                 }
                   11066:             }
1.745     raeburn  11067:         }
1.561     banghart 11068:     }
                   11069:     return @readonly_files;
                   11070: }
1.577     banghart 11071: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11072: 
1.577     banghart 11073: sub get_marked_as_readonly_hash {
1.745     raeburn  11074:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11075:     my %readonly_files;
1.745     raeburn  11076:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11077:         if (defined($group)) {
                   11078:             if ($file_name !~ m-^\Q$group\E/-) {
                   11079:                 next;
                   11080:             }
                   11081:         }
1.577     banghart 11082:         if (ref($value) eq "ARRAY"){
                   11083:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11084:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11085:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11086:                         if ($lock_descriptor eq 'graded') {
                   11087:                             $readonly_files{$file_name} = 'graded';
                   11088:                         } elsif ($lock_descriptor eq 'handback') {
                   11089:                             $readonly_files{$file_name} = 'handback';
                   11090:                         } else {
                   11091:                             if (!exists($readonly_files{$file_name})) {
                   11092:                                 $readonly_files{$file_name} = 'locked';
                   11093:                             }
                   11094:                         }
1.745     raeburn  11095:                     }
1.750     banghart 11096:                 } 
1.577     banghart 11097:             }
                   11098:         } 
                   11099:     }
                   11100:     return %readonly_files;
                   11101: }
1.559     banghart 11102: # ------------------------------------------------------------ Unmark as Read Only
                   11103: 
                   11104: sub unmark_as_readonly {
1.629     banghart 11105:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11106:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11107:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11108:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11109:     my $symb_crs = $what;
                   11110:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11111:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11112:     my ($tmp)=keys(%current_permissions);
                   11113:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11114:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11115:     foreach my $file (@readonly_files) {
1.759     albertel 11116: 	my $clean_file = &declutter_portfile($file);
                   11117: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11118: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11119:         my @new_locks;
                   11120:         my @del_keys;
                   11121:         if (ref($current_locks) eq "ARRAY"){
                   11122:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11123:                 my $compare=$locker;
1.749     raeburn  11124:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11125:                     $compare=join('',@{$locker});
1.746     raeburn  11126:                     if ($compare ne $symb_crs) {
                   11127:                         push(@new_locks, $locker);
                   11128:                     }
1.563     banghart 11129:                 }
                   11130:             }
1.650     albertel 11131:             if (scalar(@new_locks) > 0) {
1.563     banghart 11132:                 $current_permissions{$file} = \@new_locks;
                   11133:             } else {
                   11134:                 push(@del_keys, $file);
1.613     albertel 11135:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11136:                 delete($current_permissions{$file});
1.563     banghart 11137:             }
                   11138:         }
1.561     banghart 11139:     }
1.613     albertel 11140:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11141:     return;
                   11142: }
1.512     banghart 11143: 
1.17      www      11144: # ------------------------------------------------------------ Directory lister
                   11145: 
                   11146: sub dirlist {
1.955     raeburn  11147:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11148:     $uri=~s/^\///;
                   11149:     $uri=~s/\/$//;
1.253     stredwic 11150:     my ($udom, $uname);
1.955     raeburn  11151:     if ($getuserdir) {
1.253     stredwic 11152:         $udom = $userdomain;
                   11153:         $uname = $username;
1.955     raeburn  11154:     } else {
                   11155:         (undef,$udom,$uname)=split(/\//,$uri);
                   11156:         if(defined($userdomain)) {
                   11157:             $udom = $userdomain;
                   11158:         }
                   11159:         if(defined($username)) {
                   11160:             $uname = $username;
                   11161:         }
1.253     stredwic 11162:     }
1.955     raeburn  11163:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11164: 
1.955     raeburn  11165:     $dirRoot = $perlvar{'lonDocRoot'};
                   11166:     if (defined($getpropath)) {
                   11167:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11168:         $dirRoot =~ s/\/$//;
1.955     raeburn  11169:     } elsif (defined($getuserdir)) {
                   11170:         my $subdir=$uname.'__';
                   11171:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11172:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11173:                    ."/$udom/$subdir/$uname";
                   11174:     } elsif (defined($alternateRoot)) {
                   11175:         $dirRoot = $alternateRoot;
1.751     banghart 11176:     }
1.253     stredwic 11177: 
                   11178:     if($udom) {
                   11179:         if($uname) {
1.1135    raeburn  11180:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11181:             if ($uhome eq 'no_host') {
                   11182:                 return ([],'no_host');
                   11183:             }
1.955     raeburn  11184:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11185:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11186:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11187:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11188:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11189:             } else {
                   11190:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11191:             }
1.605     matthew  11192:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11193:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11194:                 @listing_results = split(/:/,$listing);
                   11195:             } else {
                   11196:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11197:             }
1.1135    raeburn  11198:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11199:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11200:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11201:                 return ([],$listing);
                   11202:             } else {
                   11203:                 return (\@listing_results);
1.1135    raeburn  11204:             }
1.955     raeburn  11205:         } elsif(!$alternateRoot) {
1.1136    raeburn  11206:             my (%allusers,%listerror);
1.841     albertel 11207: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11208:  	    foreach my $tryserver (keys(%servers)) {
                   11209:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11210:                                   &escape($udom),$tryserver);
                   11211:                 if ($listing eq 'unknown_cmd') {
                   11212: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11213: 				      $udom, $tryserver);
                   11214:                 } else {
                   11215:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11216:                 }
1.841     albertel 11217: 		if ($listing eq 'unknown_cmd') {
                   11218: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11219: 				      $udom, $tryserver);
                   11220: 		    @listing_results = split(/:/,$listing);
                   11221: 		} else {
                   11222: 		    @listing_results =
                   11223: 			map { &unescape($_); } split(/:/,$listing);
                   11224: 		}
1.1136    raeburn  11225:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11226:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11227:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11228:                     $listerror{$tryserver} = $listing;
                   11229:                 } else {
1.841     albertel 11230: 		    foreach my $line (@listing_results) {
                   11231: 			my ($entry) = split(/&/,$line,2);
                   11232: 			$allusers{$entry} = 1;
                   11233: 		    }
                   11234: 		}
1.253     stredwic 11235:             }
1.1136    raeburn  11236:             my @alluserslist=();
1.800     albertel 11237:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11238:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11239:             }
1.1318    droeschl 11240: 
                   11241:             if (!%listerror) {
                   11242:                 # no errors
                   11243:                 return (\@alluserslist);
                   11244:             } elsif (scalar(keys(%servers)) == 1) {
                   11245:                 # one library server, one error 
                   11246:                 my ($key) = keys(%listerror);
                   11247:                 return (\@alluserslist, $listerror{$key});
                   11248:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11249:                 # con_lost indicates that we might miss data from at least one
                   11250:                 # library server
                   11251:                 return (\@alluserslist, 'con_lost');
                   11252:             } else {
                   11253:                 # multiple library servers and no con_lost -> data should be
                   11254:                 # complete. 
                   11255:                 return (\@alluserslist);
                   11256:             }
                   11257: 
1.253     stredwic 11258:         } else {
1.1136    raeburn  11259:             return ([],'missing username');
1.253     stredwic 11260:         }
1.955     raeburn  11261:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11262:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11263:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11264:         return (\@all_domains);
1.955     raeburn  11265:     } else {
1.1136    raeburn  11266:         return ([],'missing domain');
1.275     stredwic 11267:     }
                   11268: }
                   11269: 
                   11270: # --------------------------------------------- GetFileTimestamp
                   11271: # This function utilizes dirlist and returns the date stamp for
                   11272: # when it was last modified.  It will also return an error of -1
                   11273: # if an error occurs
                   11274: 
                   11275: sub GetFileTimestamp {
1.955     raeburn  11276:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11277:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11278:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11279:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11280:                                     undef,$getuserdir);
                   11281:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11282:         return -1;
                   11283:     }
                   11284:     if (ref($fileref) eq 'ARRAY') {
                   11285:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11286:         # @stats contains first the filename, then the stat output
                   11287:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11288:     } else {
                   11289:         return -1;
1.253     stredwic 11290:     }
1.26      www      11291: }
                   11292: 
1.712     albertel 11293: sub stat_file {
                   11294:     my ($uri) = @_;
1.787     albertel 11295:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11296: 
1.955     raeburn  11297:     my ($udom,$uname,$file);
1.712     albertel 11298:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11299: 	($udom,$uname,$file) =
1.811     albertel 11300: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11301: 	$file = 'userfiles/'.$file;
                   11302:     }
                   11303:     if ($uri =~ m-^/res/-) {
                   11304: 	($udom,$uname) = 
1.807     albertel 11305: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11306: 	$file = $uri;
                   11307:     }
                   11308: 
                   11309:     if (!$udom || !$uname || !$file) {
                   11310: 	# unable to handle the uri
                   11311: 	return ();
                   11312:     }
1.956     raeburn  11313:     my $getpropath;
                   11314:     if ($file =~ /^userfiles\//) {
                   11315:         $getpropath = 1;
                   11316:     }
1.1136    raeburn  11317:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11318:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11319:         return ();
                   11320:     } else {
                   11321:         if (ref($listref) eq 'ARRAY') {
                   11322:             my @stats = split('&',$listref->[0]);
                   11323: 	    shift(@stats); #filename is first
                   11324: 	    return @stats;
                   11325:         }
1.712     albertel 11326:     }
                   11327:     return ();
                   11328: }
                   11329: 
1.1313    raeburn  11330: # --------------------------------------------------------- recursedirs
                   11331: # Recursive function to traverse either a specific user's Authoring Space
                   11332: # or corresponding Published Resource Space, and populate the hash ref:
                   11333: # $dirhashref with URLs of all directories, and if $filehashref hash
                   11334: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   11335: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   11336: # files in Authoring Space.
                   11337: #
                   11338: # Inputs:
                   11339: #
                   11340: # $is_home - true if current server is home server for user's space
                   11341: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   11342: # $docroot - Document root (i.e., /home/httpd/html
                   11343: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   11344: # $relpath - Current path (relative to top level).
                   11345: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   11346: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   11347: #
                   11348: # Returns: nothing
                   11349: #
                   11350: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   11351: #
                   11352: # Currently used by interface/londocs.pm to create linked select boxes for
                   11353: # directory and filename to import a Course "Author" resource into a course, and
                   11354: # also to create linked select boxes for Authoring Space and Directory to choose
                   11355: # save location for creation of a new "standard" problem from the Course Editor.
                   11356: #
                   11357: 
                   11358: sub recursedirs {
                   11359:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   11360:     return unless (ref($dirhashref) eq 'HASH');
                   11361:     my $currpath = $docroot.$toppath;
                   11362:     if ($relpath) {
                   11363:         $currpath .= "/$relpath";
                   11364:     }
                   11365:     my $savefile;
                   11366:     if (ref($filehashref)) {
                   11367:         $savefile = 1;
                   11368:     }
                   11369:     if ($is_home) {
                   11370:         if (opendir(my $dirh,$currpath)) {
                   11371:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   11372:                 next if ($item eq '');
                   11373:                 if (-d "$currpath/$item") {
                   11374:                     my $newpath;
                   11375:                     if ($relpath) {
                   11376:                         $newpath = "$relpath/$item";
                   11377:                     } else {
                   11378:                         $newpath = $item;
                   11379:                     }
                   11380:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11381:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11382:                 } elsif ($savefile) {
                   11383:                     if ($context eq 'priv') {
                   11384:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11385:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11386:                         }
                   11387:                     } else {
                   11388:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   11389:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   11390:                         }
                   11391:                     }
                   11392:                 }
                   11393:             }
                   11394:             closedir($dirh);
                   11395:         }
                   11396:     } else {
                   11397:         my ($dirlistref,$listerror) =
                   11398:             &dirlist($toppath.$relpath);
                   11399:         my @dir_lines;
                   11400:         my $dirptr=16384;
                   11401:         if (ref($dirlistref) eq 'ARRAY') {
                   11402:             foreach my $dir_line (sort
                   11403:                               {
                   11404:                                   my ($afile)=split('&',$a,2);
                   11405:                                   my ($bfile)=split('&',$b,2);
                   11406:                                   return (lc($afile) cmp lc($bfile));
                   11407:                               } (@{$dirlistref})) {
                   11408:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   11409:                     split(/\&/,$dir_line,16);
                   11410:                 $item =~ s/\s+$//;
                   11411:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   11412:                 if ($dirptr&$testdir) {
                   11413:                     my $newpath;
                   11414:                     if ($relpath) {
                   11415:                         $newpath = "$relpath/$item";
                   11416:                     } else {
                   11417:                         $relpath = '/';
                   11418:                         $newpath = $item;
                   11419:                     }
                   11420:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   11421:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   11422:                 } elsif ($savefile) {
                   11423:                     if ($context eq 'priv') {
                   11424:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   11425:                             $filehashref->{$relpath}{$item} = 1;
                   11426:                         }
                   11427:                     } else {
                   11428:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   11429:                             $filehashref->{$relpath}{$item} = 1;
                   11430:                         }
                   11431:                     }
                   11432:                 }
                   11433:             }
                   11434:         }
                   11435:     }
                   11436:     return;
                   11437: }
                   11438: 
1.26      www      11439: # -------------------------------------------------------- Value of a Condition
                   11440: 
1.713     albertel 11441: # gets the value of a specific preevaluated condition
                   11442: #    stored in the string  $env{user.state.<cid>}
                   11443: # or looks up a condition reference in the bighash and if if hasn't
                   11444: # already been evaluated recurses into docondval to get the value of
                   11445: # the condition, then memoizing it to 
                   11446: #   $env{user.state.<cid>.<condition>}
1.40      www      11447: sub directcondval {
                   11448:     my $number=shift;
1.620     albertel 11449:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11450: 	&Apache::lonuserstate::evalstate();
                   11451:     }
1.713     albertel 11452:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11453: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11454:     } elsif ($number =~ /^_/) {
                   11455: 	my $sub_condition;
                   11456: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11457: 		&GDBM_READER(),0640)) {
                   11458: 	    $sub_condition=$bighash{'conditions'.$number};
                   11459: 	    untie(%bighash);
                   11460: 	}
                   11461: 	my $value = &docondval($sub_condition);
1.949     raeburn  11462: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11463: 	return $value;
                   11464:     }
1.620     albertel 11465:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11466:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11467:     } else {
                   11468:        return 2;
                   11469:     }
                   11470: }
                   11471: 
1.713     albertel 11472: # get the collection of conditions for this resource
1.26      www      11473: sub condval {
                   11474:     my $condidx=shift;
1.54      www      11475:     my $allpathcond='';
1.713     albertel 11476:     foreach my $cond (split(/\|/,$condidx)) {
                   11477: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11478: 	    $allpathcond.=
                   11479: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11480: 	}
1.191     harris41 11481:     }
1.54      www      11482:     $allpathcond=~s/\|$//;
1.713     albertel 11483:     return &docondval($allpathcond);
                   11484: }
                   11485: 
                   11486: #evaluates an expression of conditions
                   11487: sub docondval {
                   11488:     my ($allpathcond) = @_;
                   11489:     my $result=0;
                   11490:     if ($env{'request.course.id'}
                   11491: 	&& defined($allpathcond)) {
                   11492: 	my $operand='|';
                   11493: 	my @stack;
                   11494: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11495: 	    if ($chunk eq '(') {
                   11496: 		push @stack,($operand,$result);
                   11497: 	    } elsif ($chunk eq ')') {
                   11498: 		my $before=pop @stack;
                   11499: 		if (pop @stack eq '&') {
                   11500: 		    $result=$result>$before?$before:$result;
                   11501: 		} else {
                   11502: 		    $result=$result>$before?$result:$before;
                   11503: 		}
                   11504: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11505: 		$operand=$chunk;
                   11506: 	    } else {
                   11507: 		my $new=directcondval($chunk);
                   11508: 		if ($operand eq '&') {
                   11509: 		    $result=$result>$new?$new:$result;
                   11510: 		} else {
                   11511: 		    $result=$result>$new?$result:$new;
                   11512: 		}
                   11513: 	    }
                   11514: 	}
1.26      www      11515:     }
                   11516:     return $result;
1.421     albertel 11517: }
                   11518: 
                   11519: # ---------------------------------------------------- Devalidate courseresdata
                   11520: 
                   11521: sub devalidatecourseresdata {
                   11522:     my ($coursenum,$coursedomain)=@_;
                   11523:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11524:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11525: }
                   11526: 
1.763     www      11527: 
1.200     www      11528: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11529: #
                   11530: #  Parameters:
                   11531: #      $coursenum    - Number of the course.
                   11532: #      $coursedomain - Domain at which the course was created.
                   11533: #  Returns:
                   11534: #     A hash of the course parameters along (I think) with timestamps
                   11535: #     and version info.
1.877     foxr     11536: 
1.624     albertel 11537: sub get_courseresdata {
                   11538:     my ($coursenum,$coursedomain)=@_;
1.200     www      11539:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11540:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11541:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11542:     my %dumpreply;
1.417     albertel 11543:     unless (defined($cached)) {
1.624     albertel 11544: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11545: 	$result=\%dumpreply;
1.251     albertel 11546: 	my ($tmp) = keys(%dumpreply);
                   11547: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11548: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11549: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11550: 	    return $tmp;
1.416     albertel 11551: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11552: 	    $result=undef;
1.599     albertel 11553: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11554: 	}
                   11555:     }
1.624     albertel 11556:     return $result;
                   11557: }
                   11558: 
1.633     albertel 11559: sub devalidateuserresdata {
                   11560:     my ($uname,$udom)=@_;
                   11561:     my $hashid="$udom:$uname";
                   11562:     &devalidate_cache_new('userres',$hashid);
                   11563: }
                   11564: 
1.624     albertel 11565: sub get_userresdata {
                   11566:     my ($uname,$udom)=@_;
                   11567:     #most student don\'t have any data set, check if there is some data
                   11568:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11569: 
                   11570:     my $hashid="$udom:$uname";
                   11571:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11572:     if (!defined($cached)) {
                   11573: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11574: 	$result=\%resourcedata;
                   11575: 	&do_cache_new('userres',$hashid,$result,600);
                   11576:     }
                   11577:     my ($tmp)=keys(%$result);
                   11578:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11579: 	return $result;
                   11580:     }
                   11581:     #error 2 occurs when the .db doesn't exist
                   11582:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  11583:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11584: 	    &logthis("<font color=\"blue\">WARNING:".
                   11585: 		     " Trying to get resource data for ".
                   11586: 		     $uname." at ".$udom.": ".
                   11587: 		     $tmp."</font>");
                   11588:         }
1.624     albertel 11589:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11590: 	#&EXT_cache_set($udom,$uname);
                   11591: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11592: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11593:     }
                   11594:     return $tmp;
                   11595: }
1.879     foxr     11596: #----------------------------------------------- resdata - return resource data
                   11597: #  Purpose:
                   11598: #    Return resource data for either users or for a course.
                   11599: #  Parameters:
                   11600: #     $name      - Course/user name.
                   11601: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  11602: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  11603: #     $mapp      - decluttered URL of enclosing map  
                   11604: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   11605: #     $recurseup - Ref to array of map URLs, starting with map containing
                   11606: #                  $mapp up through hierarchy of nested maps to top level map.  
                   11607: #     $courseid  - CourseID (first part of param identifier).
                   11608: #     $modifier  - Middle part of param identifier.
                   11609: #     $what      - Last part of param identifier.
1.879     foxr     11610: #     @which     - Array of names of resources desired.
                   11611: #  Returns:
                   11612: #     The value of the first reasource in @which that is found in the
                   11613: #     resource hash.
                   11614: #  Exceptional Conditions:
                   11615: #     If the $type passed in is not valid (not the string 'course' or 
                   11616: #     'user', an undefined  reference is returned.
                   11617: #     If none of the resources are found, an undef is returned
1.624     albertel 11618: sub resdata {
1.1301    raeburn  11619:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   11620:         $modifier,$what,@which)=@_;
1.624     albertel 11621:     my $result;
                   11622:     if ($type eq 'course') {
                   11623: 	$result=&get_courseresdata($name,$domain);
                   11624:     } elsif ($type eq 'user') {
                   11625: 	$result=&get_userresdata($name,$domain);
                   11626:     }
                   11627:     if (!ref($result)) { return $result; }    
1.251     albertel 11628:     foreach my $item (@which) {
1.1301    raeburn  11629:         if ($item->[1] eq 'course') {
                   11630:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   11631:                 unless ($$recursed) {
1.1302    raeburn  11632:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  11633:                     $$recursed = 1;
                   11634:                 }
                   11635:                 foreach my $item (@${recurseup}) {
                   11636:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   11637:                     last if (defined($result->{$norecursechk}));
                   11638:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   11639:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   11640:                 }
                   11641:             }
                   11642:         }
                   11643:         if (defined($result->{$item->[0]})) {
1.927     albertel 11644: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11645: 	}
1.250     albertel 11646:     }
1.291     albertel 11647:     return undef;
1.200     www      11648: }
                   11649: 
1.1360    raeburn  11650: sub get_domain_lti {
                   11651:     my ($cdom,$context) = @_;
                   11652:     my ($name,%lti);
                   11653:     if ($context eq 'consumer') {
                   11654:         $name = 'ltitools';
                   11655:     } elsif ($context eq 'provider') {
                   11656:         $name = 'lti';
                   11657:     } else {
                   11658:         return %lti;
                   11659:     }
                   11660:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  11661:     if (defined($cached)) {
                   11662:         if (ref($result) eq 'HASH') {
1.1360    raeburn  11663:             %lti = %{$result};
1.1298    raeburn  11664:         }
                   11665:     } else {
1.1360    raeburn  11666:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11667:         if (ref($domconfig{$name}) eq 'HASH') {
                   11668:             %lti = %{$domconfig{$name}};
                   11669:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   11670:             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11671:                 foreach my $id (keys(%lti)) {
                   11672:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  11673:                         foreach my $item ('key','secret') {
1.1360    raeburn  11674:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  11675:                         }
                   11676:                     }
                   11677:                 }
                   11678:             }
1.1298    raeburn  11679:         }
                   11680:         my $cachetime = 24*60*60;
1.1360    raeburn  11681:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  11682:     }
1.1360    raeburn  11683:     return %lti;
1.1298    raeburn  11684: }
                   11685: 
1.1236    raeburn  11686: sub get_numsuppfiles {
                   11687:     my ($cnum,$cdom,$ignorecache)=@_;
                   11688:     my $hashid=$cnum.':'.$cdom;
                   11689:     my ($suppcount,$cached);
                   11690:     unless ($ignorecache) {
                   11691:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11692:     }
                   11693:     unless (defined($cached)) {
                   11694:         my $chome=&homeserver($cnum,$cdom);
                   11695:         unless ($chome eq 'no_host') {
1.1366    raeburn  11696:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  11697:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  11698:             ($suppcount,$supptools,$errors) =
                   11699:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   11700:                                                          $supptools,$errors);
1.1236    raeburn  11701:         }
                   11702:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11703:     }
                   11704:     return $suppcount;
                   11705: }
                   11706: 
1.379     matthew  11707: #
                   11708: # EXT resource caching routines
                   11709: #
                   11710: 
1.1302    raeburn  11711: {
                   11712: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11713: #
                   11714: # The course for which we cache
                   11715: my $cachedmapkey='';
                   11716: # The cached recursive maps for this course
                   11717: my %cachedmaps=();
                   11718: # When this was last done
                   11719: my $cachedmaptime='';
                   11720: 
1.379     matthew  11721: sub clear_EXT_cache_status {
1.383     albertel 11722:     &delenv('cache.EXT.');
1.379     matthew  11723: }
                   11724: 
                   11725: sub EXT_cache_status {
                   11726:     my ($target_domain,$target_user) = @_;
1.383     albertel 11727:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11728:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11729:         # We know already the user has no data
                   11730:         return 1;
                   11731:     } else {
                   11732:         return 0;
                   11733:     }
                   11734: }
                   11735: 
                   11736: sub EXT_cache_set {
                   11737:     my ($target_domain,$target_user) = @_;
1.383     albertel 11738:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11739:     #&appenv({$cachename => time});
1.379     matthew  11740: }
                   11741: 
1.28      www      11742: # --------------------------------------------------------- Value of a Variable
1.58      www      11743: sub EXT {
1.715     albertel 11744: 
1.1228    raeburn  11745:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11746:     unless ($varname) { return ''; }
1.218     albertel 11747:     #get real user name/domain, courseid and symb
                   11748:     my $courseid;
1.359     albertel 11749:     my $publicuser;
1.427     www      11750:     if ($symbparm) {
                   11751: 	$symbparm=&get_symb_from_alias($symbparm);
                   11752:     }
1.218     albertel 11753:     if (!($uname && $udom)) {
1.790     albertel 11754:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11755:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11756:     } else {
1.620     albertel 11757: 	$courseid=$env{'request.course.id'};
1.218     albertel 11758:     }
1.48      www      11759:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11760:     my $rest;
1.320     albertel 11761:     if (defined($therest[0])) {
1.48      www      11762:        $rest=join('.',@therest);
                   11763:     } else {
                   11764:        $rest='';
                   11765:     }
1.320     albertel 11766: 
1.57      www      11767:     my $qualifierrest=$qualifier;
                   11768:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11769:     my $spacequalifierrest=$space;
                   11770:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11771:     if ($realm eq 'user') {
1.48      www      11772: # --------------------------------------------------------------- user.resource
                   11773: 	if ($space eq 'resource') {
1.651     albertel 11774: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11775: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11776: 		 &&
1.744     albertel 11777: 		 ($symbparm eq &symbread()) ) {	
                   11778: 		# if we are in the middle of processing the resource the
                   11779: 		# get the value we are planning on committing
                   11780:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11781:                     return $Apache::lonhomework::results{$qualifierrest};
                   11782:                 } else {
                   11783:                     return $Apache::lonhomework::history{$qualifierrest};
                   11784:                 }
1.335     albertel 11785: 	    } else {
1.359     albertel 11786: 		my %restored;
1.620     albertel 11787: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11788: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11789: 		} else {
                   11790: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11791: 		}
1.335     albertel 11792: 		return $restored{$qualifierrest};
                   11793: 	    }
1.48      www      11794: # ----------------------------------------------------------------- user.access
                   11795:         } elsif ($space eq 'access') {
1.218     albertel 11796: 	    # FIXME - not supporting calls for a specific user
1.48      www      11797:             return &allowed($qualifier,$rest);
                   11798: # ------------------------------------------ user.preferences, user.environment
                   11799:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11800: 	    if (($uname eq $env{'user.name'}) &&
                   11801: 		($udom eq $env{'user.domain'})) {
                   11802: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11803: 	    } else {
1.359     albertel 11804: 		my %returnhash;
                   11805: 		if (!$publicuser) {
                   11806: 		    %returnhash=&userenvironment($udom,$uname,
                   11807: 						 $qualifierrest);
                   11808: 		}
1.218     albertel 11809: 		return $returnhash{$qualifierrest};
                   11810: 	    }
1.48      www      11811: # ----------------------------------------------------------------- user.course
                   11812:         } elsif ($space eq 'course') {
1.218     albertel 11813: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11814:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11815: # ------------------------------------------------------------------- user.role
                   11816:         } elsif ($space eq 'role') {
1.218     albertel 11817: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11818:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11819:             if ($qualifier eq 'value') {
                   11820: 		return $role;
                   11821:             } elsif ($qualifier eq 'extent') {
                   11822:                 return $where;
                   11823:             }
                   11824: # ----------------------------------------------------------------- user.domain
                   11825:         } elsif ($space eq 'domain') {
1.218     albertel 11826:             return $udom;
1.48      www      11827: # ------------------------------------------------------------------- user.name
                   11828:         } elsif ($space eq 'name') {
1.218     albertel 11829:             return $uname;
1.48      www      11830: # ---------------------------------------------------- Any other user namespace
1.29      www      11831:         } else {
1.359     albertel 11832: 	    my %reply;
                   11833: 	    if (!$publicuser) {
                   11834: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11835: 	    }
                   11836: 	    return $reply{$qualifierrest};
1.48      www      11837:         }
1.236     www      11838:     } elsif ($realm eq 'query') {
                   11839: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11840:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11841: 						[$spacequalifierrest]);
1.620     albertel 11842: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11843:    } elsif ($realm eq 'request') {
1.48      www      11844: # ------------------------------------------------------------- request.browser
                   11845:         if ($space eq 'browser') {
1.1145    bisitz   11846:             return $env{'browser.'.$qualifier};
1.57      www      11847: # ------------------------------------------------------------ request.filename
                   11848:         } else {
1.620     albertel 11849:             return $env{'request.'.$spacequalifierrest};
1.29      www      11850:         }
1.28      www      11851:     } elsif ($realm eq 'course') {
1.48      www      11852: # ---------------------------------------------------------- course.description
1.620     albertel 11853:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11854:     } elsif ($realm eq 'resource') {
1.165     www      11855: 
1.620     albertel 11856: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11857: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11858: 	}
1.693     albertel 11859: 
1.1232    raeburn  11860:         if ($qualifier eq '') {
                   11861: 	    if ($space eq 'title') {
                   11862: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11863: 	        return &gettitle($symbparm);
                   11864: 	    }
1.693     albertel 11865: 	
1.1232    raeburn  11866: 	    if ($space eq 'map') {
                   11867: 	        my ($map) = &decode_symb($symbparm);
                   11868: 	        return &symbread($map);
                   11869: 	    }
                   11870:             if ($space eq 'maptitle') {
                   11871:                 my ($map) = &decode_symb($symbparm);
                   11872:                 return &gettitle($map);
                   11873:             }
                   11874: 	    if ($space eq 'filename') {
                   11875: 	        if ($symbparm) {
                   11876: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11877: 	        }
                   11878: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11879: 	    }
1.1232    raeburn  11880: 
1.1233    raeburn  11881:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11882:                 if ($space eq 'visibleparts') {
                   11883:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11884:                     my $item;
                   11885:                     if (ref($navmap)) {
                   11886:                         my $res = $navmap->getBySymb($symbparm);
                   11887:                         my $parts = $res->parts();
                   11888:                         if (ref($parts) eq 'ARRAY') {
                   11889:                             $item = join(',',@{$parts});
                   11890:                         }
                   11891:                         undef($navmap);
1.1232    raeburn  11892:                     }
1.1233    raeburn  11893:                     return $item;
1.1232    raeburn  11894:                 }
                   11895:             }
                   11896:         }
1.693     albertel 11897: 
1.1301    raeburn  11898: 	my ($section, $group, @groups, @recurseup, $recursed);
                   11899: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  11900:         if (($courseid eq '') && ($cid)) {
                   11901:             $courseid = $cid;
                   11902:         }
                   11903: 	if (($symbparm && $courseid) && 
                   11904: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      11905: 
1.218     albertel 11906: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11907: 
1.60      www      11908: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11909: 	    my $symbp=$symbparm;
1.1301    raeburn  11910: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11911: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  11912:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 11913: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 11914: 	    if (($env{'user.name'} eq $uname) &&
                   11915: 		($env{'user.domain'} eq $udom)) {
                   11916: 		$section=$env{'request.course.sec'};
1.733     raeburn  11917:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11918:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11919: 	    } else {
1.539     albertel 11920: 		if (! defined($usection)) {
1.551     albertel 11921: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11922: 		} else {
                   11923: 		    $section = $usection;
                   11924: 		}
1.733     raeburn  11925:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11926: 	    }
                   11927: 
                   11928: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11929: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  11930:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 11931: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11932: 
1.593     albertel 11933: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11934: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  11935:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 11936: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11937: 
1.60      www      11938: # ----------------------------------------------------------- first, check user
1.624     albertel 11939: 
1.1301    raeburn  11940: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   11941:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 11942: 				       ([$courselevelr,'resource'],
                   11943: 					[$courselevelm,'map'     ],
1.1301    raeburn  11944:                                         [$courseleveli,'map'     ],
1.927     albertel 11945: 					[$courselevel, 'course'  ]));
1.931     albertel 11946: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11947: 
1.594     albertel 11948: # ------------------------------------------------ second, check some of course
1.684     raeburn  11949:             my $coursereply;
1.691     raeburn  11950:             if (@groups > 0) {
                   11951:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  11952:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   11953:                                        $mapp,\$recursed,\@recurseup);
                   11954:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  11955:             }
1.96      www      11956: 
1.684     raeburn  11957: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11958: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11959: 				  'course',$mapp,\$recursed,\@recurseup,
                   11960:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 11961: 				  ([$seclevelr,   'resource'],
                   11962: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  11963:                                    [$secleveli,   'map'     ],
1.927     albertel 11964: 				   [$seclevel,    'course'  ],
                   11965: 				   [$courselevelr,'resource']));
                   11966: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11967: 
1.60      www      11968: # ------------------------------------------------------ third, check map parms
1.218     albertel 11969: 	    my %parmhash=();
                   11970: 	    my $thisparm='';
                   11971: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11972: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11973: 		    &GDBM_READER(),0640)) {
1.218     albertel 11974: 		$thisparm=$parmhash{$symbparm};
                   11975: 		untie(%parmhash);
                   11976: 	    }
1.927     albertel 11977: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11978: 	}
1.594     albertel 11979: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  11980:  
                   11981:         my $what = $spacequalifierrest;
                   11982: 	$what=~s/\./\_/;
1.282     albertel 11983: 	my $filename;
                   11984: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11985: 	if ($symbparm) {
1.409     www      11986: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11987: 	} else {
1.620     albertel 11988: 	    $filename=$env{'request.filename'};
1.282     albertel 11989: 	}
1.1362    raeburn  11990:         my $toolsymb;
                   11991:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   11992:             $toolsymb = $symbparm;
                   11993:         }
                   11994: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 11995: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  11996: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 11997: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11998: 
1.1301    raeburn  11999: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 12000: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12001: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12002: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12003: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12004: 				     'course',$mapp,\$recursed,\@recurseup,
                   12005:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 12006: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  12007:                                       [$courseleveli,'map'   ],
1.927     albertel 12008: 				      [$courselevel, 'course']));
                   12009: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12010: 	}
1.145     www      12011: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12012: 	unless ($space eq '0') {
1.336     albertel 12013: 	    my @parts=split(/_/,$space);
                   12014: 	    my $id=pop(@parts);
                   12015: 	    my $part=join('_',@parts);
                   12016: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12017: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12018: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12019: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12020: 	}
1.395     albertel 12021: 	if ($recurse) { return undef; }
1.1362    raeburn  12022: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 12023: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12024: # ---------------------------------------------------- Any other user namespace
                   12025:     } elsif ($realm eq 'environment') {
                   12026: # ----------------------------------------------------------------- environment
1.620     albertel 12027: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12028: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12029: 	} else {
1.770     albertel 12030: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12031: 		return '';
                   12032: 	    }
1.219     albertel 12033: 	    my %returnhash=&userenvironment($udom,$uname,
                   12034: 					    $spacequalifierrest);
                   12035: 	    return $returnhash{$spacequalifierrest};
                   12036: 	}
1.28      www      12037:     } elsif ($realm eq 'system') {
1.48      www      12038: # ----------------------------------------------------------------- system.time
                   12039: 	if ($space eq 'time') {
                   12040: 	    return time;
                   12041:         }
1.696     albertel 12042:     } elsif ($realm eq 'server') {
                   12043: # ----------------------------------------------------------------- system.time
                   12044: 	if ($space eq 'name') {
                   12045: 	    return $ENV{'SERVER_NAME'};
                   12046:         }
1.28      www      12047:     }
1.48      www      12048:     return '';
1.61      www      12049: }
                   12050: 
1.927     albertel 12051: sub get_reply {
                   12052:     my ($reply_value) = @_;
1.940     raeburn  12053:     if (ref($reply_value) eq 'ARRAY') {
                   12054:         if (wantarray) {
                   12055: 	    return @$reply_value;
                   12056:         }
                   12057:         return $reply_value->[0];
                   12058:     } else {
                   12059:         return $reply_value;
1.927     albertel 12060:     }
                   12061: }
                   12062: 
1.691     raeburn  12063: sub check_group_parms {
1.1301    raeburn  12064:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   12065:         $recursed,$recurseupref) = @_;
                   12066:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   12067:                   [$what,'course']);
                   12068:     my $coursereply;
1.691     raeburn  12069:     foreach my $group (@{$groups}) {
1.1301    raeburn  12070:         my @groupitems = ();
1.691     raeburn  12071:         foreach my $level (@levels) {
1.927     albertel 12072:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12073:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12074:         }
1.1301    raeburn  12075:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12076:                                    $env{'course.'.$courseid.'.domain'},
                   12077:                                    'course',$mapp,$recursed,$recurseupref,
                   12078:                                    $courseid,'.['.$group.'].',$what,
                   12079:                                    @groupitems);
                   12080:         last if (defined($coursereply));
1.691     raeburn  12081:     }
                   12082:     return $coursereply;
                   12083: }
                   12084: 
1.1301    raeburn  12085: sub get_map_hierarchy {
1.1302    raeburn  12086:     my ($mapname,$courseid) = @_;
                   12087:     my @recurseup = ();
1.1301    raeburn  12088:     if ($mapname) {
1.1302    raeburn  12089:         if (($cachedmapkey eq $courseid) &&
                   12090:             (abs($cachedmaptime-time)<5)) {
                   12091:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12092:                 return @{$cachedmaps{$mapname}};
                   12093:             }
                   12094:         }
1.1301    raeburn  12095:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12096:         if (ref($navmap)) {
                   12097:             @recurseup = $navmap->recurseup_maps($mapname);
                   12098:             undef($navmap);
1.1302    raeburn  12099:             $cachedmaps{$mapname} = \@recurseup;
                   12100:             $cachedmaptime=time;
                   12101:             $cachedmapkey=$courseid;
1.1301    raeburn  12102:         }
                   12103:     }
                   12104:     return @recurseup;
                   12105: }
                   12106: 
1.1302    raeburn  12107: }
                   12108: 
1.691     raeburn  12109: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12110:     my ($courseid,@groups) = @_;
                   12111:     @groups = sort(@groups);
1.691     raeburn  12112:     return @groups;
                   12113: }
                   12114: 
1.395     albertel 12115: sub packages_tab_default {
1.1362    raeburn  12116:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 12117:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12118: 
                   12119:     my (@extension,@specifics,$do_default);
1.1362    raeburn  12120:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 12121: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12122: 	if ($pack_type eq 'default') {
                   12123: 	    $do_default=1;
                   12124: 	} elsif ($pack_type eq 'extension') {
                   12125: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12126: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12127: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12128: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12129: 	}
                   12130:     }
                   12131:     # first look for a package that matches the requested part id
                   12132:     foreach my $package (@specifics) {
                   12133: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12134: 	next if ($pack_part ne $part);
                   12135: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12136: 	    return $packagetab{"$pack_type&$name&default"};
                   12137: 	}
                   12138:     }
                   12139:     # look for any possible matching non extension_ package
                   12140:     foreach my $package (@specifics) {
                   12141: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12142: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12143: 	    return $packagetab{"$pack_type&$name&default"};
                   12144: 	}
1.585     albertel 12145: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12146: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12147: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12148: 	}
                   12149:     }
1.738     albertel 12150:     # look for any posible extension_ match
                   12151:     foreach my $package (@extension) {
                   12152: 	my ($package,$pack_type)=@{$package};
                   12153: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12154: 	    return $packagetab{"$pack_type&$name&default"};
                   12155: 	}
                   12156: 	if (defined($packagetab{$package."&$name&default"})) {
                   12157: 	    return $packagetab{$package."&$name&default"};
                   12158: 	}
                   12159:     }
                   12160:     # look for a global default setting
                   12161:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12162: 	return $packagetab{"default&$name&default"};
                   12163:     }
1.395     albertel 12164:     return undef;
                   12165: }
                   12166: 
1.334     albertel 12167: sub add_prefix_and_part {
                   12168:     my ($prefix,$part)=@_;
                   12169:     my $keyroot;
                   12170:     if (defined($prefix) && $prefix !~ /^__/) {
                   12171: 	# prefix that has a part already
                   12172: 	$keyroot=$prefix;
                   12173:     } elsif (defined($prefix)) {
                   12174: 	# prefix that is missing a part
                   12175: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12176:     } else {
                   12177: 	# no prefix at all
                   12178: 	if (defined($part)) { $keyroot='_'.$part; }
                   12179:     }
                   12180:     return $keyroot;
                   12181: }
                   12182: 
1.71      www      12183: # ---------------------------------------------------------------- Get metadata
                   12184: 
1.599     albertel 12185: my %metaentry;
1.1070    www      12186: my %importedpartids;
1.1369    raeburn  12187: my %importedrespids;
1.71      www      12188: sub metadata {
1.1362    raeburn  12189:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      12190:     $uri=&declutter($uri);
1.288     albertel 12191:     # if it is a non metadata possible uri return quickly
1.529     albertel 12192:     if (($uri eq '') || 
                   12193: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  12194: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12195:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12196: 	return undef;
                   12197:     }
1.1261    raeburn  12198:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12199: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12200: 	return undef;
1.288     albertel 12201:     }
1.73      www      12202:     my $filename=$uri;
                   12203:     $uri=~s/\.meta$//;
1.172     www      12204: #
                   12205: # Is the metadata already cached?
1.177     www      12206: # Look at timestamp of caching
1.172     www      12207: # Everything is cached by the main uri, libraries are never directly cached
                   12208: #
1.428     albertel 12209:     if (!defined($liburi)) {
1.599     albertel 12210: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12211: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12212:     }
1.1362    raeburn  12213: 
                   12214: #
                   12215: # If the uri is for an external tool the file from
                   12216: # which metadata should be retrieved depends on whether
                   12217: # the tool had been configured to be gradable (set in the Course
                   12218: # Editor or Resource Editor).
                   12219: #
                   12220: # If a valid symb has been included as the third arg in the call
                   12221: # to &metadata() that can be used to retrieve the value of
                   12222: # parameter_0_gradable set for the resource, and included in the
                   12223: # uploaded map containing the tool. The value is retrieved via
                   12224: # &EXT(), if a valid symb is available.  Otherwise the value of
                   12225: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  12226: # is retrieved via &get().
                   12227: #
                   12228: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   12229: # hiddenresource and encrypturl (during course initialization)
                   12230: # the map-level parameter for resource.0.gradable included in the 
                   12231: # uploaded map containing the tool will not yet have been stored
                   12232: # in the user_course_parms.db file for the user's session, so in 
                   12233: # this case fall back to retrieving gradable status from the
                   12234: # exttool_$marker.db file.
1.1362    raeburn  12235: #
                   12236: # In order to avoid an infinite loop, &metadata() will return
                   12237: # before a call to &EXT(), if the uri is for an external tool
                   12238: # and the $what for which metadata is being requested is
                   12239: # parameter_0_gradable or 0_gradable.
                   12240: #
                   12241: 
                   12242:     if ($uri =~ /ext\.tool$/) {
                   12243:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   12244:             return;
                   12245:         } else {
                   12246:             my ($checked,$use_passback);
                   12247:             if ($toolsymb ne '') {
                   12248:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  12249:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  12250:                     $checked = 1;
                   12251:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   12252:                         $use_passback = 1;
                   12253:                     }
                   12254:                 }
                   12255:             }
                   12256:             unless ($checked) {
                   12257:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   12258:                 $marker=~s/\D//g;
1.1363    raeburn  12259:                 if ($marker) {
1.1362    raeburn  12260:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   12261:                     $use_passback = $toolsettings{'gradable'};
                   12262:                 }
                   12263:             }
                   12264:             if ($use_passback) {
                   12265:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   12266:             } else {
                   12267:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   12268:             }
                   12269:         }
                   12270:     }
                   12271: 
1.428     albertel 12272:     {
1.1069    www      12273: # Imported parts would go here
1.1369    raeburn  12274:         my @origfiletagids=();
1.1069    www      12275:         my $importedparts=0;
1.1369    raeburn  12276: 
                   12277: # Imported responseids would go here
                   12278:         my $importedresponses=0;
1.172     www      12279: #
                   12280: # Is this a recursive call for a library?
                   12281: #
1.599     albertel 12282: #	if (! exists($metacache{$uri})) {
                   12283: #	    $metacache{$uri}={};
                   12284: #	}
1.924     albertel 12285: 	my $cachetime = 60*60;
1.171     www      12286:         if ($liburi) {
                   12287: 	    $liburi=&declutter($liburi);
                   12288:             $filename=$liburi;
1.401     bowersj2 12289:         } else {
1.599     albertel 12290: 	    &devalidate_cache_new('meta',$uri);
                   12291: 	    undef(%metaentry);
1.401     bowersj2 12292: 	}
1.140     www      12293:         my %metathesekeys=();
1.73      www      12294:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12295: 	my $metastring;
1.1140    www      12296: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12297: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12298: 	    $metastring = 
1.929     albertel 12299: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12300: 					  ('grade_target' => 'meta'));
                   12301: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12302: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12303:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12304: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12305: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12306: 	    $metastring=&getfile($file);
1.489     albertel 12307: 	}
1.208     albertel 12308:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12309:         my $token;
1.140     www      12310:         undef %metathesekeys;
1.71      www      12311:         while ($token=$parser->get_token) {
1.339     albertel 12312: 	    if ($token->[0] eq 'S') {
                   12313: 		if (defined($token->[2]->{'package'})) {
1.172     www      12314: #
                   12315: # This is a package - get package info
                   12316: #
1.339     albertel 12317: 		    my $package=$token->[2]->{'package'};
                   12318: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12319: 		    if (defined($token->[2]->{'id'})) { 
                   12320: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12321: 		    }
1.599     albertel 12322: 		    if ($metaentry{':packages'}) {
                   12323: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12324: 		    } else {
1.599     albertel 12325: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12326: 		    }
1.736     albertel 12327: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12328: 			my $part=$keyroot;
                   12329: 			$part=~s/^\_//;
1.736     albertel 12330: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12331: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12332: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12333: 			    # ignore package.tab specified default values
                   12334:                             # here &package_tab_default() will fetch those
                   12335: 			    if ($subp eq 'default') { next; }
1.736     albertel 12336: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12337: 			    my $unikey;
                   12338: 			    if ($pack =~ /_0$/) {
                   12339: 				$unikey='parameter_0_'.$name;
                   12340: 				$part=0;
                   12341: 			    } else {
                   12342: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12343: 			    }
1.339     albertel 12344: 			    if ($subp eq 'display') {
                   12345: 				$value.=' [Part: '.$part.']';
                   12346: 			    }
1.599     albertel 12347: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12348: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12349: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12350: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12351: 			    }
1.599     albertel 12352: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12353: 				$metaentry{':'.$unikey}=
                   12354: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12355: 			    }
1.339     albertel 12356: 			}
                   12357: 		    }
                   12358: 		} else {
1.172     www      12359: #
                   12360: # This is not a package - some other kind of start tag
1.339     albertel 12361: #
                   12362: 		    my $entry=$token->[1];
1.1068    www      12363: 		    my $unikey='';
1.175     www      12364: 
1.339     albertel 12365: 		    if ($entry eq 'import') {
1.175     www      12366: #
                   12367: # Importing a library here
1.339     albertel 12368: #
1.1067    www      12369:                         my $location=$parser->get_text('/import');
                   12370:                         my $dir=$filename;
                   12371:                         $dir=~s|[^/]*$||;
                   12372:                         $location=&filelocation($dir,$location);
1.1369    raeburn  12373: 
                   12374:                         my $importid=$token->[2]->{'id'};
1.1068    www      12375:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  12376: #
                   12377: # Check metadata for imported file to
                   12378: # see if it contained response items
                   12379: #
1.1372    raeburn  12380:                         my ($origfile,@libfilekeys);
1.1370    raeburn  12381:                         my %currmetaentry = %metaentry;
1.1372    raeburn  12382:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   12383:                                                            $depthcount+1));
                   12384:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   12385:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   12386:                                                              undef,$depthcount+1);
                   12387:                             if ($libresponseorder ne '') {
                   12388:                                 if ($#origfiletagids<0) {
                   12389:                                     undef(%importedrespids);
                   12390:                                     undef(%importedpartids);
                   12391:                                 }
1.1373    raeburn  12392:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   12393:                                 if (@respids) {
                   12394:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   12395:                                 }
                   12396:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  12397:                                     $importedresponses = 1;
1.1369    raeburn  12398: # We need to get the original file and the imported file to get the response order correct
                   12399: # Load and inspect original file
1.1372    raeburn  12400:                                     if ($#origfiletagids<0) {
                   12401:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12402:                                         $origfile=&getfile($origfilelocation);
                   12403:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12404:                                     }
1.1369    raeburn  12405:                                 }
                   12406:                             }
                   12407:                         }
1.1370    raeburn  12408: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12409: # hash populated for imported library file
                   12410:                         %metaentry = %currmetaentry;
                   12411:                         undef(%currmetaentry);
1.1374    raeburn  12412:                         if ($importmode eq 'part') {
1.1068    www      12413: # Import as part(s)
1.1069    www      12414:                            $importedparts=1;
                   12415: # We need to get the original file and the imported file to get the part order correct
                   12416: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  12417: # Load and inspect original file if we didn't do that already
                   12418:                            if ($#origfiletagids<0) {
                   12419:                                undef(%importedrespids);
                   12420:                                undef(%importedpartids);
                   12421:                                if ($origfile eq '') {
                   12422:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12423:                                    $origfile=&getfile($origfilelocation);
                   12424:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12425:                                }
1.1070    www      12426:                            }
1.1372    raeburn  12427:                            my @impfilepartids;
                   12428: # If <partorder> tag is included in metadata for the imported file
                   12429: # get the parts in the imported file from that.
                   12430:                            if (grep(/^partorder$/,@libfilekeys)) {
                   12431:                                %currmetaentry = %metaentry;
                   12432:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12433:                                                             $depthcount+1);
                   12434:                                %metaentry = %currmetaentry;
                   12435:                                undef(%currmetaentry);
                   12436:                                if ($libpartorder ne '') {
                   12437:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   12438:                                }
                   12439:                            } else {
                   12440: # If no <partorder> tag available, load and inspect imported file
                   12441:                                my $impfile=&getfile($location);
                   12442:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12443:                            }
1.1069    www      12444:                            if ($#impfilepartids>=0) {
                   12445: # This problem had parts
1.1070    www      12446:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12447:                            } else {
                   12448: # Importing by turning a single problem into a problem part
                   12449: # It gets the import-tags ID as part-ID
                   12450:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12451:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12452:                            }
1.1068    www      12453:                         } else {
1.1374    raeburn  12454: # Import as problem or as normal import
                   12455:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12456:                             unless ($importmode eq 'problem') {
1.1068    www      12457: # Normal import
1.1374    raeburn  12458:                                 if (defined($token->[2]->{'id'})) {
                   12459:                                     $unikey.='_'.$token->[2]->{'id'};
                   12460:                                 }
                   12461:                             }
                   12462: # Check metadata for imported file to
                   12463: # see if it contained parts
                   12464:                             if (grep(/^partorder$/,@libfilekeys)) {
                   12465:                                 %currmetaentry = %metaentry;
                   12466:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12467:                                                              $depthcount+1);
                   12468:                                 %metaentry = %currmetaentry;
                   12469:                                 undef(%currmetaentry);
                   12470:                                 if ($libpartorder ne '') {
                   12471:                                     $importedparts = 1;
                   12472:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   12473:                                 }
                   12474:                             }
1.1067    www      12475:                         }
1.339     albertel 12476: 			if ($depthcount<20) {
1.736     albertel 12477: 			    my $metadata = 
1.1362    raeburn  12478: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12479: 					  $depthcount+1);
                   12480: 			    foreach my $meta (split(',',$metadata)) {
                   12481: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12482: 				$metathesekeys{$meta}=1;
1.339     albertel 12483: 			    }
1.1068    www      12484:                         }
1.1067    www      12485: 		    } else {
                   12486: #
                   12487: # Not importing, some other kind of non-package, non-library start tag
                   12488: # 
                   12489:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12490:                         if (defined($token->[2]->{'id'})) {
                   12491:                             $unikey.='_'.$token->[2]->{'id'};
                   12492:                         }
1.339     albertel 12493: 			if (defined($token->[2]->{'name'})) { 
                   12494: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12495: 			}
                   12496: 			$metathesekeys{$unikey}=1;
1.736     albertel 12497: 			foreach my $param (@{$token->[3]}) {
                   12498: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12499: 				$token->[2]->{$param};
1.339     albertel 12500: 			}
                   12501: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12502: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12503: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12504: 		 # only ws inside the tag, and not in default, so use default
                   12505: 		 # as value
1.599     albertel 12506: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12507: 			} elsif ( $internaltext =~ /\S/ ) {
                   12508: 		  # something interesting inside the tag
                   12509: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12510: 			} else {
1.908     albertel 12511: 		  # no interesting values, don't set a default
1.339     albertel 12512: 			}
1.172     www      12513: # end of not-a-package not-a-library import
1.339     albertel 12514: 		    }
1.172     www      12515: # end of not-a-package start tag
1.339     albertel 12516: 		}
1.172     www      12517: # the next is the end of "start tag"
1.339     albertel 12518: 	    }
                   12519: 	}
1.483     albertel 12520: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12521: 	$extension = lc($extension);
                   12522: 	if ($extension eq 'htm') { $extension='html'; }
                   12523: 
1.737     albertel 12524: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12525: 	    #no specific packages #how's our extension
                   12526: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12527: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12528: 					 \%metathesekeys);
                   12529: 	}
1.883     albertel 12530: 
                   12531: 	if (!exists($metaentry{':packages'})
                   12532: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12533: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12534: 		#no specific packages well let's get default then
                   12535: 		if ($key!~/^default&/) { next; }
1.488     albertel 12536: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12537: 					     \%metathesekeys);
                   12538: 	    }
                   12539: 	}
1.338     www      12540: # are there custom rights to evaluate
1.599     albertel 12541: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12542: 
1.338     www      12543:     #
                   12544:     # Importing a rights file here
1.339     albertel 12545:     #
                   12546: 	    unless ($depthcount) {
1.599     albertel 12547: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12548: 		my $dir=$filename;
                   12549: 		$dir=~s|[^/]*$||;
                   12550: 		$location=&filelocation($dir,$location);
1.736     albertel 12551: 		my $rights_metadata =
1.1362    raeburn  12552: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 12553: 			      $depthcount+1);
                   12554: 		foreach my $rights (split(',',$rights_metadata)) {
                   12555: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12556: 		    $metathesekeys{$rights}=1;
1.339     albertel 12557: 		}
                   12558: 	    }
                   12559: 	}
1.737     albertel 12560: 	# uniqifiy package listing
                   12561: 	my %seen;
                   12562: 	my @uniq_packages =
                   12563: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12564: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12565: 
1.1369    raeburn  12566:         if (($importedresponses) || ($importedparts)) {
                   12567:             if ($importedparts) {
1.1070    www      12568: # We had imported parts and need to rebuild partorder
1.1369    raeburn  12569:                 $metaentry{':partorder'}='';
                   12570:                 $metathesekeys{'partorder'}=1;
                   12571:             }
                   12572:             if ($importedresponses) {
                   12573: # We had imported responses and need to rebuil responseorder
                   12574:                 $metaentry{':responseorder'}='';
                   12575:                 $metathesekeys{'responseorder'}=1;
                   12576:             }
                   12577:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12578:                 my $origid = $origfiletagids[$index+1];
                   12579:                 if ($origfiletagids[$index] eq 'part') {
                   12580: # Original part, part of the problem
                   12581:                     if ($importedparts) {
                   12582:                         $metaentry{':partorder'}.=','.$origid;
                   12583:                     }
                   12584:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12585:                     if ($importedparts) {
                   12586: # We have imported parts at this position
1.1373    raeburn  12587:                         if ($importedpartids{$origid} ne '') {
                   12588:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12589:                         }
1.1369    raeburn  12590:                     }
                   12591:                     if ($importedresponses) {
                   12592: # We have imported responses at this position
1.1373    raeburn  12593:                         if ($importedrespids{$origid} ne '') {
                   12594:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  12595:                         }
                   12596:                     }
                   12597:                 } else {
                   12598: # Original response item, part of the problem
                   12599:                     if ($importedresponses) {
                   12600:                         $metaentry{':responseorder'}.=','.$origid;
                   12601:                     }
                   12602:                 }
                   12603:             }
                   12604:             if ($importedparts) {
                   12605:                 $metaentry{':partorder'}=~s/^\,//;
                   12606:             }
                   12607:             if ($importedresponses) {
                   12608:                 $metaentry{':responseorder'}=~s/^\,//;
                   12609:             }
1.1070    www      12610:         }
1.737     albertel 12611: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12612: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  12613: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  12614:         unless ($liburi) {
                   12615: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   12616:         }
1.177     www      12617: # this is the end of "was not already recently cached
1.71      www      12618:     }
1.599     albertel 12619:     return $metaentry{':'.$what};
1.261     albertel 12620: }
                   12621: 
1.488     albertel 12622: sub metadata_create_package_def {
1.483     albertel 12623:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12624:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12625:     if ($subp eq 'default') { next; }
                   12626:     
1.599     albertel 12627:     if (defined($metaentry{':packages'})) {
                   12628: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12629:     } else {
1.599     albertel 12630: 	$metaentry{':packages'}=$package;
1.483     albertel 12631:     }
                   12632:     my $value=$packagetab{$key};
                   12633:     my $unikey;
                   12634:     $unikey='parameter_0_'.$name;
1.599     albertel 12635:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12636:     $$metathesekeys{$unikey}=1;
1.599     albertel 12637:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12638: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12639:     }
1.599     albertel 12640:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12641: 	$metaentry{':'.$unikey}=
                   12642: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12643:     }
                   12644: }
                   12645: 
1.261     albertel 12646: sub metadata_generate_part0 {
                   12647:     my ($metadata,$metacache,$uri) = @_;
                   12648:     my %allnames;
1.737     albertel 12649:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12650: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12651: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12652: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12653: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12654: 	    $allnames{$name}=$part;
                   12655: 	  }
                   12656: 	}
                   12657:     }
                   12658:     foreach my $name (keys(%allnames)) {
                   12659:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12660:       my $key=":parameter_0_$name";
1.261     albertel 12661:       $$metacache{"$key.part"}='0';
                   12662:       $$metacache{"$key.name"}=$name;
1.428     albertel 12663:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12664: 					   $allnames{$name}.'_'.$name.
                   12665: 					   '.type'};
1.428     albertel 12666:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12667: 			     '.display'};
1.644     www      12668:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12669:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12670:       $$metacache{"$key.display"}=$olddis;
                   12671:     }
1.71      www      12672: }
                   12673: 
1.764     albertel 12674: # ------------------------------------------------------ Devalidate title cache
                   12675: 
                   12676: sub devalidate_title_cache {
                   12677:     my ($url)=@_;
                   12678:     if (!$env{'request.course.id'}) { return; }
                   12679:     my $symb=&symbread($url);
                   12680:     if (!$symb) { return; }
                   12681:     my $key=$env{'request.course.id'}."\0".$symb;
                   12682:     &devalidate_cache_new('title',$key);
                   12683: }
                   12684: 
1.1014    droeschl 12685: # ------------------------------------------------- Get the title of a course
                   12686: 
                   12687: sub current_course_title {
                   12688:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12689: }
1.301     www      12690: # ------------------------------------------------- Get the title of a resource
                   12691: 
                   12692: sub gettitle {
                   12693:     my $urlsymb=shift;
                   12694:     my $symb=&symbread($urlsymb);
1.534     albertel 12695:     if ($symb) {
1.620     albertel 12696: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12697: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12698: 	if (defined($cached)) { 
                   12699: 	    return $result;
                   12700: 	}
1.534     albertel 12701: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12702: 	my $title='';
1.907     albertel 12703: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12704: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12705: 	} else {
                   12706: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12707: 		    &GDBM_READER(),0640)) {
                   12708: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12709: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12710: 		untie(%bighash);
                   12711: 	    }
1.534     albertel 12712: 	}
                   12713: 	$title=~s/\&colon\;/\:/gs;
                   12714: 	if ($title) {
1.1159    www      12715: # Remember both $symb and $title for dynamic metadata
                   12716:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12717:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12718: # Cache this title and then return it
1.599     albertel 12719: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12720: 	}
                   12721: 	$urlsymb=$url;
                   12722:     }
                   12723:     my $title=&metadata($urlsymb,'title');
                   12724:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12725:     return $title;
1.301     www      12726: }
1.613     albertel 12727: 
1.614     albertel 12728: sub get_slot {
                   12729:     my ($which,$cnum,$cdom)=@_;
                   12730:     if (!$cnum || !$cdom) {
1.790     albertel 12731: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12732: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12733: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12734:     }
1.703     albertel 12735:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12736:     my %slotinfo;
                   12737:     if (exists($remembered{$key})) {
                   12738: 	$slotinfo{$which} = $remembered{$key};
                   12739:     } else {
                   12740: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12741: 	&Apache::lonhomework::showhash(%slotinfo);
                   12742: 	my ($tmp)=keys(%slotinfo);
                   12743: 	if ($tmp=~/^error:/) { return (); }
                   12744: 	$remembered{$key} = $slotinfo{$which};
                   12745:     }
1.616     albertel 12746:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12747: 	return %{$slotinfo{$which}};
                   12748:     }
                   12749:     return $slotinfo{$which};
1.614     albertel 12750: }
1.1150    raeburn  12751: 
                   12752: sub get_reservable_slots {
                   12753:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12754:     my $now = time;
                   12755:     my $reservable_info;
                   12756:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12757:     if (exists($remembered{$key})) {
                   12758:         $reservable_info = $remembered{$key};
                   12759:     } else {
                   12760:         my %resv;
                   12761:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12762:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12763:         $reservable_info = \%resv;
                   12764:         $remembered{$key} = $reservable_info;
                   12765:     }
                   12766:     return $reservable_info;
                   12767: }
                   12768: 
                   12769: sub get_course_slots {
                   12770:     my ($cnum,$cdom) = @_;
                   12771:     my $hashid=$cnum.':'.$cdom;
                   12772:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12773:     if (defined($cached)) {
                   12774:         if (ref($result) eq 'HASH') {
                   12775:             return %{$result};
                   12776:         }
                   12777:     } else {
                   12778:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12779:         my ($tmp) = keys(%slots);
                   12780:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  12781:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12782:             return %slots;
                   12783:         }
                   12784:     }
                   12785:     return;
                   12786: }
                   12787: 
                   12788: sub devalidate_slots_cache {
                   12789:     my ($cnum,$cdom)=@_;
                   12790:     my $hashid=$cnum.':'.$cdom;
                   12791:     &devalidate_cache_new('allslots',$hashid);
                   12792: }
                   12793: 
1.1181    raeburn  12794: sub get_coursechange {
                   12795:     my ($cdom,$cnum) = @_;
                   12796:     if ($cdom eq '' || $cnum eq '') {
                   12797:         return unless ($env{'request.course.id'});
                   12798:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12799:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12800:     }
                   12801:     my $hashid=$cdom.'_'.$cnum;
                   12802:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12803:     if ((defined($cached)) && ($change ne '')) {
                   12804:         return $change;
                   12805:     } else {
                   12806:         my %crshash;
                   12807:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12808:         if ($crshash{'internal.contentchange'} eq '') {
                   12809:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12810:             if ($change eq '') {
                   12811:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12812:                 $change = $crshash{'internal.created'};
                   12813:             }
                   12814:         } else {
                   12815:             $change = $crshash{'internal.contentchange'};
                   12816:         }
                   12817:         my $cachetime = 600;
                   12818:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12819:     }
                   12820:     return $change;
                   12821: }
                   12822: 
                   12823: sub devalidate_coursechange_cache {
                   12824:     my ($cnum,$cdom)=@_;
                   12825:     my $hashid=$cnum.':'.$cdom;
                   12826:     &devalidate_cache_new('crschange',$hashid);
                   12827: }
                   12828: 
1.31      www      12829: # ------------------------------------------------- Update symbolic store links
                   12830: 
                   12831: sub symblist {
                   12832:     my ($mapname,%newhash)=@_;
1.438     www      12833:     $mapname=&deversion(&declutter($mapname));
1.31      www      12834:     my %hash;
1.620     albertel 12835:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12836:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12837:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12838: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12839: 		next if ($url eq 'last_known'
                   12840: 			 && $env{'form.no_update_last_known'});
                   12841: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12842: 						    $newhash{$url}->[1],
                   12843: 						    $newhash{$url}->[0]);
1.191     harris41 12844:             }
1.31      www      12845:             if (untie(%hash)) {
                   12846: 		return 'ok';
                   12847:             }
                   12848:         }
                   12849:     }
                   12850:     return 'error';
1.212     www      12851: }
                   12852: 
                   12853: # --------------------------------------------------------------- Verify a symb
                   12854: 
                   12855: sub symbverify {
1.1190    raeburn  12856:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12857:     my $thisfn=$thisurl;
1.439     www      12858:     $thisfn=&declutter($thisfn);
1.215     www      12859: # direct jump to resource in page or to a sequence - will construct own symbs
                   12860:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12861: # check URL part
1.409     www      12862:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12863: 
1.431     www      12864:     unless ($url eq $thisfn) { return 0; }
1.213     www      12865: 
1.216     www      12866:     $symb=&symbclean($symb);
1.510     www      12867:     $thisurl=&deversion($thisurl);
1.439     www      12868:     $thisfn=&deversion($thisfn);
1.213     www      12869: 
                   12870:     my %bighash;
                   12871:     my $okay=0;
1.431     www      12872: 
1.620     albertel 12873:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12874:                             &GDBM_READER(),0640)) {
1.1204    raeburn  12875:         my $noclutter;
1.1032    raeburn  12876:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12877:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  12878:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12879:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12880:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12881:                 $noclutter = 1;
                   12882:             }
                   12883:         }
                   12884:         my $ids;
                   12885:         if ($noclutter) {
                   12886:             $ids=$bighash{'ids_'.$thisurl};
                   12887:         } else {
                   12888:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12889:         }
1.1102    raeburn  12890:         unless ($ids) {
                   12891:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   12892:             $ids=$bighash{$idkey};
1.216     www      12893:         }
                   12894:         if ($ids) {
                   12895: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  12896:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  12897:                 $symb =~ s/\?.+$//;
1.1202    raeburn  12898:             }
1.800     albertel 12899: 	    foreach my $id (split(/\,/,$ids)) {
                   12900: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12901:                if (
                   12902:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  12903:    eq $symb) {
                   12904:                    if (ref($encstate)) {
                   12905:                        $$encstate = $bighash{'encrypted_'.$id};
                   12906:                    }
1.620     albertel 12907: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  12908: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   12909:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  12910: 		       $okay=1;
1.1202    raeburn  12911:                        last;
1.582     albertel 12912: 		   }
                   12913: 	       }
1.216     www      12914: 	   }
                   12915:         }
1.213     www      12916: 	untie(%bighash);
                   12917:     }
                   12918:     return $okay;
1.31      www      12919: }
                   12920: 
1.210     www      12921: # --------------------------------------------------------------- Clean-up symb
                   12922: 
                   12923: sub symbclean {
                   12924:     my $symb=shift;
1.568     albertel 12925:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12926: # remove version from map
                   12927:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12928: 
1.210     www      12929: # remove version from URL
                   12930:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12931: 
1.507     www      12932: # remove wrapper
                   12933: 
1.510     www      12934:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12935:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12936:     return $symb;
1.409     www      12937: }
                   12938: 
                   12939: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12940: 
                   12941: sub encode_symb {
                   12942:     my ($map,$resid,$url)=@_;
                   12943:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12944: }
1.409     www      12945: 
                   12946: sub decode_symb {
1.568     albertel 12947:     my $symb=shift;
                   12948:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12949:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12950:     return (&fixversion($map),$resid,&fixversion($url));
                   12951: }
                   12952: 
                   12953: sub fixversion {
                   12954:     my $fn=shift;
1.609     banghart 12955:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12956:     my %bighash;
                   12957:     my $uri=&clutter($fn);
1.620     albertel 12958:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12959: # is this cached?
1.599     albertel 12960:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12961:     if (defined($cached)) { return $result; }
                   12962: # unfortunately not cached, or expired
1.620     albertel 12963:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12964: 	    &GDBM_READER(),0640)) {
                   12965:  	if ($bighash{'version_'.$uri}) {
                   12966:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12967:  	    unless (($version eq 'mostrecent') || 
                   12968: 		    ($version==&getversion($uri))) {
1.440     www      12969:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12970:  	    }
                   12971:  	}
                   12972:  	untie %bighash;
1.413     www      12973:     }
1.599     albertel 12974:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12975: }
                   12976: 
                   12977: sub deversion {
                   12978:     my $url=shift;
                   12979:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12980:     return $url;
1.210     www      12981: }
                   12982: 
1.31      www      12983: # ------------------------------------------------------ Return symb list entry
                   12984: 
                   12985: sub symbread {
1.1282    raeburn  12986:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  12987:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  12988:     if (defined($env{$cache_str})) {
                   12989:         if ($ignorecachednull) {
                   12990:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12991:         } else {
                   12992:             return $env{$cache_str};
                   12993:         }
                   12994:     }
1.242     www      12995: # no filename provided? try from environment
1.1265    raeburn  12996:     unless ($thisfn) {
1.620     albertel 12997:         if ($env{'request.symb'}) {
                   12998: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 12999: 	}
1.620     albertel 13000: 	$thisfn=$env{'request.filename'};
1.44      www      13001:     }
1.569     albertel 13002:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13003: # is that filename actually a symb? Verify, clean, and return
                   13004:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13005: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 13006: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13007: 	}
1.242     www      13008:     }
1.44      www      13009:     $thisfn=declutter($thisfn);
1.31      www      13010:     my %hash;
1.37      www      13011:     my %bighash;
                   13012:     my $syval='';
1.620     albertel 13013:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  13014:         my $targetfn = $thisfn;
1.609     banghart 13015:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  13016:             $targetfn = 'adm/wrapper/'.$thisfn;
                   13017:         }
1.687     albertel 13018: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   13019: 	    $targetfn=$1;
                   13020: 	}
1.620     albertel 13021:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 13022:                       &GDBM_READER(),0640)) {
1.481     raeburn  13023: 	    $syval=$hash{$targetfn};
1.37      www      13024:             untie(%hash);
                   13025:         }
                   13026: # ---------------------------------------------------------- There was an entry
                   13027:         if ($syval) {
1.601     albertel 13028: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13029: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13030: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13031: 		    #return $env{$cache_str}='';
1.601     albertel 13032: 		#}    
                   13033: 		#$syval.=$1;
                   13034: 	    #}
1.37      www      13035:         } else {
                   13036: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13037:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13038:                             &GDBM_READER(),0640)) {
1.37      www      13039: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13040:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13041:               unless ($ids) { 
                   13042:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13043:               }
                   13044:               unless ($ids) {
                   13045: # alias?
                   13046: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13047:               }
1.37      www      13048:               if ($ids) {
                   13049: # ------------------------------------------------------------------- Has ID(s)
                   13050:                  my @possibilities=split(/\,/,$ids);
1.39      www      13051:                  if ($#possibilities==0) {
                   13052: # ----------------------------------------------- There is only one possibility
1.37      www      13053: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13054: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13055: 						    $resid,$thisfn);
1.1282    raeburn  13056:                      if (ref($possibles) eq 'HASH') {
                   13057:                          $possibles->{$syval} = 1;    
                   13058:                      }
                   13059:                      if ($checkforblock) {
                   13060:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   13061:                          if (@blockers) {
                   13062:                              $syval = '';
                   13063:                              return;
                   13064:                          }
                   13065:                      }
                   13066:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      13067: # ------------------------------------------ There is more than one possibility
                   13068:                      my $realpossible=0;
1.800     albertel 13069:                      foreach my $id (@possibilities) {
                   13070: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  13071:                          my $canaccess;
                   13072:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13073:                              $canaccess = 1;
                   13074:                          } else { 
                   13075:                              $canaccess = &allowed('bre',$file);
                   13076:                          }
                   13077:                          if ($canaccess) {
                   13078:          		     my ($mapid,$resid)=split(/\./,$id);
                   13079:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13080:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13081: 						             $resid,$thisfn);
                   13082:                                  if (ref($possibles) eq 'HASH') {
                   13083:                                      $possibles->{$syval} = 1;
                   13084:                                  }
                   13085:                                  if ($checkforblock) {
                   13086:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   13087:                                      unless (@blockers > 0) {
                   13088:                                          $syval = $poss_syval;
                   13089:                                          $realpossible++;
                   13090:                                      }
                   13091:                                  } else {
                   13092:                                      $syval = $poss_syval;
                   13093:                                      $realpossible++;
                   13094:                                  }
                   13095:                              }
1.39      www      13096: 			 }
1.191     harris41 13097:                      }
1.39      www      13098: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13099:                  } else {
                   13100:                      $syval='';
1.37      www      13101:                  }
                   13102: 	      }
1.1282    raeburn  13103:               untie(%bighash);
1.481     raeburn  13104:            }
1.31      www      13105:         }
1.62      www      13106:         if ($syval) {
1.620     albertel 13107: 	    return $env{$cache_str}=$syval;
1.62      www      13108:         }
1.31      www      13109:     }
1.949     raeburn  13110:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13111:     return $env{$cache_str}='';
1.31      www      13112: }
                   13113: 
                   13114: # ---------------------------------------------------------- Return random seed
                   13115: 
1.32      www      13116: sub numval {
                   13117:     my $txt=shift;
                   13118:     $txt=~tr/A-J/0-9/;
                   13119:     $txt=~tr/a-j/0-9/;
                   13120:     $txt=~tr/K-T/0-9/;
                   13121:     $txt=~tr/k-t/0-9/;
                   13122:     $txt=~tr/U-Z/0-5/;
                   13123:     $txt=~tr/u-z/0-5/;
                   13124:     $txt=~s/\D//g;
1.564     albertel 13125:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13126:     return int($txt);
1.368     albertel 13127: }
                   13128: 
1.484     albertel 13129: sub numval2 {
                   13130:     my $txt=shift;
                   13131:     $txt=~tr/A-J/0-9/;
                   13132:     $txt=~tr/a-j/0-9/;
                   13133:     $txt=~tr/K-T/0-9/;
                   13134:     $txt=~tr/k-t/0-9/;
                   13135:     $txt=~tr/U-Z/0-5/;
                   13136:     $txt=~tr/u-z/0-5/;
                   13137:     $txt=~s/\D//g;
                   13138:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13139:     my $total;
                   13140:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13141:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13142:     return int($total);
                   13143: }
                   13144: 
1.575     albertel 13145: sub numval3 {
                   13146:     use integer;
                   13147:     my $txt=shift;
                   13148:     $txt=~tr/A-J/0-9/;
                   13149:     $txt=~tr/a-j/0-9/;
                   13150:     $txt=~tr/K-T/0-9/;
                   13151:     $txt=~tr/k-t/0-9/;
                   13152:     $txt=~tr/U-Z/0-5/;
                   13153:     $txt=~tr/u-z/0-5/;
                   13154:     $txt=~s/\D//g;
                   13155:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13156:     my $total;
                   13157:     foreach my $val (@txts) { $total+=$val; }
                   13158:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13159:     return $total;
                   13160: }
                   13161: 
1.675     albertel 13162: sub digest {
                   13163:     my ($data)=@_;
                   13164:     my $digest=&Digest::MD5::md5($data);
                   13165:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13166:     my ($e,$f);
                   13167:     {
                   13168:         use integer;
                   13169:         $e=($a+$b);
                   13170:         $f=($c+$d);
                   13171:         if ($_64bit) {
                   13172:             $e=(($e<<32)>>32);
                   13173:             $f=(($f<<32)>>32);
                   13174:         }
                   13175:     }
                   13176:     if (wantarray) {
                   13177: 	return ($e,$f);
                   13178:     } else {
                   13179: 	my $g;
                   13180: 	{
                   13181: 	    use integer;
                   13182: 	    $g=($e+$f);
                   13183: 	    if ($_64bit) {
                   13184: 		$g=(($g<<32)>>32);
                   13185: 	    }
                   13186: 	}
                   13187: 	return $g;
                   13188:     }
                   13189: }
                   13190: 
1.368     albertel 13191: sub latest_rnd_algorithm_id {
1.675     albertel 13192:     return '64bit5';
1.366     albertel 13193: }
1.32      www      13194: 
1.503     albertel 13195: sub get_rand_alg {
                   13196:     my ($courseid)=@_;
1.790     albertel 13197:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13198:     if ($courseid) {
1.620     albertel 13199: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13200:     }
                   13201:     return &latest_rnd_algorithm_id();
                   13202: }
                   13203: 
1.562     albertel 13204: sub validCODE {
                   13205:     my ($CODE)=@_;
                   13206:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13207:     return 0;
                   13208: }
                   13209: 
1.491     albertel 13210: sub getCODE {
1.620     albertel 13211:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13212:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13213: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13214: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13215: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13216:     }
                   13217:     return undef;
                   13218: }
1.1133    foxr     13219: #
                   13220: #  Determines the random seed for a specific context:
                   13221: #
                   13222: # parameters:
                   13223: #   symb      - in course context the symb for the seed.
                   13224: #   course_id - The course id of the form domain_coursenum.
                   13225: #   domain    - Domain for the user.
                   13226: #   course    - Course for the user.
                   13227: #   cenv      - environment of the course.
                   13228: #
                   13229: # NOTE:
                   13230: #   All parameters are picked out of the environment if missing
                   13231: #   or not defined.
                   13232: #   If a symb cannot be determined the current time is used instead.
                   13233: #
                   13234: #  For a given well defined symb, courside, domain, username,
                   13235: #  and course environment, the seed is reproducible.
                   13236: #
1.31      www      13237: sub rndseed {
1.1133    foxr     13238:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13239:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13240:     if (!defined($symb)) {
1.366     albertel 13241: 	unless ($symb=$wsymb) { return time; }
                   13242:     }
1.1146    foxr     13243:     if (!defined $courseid) { 
                   13244: 	$courseid=$wcourseid; 
                   13245:     }
                   13246:     if (!defined $domain) { $domain=$wdomain; }
                   13247:     if (!defined $username) { $username=$wusername }
1.1133    foxr     13248: 
                   13249:     my $which;
                   13250:     if (defined($cenv->{'rndseed'})) {
                   13251: 	$which = $cenv->{'rndseed'};
                   13252:     } else {
                   13253: 	$which =&get_rand_alg($courseid);
                   13254:     }
1.491     albertel 13255:     if (defined(&getCODE())) {
1.1133    foxr     13256: 
1.675     albertel 13257: 	if ($which eq '64bit5') {
                   13258: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   13259: 	} elsif ($which eq '64bit4') {
1.575     albertel 13260: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   13261: 	} else {
                   13262: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   13263: 	}
1.675     albertel 13264:     } elsif ($which eq '64bit5') {
                   13265: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 13266:     } elsif ($which eq '64bit4') {
                   13267: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 13268:     } elsif ($which eq '64bit3') {
                   13269: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 13270:     } elsif ($which eq '64bit2') {
                   13271: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13272:     } elsif ($which eq '64bit') {
                   13273: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13274:     }
                   13275:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13276: }
                   13277: 
                   13278: sub rndseed_32bit {
                   13279:     my ($symb,$courseid,$domain,$username)=@_;
                   13280:     {
                   13281: 	use integer;
                   13282: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13283: 	my $symbseed=numval($symb) << 22;
                   13284: 	my $namechck=unpack("%32C*",$username) << 17;
                   13285: 	my $nameseed=numval($username) << 12;
                   13286: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13287: 	my $courseseed=unpack("%32C*",$courseid);
                   13288: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13289: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13290: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13291: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13292: 	return $num;
                   13293:     }
                   13294: }
                   13295: 
                   13296: sub rndseed_64bit {
                   13297:     my ($symb,$courseid,$domain,$username)=@_;
                   13298:     {
                   13299: 	use integer;
                   13300: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13301: 	my $symbseed=numval($symb) << 10;
                   13302: 	my $namechck=unpack("%32S*",$username);
                   13303: 	
                   13304: 	my $nameseed=numval($username) << 21;
                   13305: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13306: 	my $courseseed=unpack("%32S*",$courseid);
                   13307: 	
                   13308: 	my $num1=$symbchck+$symbseed+$namechck;
                   13309: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13310: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13311: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13312: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13313: 	return "$num1,$num2";
1.155     albertel 13314:     }
1.366     albertel 13315: }
                   13316: 
1.443     albertel 13317: sub rndseed_64bit2 {
                   13318:     my ($symb,$courseid,$domain,$username)=@_;
                   13319:     {
                   13320: 	use integer;
                   13321: 	# strings need to be an even # of cahracters long, it it is odd the
                   13322:         # last characters gets thrown away
                   13323: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13324: 	my $symbseed=numval($symb) << 10;
                   13325: 	my $namechck=unpack("%32S*",$username.' ');
                   13326: 	
                   13327: 	my $nameseed=numval($username) << 21;
1.501     albertel 13328: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13329: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13330: 	
                   13331: 	my $num1=$symbchck+$symbseed+$namechck;
                   13332: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13333: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13334: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13335: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13336: 	return "$num1,$num2";
                   13337:     }
                   13338: }
                   13339: 
                   13340: sub rndseed_64bit3 {
                   13341:     my ($symb,$courseid,$domain,$username)=@_;
                   13342:     {
                   13343: 	use integer;
                   13344: 	# strings need to be an even # of cahracters long, it it is odd the
                   13345:         # last characters gets thrown away
                   13346: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13347: 	my $symbseed=numval2($symb) << 10;
                   13348: 	my $namechck=unpack("%32S*",$username.' ');
                   13349: 	
                   13350: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13351: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13352: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13353: 	
                   13354: 	my $num1=$symbchck+$symbseed+$namechck;
                   13355: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13356: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13357: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13358: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13359: 	
1.503     albertel 13360: 	return "$num1:$num2";
1.443     albertel 13361:     }
                   13362: }
                   13363: 
1.575     albertel 13364: sub rndseed_64bit4 {
                   13365:     my ($symb,$courseid,$domain,$username)=@_;
                   13366:     {
                   13367: 	use integer;
                   13368: 	# strings need to be an even # of cahracters long, it it is odd the
                   13369:         # last characters gets thrown away
                   13370: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13371: 	my $symbseed=numval3($symb) << 10;
                   13372: 	my $namechck=unpack("%32S*",$username.' ');
                   13373: 	
                   13374: 	my $nameseed=numval3($username) << 21;
                   13375: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13376: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13377: 	
                   13378: 	my $num1=$symbchck+$symbseed+$namechck;
                   13379: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13380: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13381: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13382: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13383: 	
1.575     albertel 13384: 	return "$num1:$num2";
                   13385:     }
                   13386: }
                   13387: 
1.675     albertel 13388: sub rndseed_64bit5 {
                   13389:     my ($symb,$courseid,$domain,$username)=@_;
                   13390:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13391:     return "$num1:$num2";
                   13392: }
                   13393: 
1.366     albertel 13394: sub rndseed_CODE_64bit {
                   13395:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13396:     {
1.366     albertel 13397: 	use integer;
1.443     albertel 13398: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13399: 	my $symbseed=numval2($symb);
1.491     albertel 13400: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13401: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13402: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13403: 	my $num1=$symbseed+$CODEchck;
                   13404: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13405: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13406: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13407: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13408: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13409: 	return "$num1:$num2";
1.366     albertel 13410:     }
                   13411: }
                   13412: 
1.575     albertel 13413: sub rndseed_CODE_64bit4 {
                   13414:     my ($symb,$courseid,$domain,$username)=@_;
                   13415:     {
                   13416: 	use integer;
                   13417: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13418: 	my $symbseed=numval3($symb);
                   13419: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13420: 	my $CODEseed=numval3(&getCODE());
                   13421: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13422: 	my $num1=$symbseed+$CODEchck;
                   13423: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13424: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13425: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13426: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13427: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13428: 	return "$num1:$num2";
                   13429:     }
                   13430: }
                   13431: 
1.675     albertel 13432: sub rndseed_CODE_64bit5 {
                   13433:     my ($symb,$courseid,$domain,$username)=@_;
                   13434:     my $code = &getCODE();
                   13435:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13436:     return "$num1:$num2";
                   13437: }
                   13438: 
1.366     albertel 13439: sub setup_random_from_rndseed {
                   13440:     my ($rndseed)=@_;
1.503     albertel 13441:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  13442:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13443:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13444:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13445:         } else {
                   13446:             &Math::Random::random_set_seed($num1,$num2);
                   13447:         }
1.366     albertel 13448:     } else {
                   13449: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13450:     }
1.36      albertel 13451: }
                   13452: 
1.474     albertel 13453: sub latest_receipt_algorithm_id {
1.835     albertel 13454:     return 'receipt3';
1.474     albertel 13455: }
                   13456: 
1.480     www      13457: sub recunique {
                   13458:     my $fucourseid=shift;
                   13459:     my $unique;
1.835     albertel 13460:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13461: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13462: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13463:     } else {
                   13464: 	$unique=$perlvar{'lonReceipt'};
                   13465:     }
                   13466:     return unpack("%32C*",$unique);
                   13467: }
                   13468: 
                   13469: sub recprefix {
                   13470:     my $fucourseid=shift;
                   13471:     my $prefix;
1.835     albertel 13472:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13473: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13474: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13475:     } else {
                   13476: 	$prefix=$perlvar{'lonHostID'};
                   13477:     }
                   13478:     return unpack("%32C*",$prefix);
                   13479: }
                   13480: 
1.76      www      13481: sub ireceipt {
1.474     albertel 13482:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13483: 
                   13484:     my $return =&recprefix($fucourseid).'-';
                   13485: 
                   13486:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13487: 	$env{'request.state'} eq 'construct') {
                   13488: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13489: 	return $return;
                   13490:     }
                   13491: 
1.76      www      13492:     my $cuname=unpack("%32C*",$funame);
                   13493:     my $cudom=unpack("%32C*",$fudom);
                   13494:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13495:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13496:     my $cunique=&recunique($fucourseid);
1.474     albertel 13497:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13498:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13499: 
1.790     albertel 13500: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13501: 			       
                   13502: 	$return.= ($cunique%$cuname+
                   13503: 		   $cunique%$cudom+
                   13504: 		   $cusymb%$cuname+
                   13505: 		   $cusymb%$cudom+
                   13506: 		   $cucourseid%$cuname+
                   13507: 		   $cucourseid%$cudom+
                   13508: 		   $cpart%$cuname+
                   13509: 		   $cpart%$cudom);
                   13510:     } else {
                   13511: 	$return.= ($cunique%$cuname+
                   13512: 		   $cunique%$cudom+
                   13513: 		   $cusymb%$cuname+
                   13514: 		   $cusymb%$cudom+
                   13515: 		   $cucourseid%$cuname+
                   13516: 		   $cucourseid%$cudom);
                   13517:     }
                   13518:     return $return;
1.76      www      13519: }
                   13520: 
                   13521: sub receipt {
1.474     albertel 13522:     my ($part)=@_;
1.790     albertel 13523:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13524:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13525: }
1.260     ng       13526: 
1.790     albertel 13527: sub whichuser {
                   13528:     my ($passedsymb)=@_;
                   13529:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13530:     if (defined($env{'form.grade_symb'})) {
                   13531: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13532: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13533: 	if (!$allowed &&
                   13534: 	    exists($env{'request.course.sec'}) &&
                   13535: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13536: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13537: 			      '/'.$env{'request.course.sec'});
                   13538: 	}
                   13539: 	if ($allowed) {
                   13540: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13541: 	    $courseid=$tmp_courseid;
                   13542: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13543: 	    ($name)=&get_env_multiple('form.grade_username');
                   13544: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13545: 	}
                   13546:     }
                   13547:     if (!$passedsymb) {
                   13548: 	$symb=&symbread();
                   13549:     } else {
                   13550: 	$symb=$passedsymb;
                   13551:     }
                   13552:     $courseid=$env{'request.course.id'};
                   13553:     $domain=$env{'user.domain'};
                   13554:     $name=$env{'user.name'};
                   13555:     if ($name eq 'public' && $domain eq 'public') {
                   13556: 	if (!defined($env{'form.username'})) {
                   13557: 	    $env{'form.username'}.=time.rand(10000000);
                   13558: 	}
                   13559: 	$name.=$env{'form.username'};
                   13560:     }
                   13561:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13562: 
                   13563: }
                   13564: 
1.36      albertel 13565: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13566: # returns either the contents of the file or 
                   13567: # -1 if the file doesn't exist
1.481     raeburn  13568: #
                   13569: # if the target is a file that was uploaded via DOCS, 
                   13570: # a check will be made to see if a current copy exists on the local server,
                   13571: # if it does this will be served, otherwise a copy will be retrieved from
                   13572: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13573: # the local server.   
1.472     albertel 13574: 
1.36      albertel 13575: sub getfile {
1.538     albertel 13576:     my ($file) = @_;
1.609     banghart 13577:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13578:     &repcopy($file);
                   13579:     return &readfile($file);
                   13580: }
                   13581: 
                   13582: sub repcopy_userfile {
                   13583:     my ($file)=@_;
1.1142    raeburn  13584:     my $londocroot = $perlvar{'lonDocRoot'};
                   13585:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13586:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13587:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13588: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13589:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13590:     if (-e "$file") {
1.828     www      13591: # we already have a local copy, check it out
1.538     albertel 13592: 	my @fileinfo = stat($file);
1.828     www      13593: 	my $rtncode;
                   13594: 	my $info;
1.538     albertel 13595: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13596: 	if ($lwpresp ne 'ok') {
1.828     www      13597: # there is no such file anymore, even though we had a local copy
1.482     albertel 13598: 	    if ($rtncode eq '404') {
1.538     albertel 13599: 		unlink($file);
1.482     albertel 13600: 	    }
                   13601: 	    return -1;
                   13602: 	}
                   13603: 	if ($info < $fileinfo[9]) {
1.828     www      13604: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13605: 	    return 'ok';
1.828     www      13606: 	} else {
                   13607: # the file is outdated, get rid of it
                   13608: 	    unlink($file);
1.482     albertel 13609: 	}
1.828     www      13610:     }
                   13611: # one way or the other, at this point, we don't have the file
                   13612: # construct the correct path for the file
                   13613:     my @parts = ($cdom,$cnum); 
                   13614:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13615: 	push @parts, split(/\//,$1);
                   13616:     }
                   13617:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13618:     foreach my $part (@parts) {
                   13619: 	$path .= '/'.$part;
                   13620: 	if (!-e $path) {
                   13621: 	    mkdir($path,0770);
1.482     albertel 13622: 	}
                   13623:     }
1.828     www      13624: # now the path exists for sure
                   13625: # get a user agent
                   13626:     my $transferfile=$file.'.in.transfer';
                   13627: # FIXME: this should flock
                   13628:     if (-e $transferfile) { return 'ok'; }
                   13629:     my $request;
                   13630:     $uri=~s/^\///;
1.980     raeburn  13631:     my $homeserver = &homeserver($cnum,$cdom);
1.1398    raeburn  13632:     my $hostname = &hostname($homeserver);
1.980     raeburn  13633:     my $protocol = $protocol{$homeserver};
                   13634:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  13635:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345    raeburn  13636:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      13637: # did it work?
                   13638:     if ($response->is_error()) {
                   13639: 	unlink($transferfile);
                   13640: 	&logthis("Userfile repcopy failed for $uri");
                   13641: 	return -1;
                   13642:     }
                   13643: # worked, rename the transfer file
                   13644:     rename($transferfile,$file);
1.607     raeburn  13645:     return 'ok';
1.481     raeburn  13646: }
                   13647: 
1.517     albertel 13648: sub tokenwrapper {
                   13649:     my $uri=shift;
1.980     raeburn  13650:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13651:     $uri=~s|^/||;
1.620     albertel 13652:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13653:     my $token=$1;
1.552     albertel 13654:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13655:     if ($udom && $uname && $file) {
                   13656: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13657:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13658:         my $homeserver = &homeserver($uname,$udom);
1.1397    raeburn  13659:         my $hostname = &hostname($homeserver);
1.980     raeburn  13660:         my $protocol = $protocol{$homeserver};
                   13661:         $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  13662:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13663:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13664:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13665:     } else {
                   13666:         return '/adm/notfound.html';
                   13667:     }
                   13668: }
                   13669: 
1.828     www      13670: # call with reqtype HEAD: get last modification time
                   13671: # call with reqtype GET: get the file contents
                   13672: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13673: #
1.481     raeburn  13674: sub getuploaded {
                   13675:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13676:     $uri=~s/^\///;
1.980     raeburn  13677:     my $homeserver = &homeserver($cnum,$cdom);
1.1397    raeburn  13678:     my $hostname = &hostname($homeserver);
1.980     raeburn  13679:     my $protocol = $protocol{$homeserver};
                   13680:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  13681:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13682:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  13683:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  13684:     $$rtncode = $response->code;
1.482     albertel 13685:     if (! $response->is_success()) {
                   13686: 	return 'failed';
                   13687:     }      
                   13688:     if ($reqtype eq 'HEAD') {
1.486     www      13689: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13690:     } elsif ($reqtype eq 'GET') {
                   13691: 	$$info = $response->content;
1.472     albertel 13692:     }
1.482     albertel 13693:     return 'ok';
1.36      albertel 13694: }
                   13695: 
1.481     raeburn  13696: sub readfile {
                   13697:     my $file = shift;
                   13698:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13699:     my $fh;
1.1359    raeburn  13700:     open($fh,"<",$file);
1.481     raeburn  13701:     my $a='';
1.800     albertel 13702:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13703:     return $a;
                   13704: }
                   13705: 
1.36      albertel 13706: sub filelocation {
1.590     banghart 13707:     my ($dir,$file) = @_;
                   13708:     my $location;
                   13709:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13710: 
                   13711:     if ($file =~ m-^/adm/-) {
                   13712: 	$file=~s-^/adm/wrapper/-/-;
                   13713: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13714:     }
1.882     albertel 13715: 
1.1139    www      13716:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13717:         $location = $file;
1.609     banghart 13718:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13719:         my ($udom,$uname,$filename)=
1.811     albertel 13720:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13721:         my $home=&homeserver($uname,$udom);
                   13722:         my $is_me=0;
                   13723:         my @ids=&current_machine_ids();
                   13724:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13725:         if ($is_me) {
1.1117    foxr     13726:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13727:         } else {
                   13728:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13729:   	      $udom.'/'.$uname.'/'.$filename;
                   13730:         }
1.882     albertel 13731:     } elsif ($file =~ m-^/adm/-) {
                   13732: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13733:     } else {
                   13734:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13735:         $file=~s:^/(res|priv)/:/:;
                   13736:         my $space=$1;
1.590     banghart 13737:         if ( !( $file =~ m:^/:) ) {
                   13738:             $location = $dir. '/'.$file;
                   13739:         } else {
1.1142    raeburn  13740:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13741:         }
1.59      albertel 13742:     }
1.590     banghart 13743:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13744:     while ($location=~m{/\.\./}) {
                   13745: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13746: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13747: 	} else {
                   13748: 	    $location=~ s{/\.\./}{/}g;
                   13749: 	}
                   13750:     } #remove dir/..
1.590     banghart 13751:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13752:     return $location;
1.46      www      13753: }
1.36      albertel 13754: 
1.46      www      13755: sub hreflocation {
                   13756:     my ($dir,$file)=@_;
1.980     raeburn  13757:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13758: 	$file=filelocation($dir,$file);
1.700     albertel 13759:     } elsif ($file=~m-^/adm/-) {
                   13760: 	$file=~s-^/adm/wrapper/-/-;
                   13761: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13762:     }
                   13763:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13764: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13765:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13766: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13767: 	        {/uploaded/$1/$2/}x;
1.46      www      13768:     }
1.913     albertel 13769:     if ($file=~ m{^/userfiles/}) {
                   13770: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13771:     }
1.462     albertel 13772:     return $file;
1.465     albertel 13773: }
                   13774: 
1.1139    www      13775: 
                   13776: 
                   13777: 
                   13778: 
1.465     albertel 13779: sub current_machine_domains {
1.853     albertel 13780:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13781: }
                   13782: 
                   13783: sub machine_domains {
                   13784:     my ($hostname) = @_;
1.465     albertel 13785:     my @domains;
1.838     albertel 13786:     my %hostname = &all_hostnames();
1.465     albertel 13787:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13788: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13789: 	if ($hostname eq $name) {
1.844     albertel 13790: 	    push(@domains,&host_domain($id));
1.465     albertel 13791: 	}
                   13792:     }
                   13793:     return @domains;
                   13794: }
                   13795: 
                   13796: sub current_machine_ids {
1.853     albertel 13797:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13798: }
                   13799: 
                   13800: sub machine_ids {
                   13801:     my ($hostname) = @_;
                   13802:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13803:     my @ids;
1.888     albertel 13804:     my %name_to_host = &all_names();
1.889     albertel 13805:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13806: 	return @{ $name_to_host{$hostname} };
                   13807:     }
                   13808:     return;
1.31      www      13809: }
                   13810: 
1.824     raeburn  13811: sub additional_machine_domains {
                   13812:     my @domains;
1.1359    raeburn  13813:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13814:     while( my $line = <$fh>) {
                   13815:         $line =~ s/\s//g;
                   13816:         push(@domains,$line);
                   13817:     }
                   13818:     return @domains;
                   13819: }
                   13820: 
                   13821: sub default_login_domain {
                   13822:     my $domain = $perlvar{'lonDefDomain'};
                   13823:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13824:     foreach my $posdom (&current_machine_domains(),
                   13825:                         &additional_machine_domains()) {
                   13826:         if (lc($posdom) eq lc($testdomain)) {
                   13827:             $domain=$posdom;
                   13828:             last;
                   13829:         }
                   13830:     }
                   13831:     return $domain;
                   13832: }
                   13833: 
1.1398    raeburn  13834: sub uses_sts {
                   13835:     my ($ignore_cache) = @_;
                   13836:     my $lonhost = $perlvar{'lonHostID'};
                   13837:     my $hostname = &hostname($lonhost);
                   13838:     my $sts_on;
                   13839:     if ($protocol{$lonhost} eq 'https') {
                   13840:         my $cachetime = 12*3600;
                   13841:         if (!$ignore_cache) {
                   13842:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13843:             if (defined($cached)) {
                   13844:                 return $sts_on;
                   13845:             }
                   13846:         }
                   13847:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13848:         my $request=new HTTP::Request('HEAD',$url);
                   13849:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
                   13850:         if ($response->is_success) {
                   13851:             my $has_sts = $response->header('Strict-Transport-Security');
                   13852:             if ($has_sts eq '') {
                   13853:                 $sts_on = 0;
                   13854:             } else {
                   13855:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13856:                     my $maxage = $1;
                   13857:                     if ($maxage) {
                   13858:                         $sts_on = 1;
                   13859:                     } else {
                   13860:                         $sts_on = 0;
                   13861:                     }
                   13862:                 } else {
                   13863:                     $sts_on = 0;
                   13864:                 }
                   13865:             }
                   13866:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13867:         }
                   13868:     }
                   13869:     return;
                   13870: }
                   13871: 
1.31      www      13872: # ------------------------------------------------------------- Declutters URLs
                   13873: 
                   13874: sub declutter {
                   13875:     my $thisfn=shift;
1.569     albertel 13876:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  13877:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13878:         $thisfn=~s{^/home/httpd/html}{};
                   13879:     }
1.31      www      13880:     $thisfn=~s/^\///;
1.697     albertel 13881:     $thisfn=~s|^adm/wrapper/||;
                   13882:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13883:     $thisfn=~s/^res\///;
1.1172    bisitz   13884:     $thisfn=~s/^priv\///;
1.1032    raeburn  13885:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13886:         $thisfn=~s/\?.+$//;
                   13887:     }
1.268     www      13888:     return $thisfn;
                   13889: }
                   13890: 
                   13891: # ------------------------------------------------------------- Clutter up URLs
                   13892: 
                   13893: sub clutter {
                   13894:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13895:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13896: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13897:        $thisfn='/res'.$thisfn; 
                   13898:     }
1.1031    raeburn  13899:     if ($thisfn !~m|^/adm|) {
                   13900: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13901: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13902: 	} else {
                   13903: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13904: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13905: 	    if ($embstyle eq 'ssi'
                   13906: 		|| ($embstyle eq 'hdn')
                   13907: 		|| ($embstyle eq 'rat')
                   13908: 		|| ($embstyle eq 'prv')
                   13909: 		|| ($embstyle eq 'ign')) {
                   13910: 		#do nothing with these
                   13911: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13912: 		|| ($embstyle eq 'emb')
                   13913: 		|| ($embstyle eq 'wrp')) {
                   13914: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13915: 	    } elsif ($embstyle eq 'unk'
                   13916: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13917: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13918: 	    } else {
1.718     www      13919: #		&logthis("Got a blank emb style");
1.695     albertel 13920: 	    }
1.694     albertel 13921: 	}
1.1343    raeburn  13922:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  13923:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13924:     }
1.31      www      13925:     return $thisfn;
1.12      www      13926: }
                   13927: 
1.787     albertel 13928: sub clutter_with_no_wrapper {
                   13929:     my $uri = &clutter(shift);
                   13930:     if ($uri =~ m-^/adm/-) {
                   13931: 	$uri =~ s-^/adm/wrapper/-/-;
                   13932: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13933:     }
                   13934:     return $uri;
                   13935: }
                   13936: 
1.557     albertel 13937: sub freeze_escape {
                   13938:     my ($value)=@_;
                   13939:     if (ref($value)) {
                   13940: 	$value=&nfreeze($value);
                   13941: 	return '__FROZEN__'.&escape($value);
                   13942:     }
                   13943:     return &escape($value);
                   13944: }
                   13945: 
1.11      www      13946: 
1.557     albertel 13947: sub thaw_unescape {
                   13948:     my ($value)=@_;
                   13949:     if ($value =~ /^__FROZEN__/) {
                   13950: 	substr($value,0,10,undef);
                   13951: 	$value=&unescape($value);
                   13952: 	return &thaw($value);
                   13953:     }
                   13954:     return &unescape($value);
                   13955: }
                   13956: 
1.436     albertel 13957: sub correct_line_ends {
                   13958:     my ($result)=@_;
                   13959:     $$result =~s/\r\n/\n/mg;
                   13960:     $$result =~s/\r/\n/mg;
1.415     albertel 13961: }
1.1       albertel 13962: # ================================================================ Main Program
                   13963: 
1.184     www      13964: sub goodbye {
1.204     albertel 13965:    &logthis("Starting Shut down");
1.443     albertel 13966: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13967:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13968: #converted
1.599     albertel 13969: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13970:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13971: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13972: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13973: #1.1 only
1.870     albertel 13974: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13975: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13976: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13977: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13978:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13979:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13980:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13981:    &flushcourselogs();
                   13982:    &logthis("Shutting down");
                   13983: }
                   13984: 
1.852     albertel 13985: sub get_dns {
1.1210    raeburn  13986:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13987:     if (!$ignore_cache) {
                   13988: 	my ($content,$cached)=
                   13989: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13990: 	if ($cached) {
1.1210    raeburn  13991: 	    &$func($content,$hashref);
1.869     albertel 13992: 	    return;
                   13993: 	}
                   13994:     }
                   13995: 
                   13996:     my %alldns;
1.1379    raeburn  13997:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13998:         foreach my $dns (<$config>) {
                   13999: 	    next if ($dns !~ /^\^(\S*)/x);
                   14000:             my $line = $1;
                   14001:             my ($host,$protocol) = split(/:/,$line);
                   14002:             if ($protocol ne 'https') {
                   14003:                 $protocol = 'http';
                   14004:             }
                   14005: 	    $alldns{$host} = $protocol;
1.979     raeburn  14006:         }
1.1379    raeburn  14007:         close($config);
1.869     albertel 14008:     }
                   14009:     while (%alldns) {
1.1263    raeburn  14010: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979     raeburn  14011: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345    raeburn  14012:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979     raeburn  14013:         delete($alldns{$dns});
1.852     albertel 14014: 	next if ($response->is_error());
1.1379    raeburn  14015:         if ($url eq '/adm/dns/loncapaCRL') {
                   14016:             return &$func($response);
                   14017:         } else {
                   14018: 	    my @content = split("\n",$response->content);
                   14019: 	    unless ($nocache) {
                   14020: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   14021: 	    }
                   14022: 	    &$func(\@content,$hashref);
                   14023:             return;
                   14024:         }
                   14025:     }
                   14026:     my $which = (split('/',$url,4))[3];
                   14027:     if ($which eq 'loncapaCRL') {
                   14028:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   14029:         if (-e $diskfile) {
                   14030:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   14031:         } else {
                   14032:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   14033:         }
                   14034:     } else {
                   14035:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   14036:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   14037:             my @content = <$config>;
                   14038:             close($config);
                   14039:             &$func(\@content,$hashref);
                   14040:         }
1.852     albertel 14041:     }
1.1210    raeburn  14042:     return;
                   14043: }
                   14044: 
                   14045: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  14046: sub parse_dns_checksums_tab {
1.1210    raeburn  14047:     my ($lines,$hashref) = @_;
1.1264    raeburn  14048:     my $lonhost = $perlvar{'lonHostID'};
                   14049:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  14050:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  14051:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14052:     my $webconfdir = '/etc/httpd/conf';
                   14053:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14054:         $webconfdir = '/etc/apache2';
                   14055:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14056:         if ($1 >= 10) {
                   14057:             $webconfdir = '/etc/apache2';
                   14058:         }
                   14059:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14060:         if ($1 >= 10.0) {
                   14061:             $webconfdir = '/etc/apache2';
                   14062:         }
                   14063:     }
1.1210    raeburn  14064:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14065:     my (%chksum,%revnum);
                   14066:     if (ref($lines) eq 'ARRAY') {
                   14067:         chomp(@{$lines});
1.1238    raeburn  14068:         my $version = shift(@{$lines});
                   14069:         if ($version eq $release) {  
1.1210    raeburn  14070:             foreach my $line (@{$lines}) {
1.1238    raeburn  14071:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  14072:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14073:                     if ($webconfdir eq '/etc/apache2') {
                   14074:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14075:                     }
                   14076:                 }
1.1238    raeburn  14077:                 $chksum{$file} = $shasum;
                   14078:                 $revnum{$file} = $version;
1.1210    raeburn  14079:             }
                   14080:             if (ref($hashref) eq 'HASH') {
                   14081:                 %{$hashref} = (
                   14082:                                 sums     => \%chksum,
                   14083:                                 versions => \%revnum,
                   14084:                               );
                   14085:             }
                   14086:         }
                   14087:     }
1.869     albertel 14088:     return;
1.852     albertel 14089: }
1.1210    raeburn  14090: 
                   14091: sub fetch_dns_checksums {
1.1238    raeburn  14092:     my %checksums;
                   14093:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  14094:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  14095:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14096:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  14097:              \%checksums);
1.1210    raeburn  14098:     return \%checksums;
                   14099: }
                   14100: 
1.1379    raeburn  14101: sub fetch_crl_pemfile {
                   14102:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   14103: }
                   14104: 
                   14105: sub save_crl_pem {
                   14106:     my ($response) = @_;
1.1380    raeburn  14107:     my ($msg,$hadchanges);
1.1379    raeburn  14108:     if (ref($response)) {
                   14109:         my $now = time;
                   14110:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   14111:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   14112:         if (open(my $fh,'>',"$tmpcrl")) {
                   14113:             print $fh $response->content;
                   14114:             close($fh);
                   14115:             if (-e $lonca) {
                   14116:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   14117:                     my $check = <PIPE>;
                   14118:                     close(PIPE);
                   14119:                     chomp($check);
                   14120:                     if ($check eq 'verify OK') {
                   14121:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  14122:                         my $backup;
1.1379    raeburn  14123:                         if (-e $dest) {
1.1380    raeburn  14124:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   14125:                                 $backup = 'ok';
                   14126:                             }
1.1379    raeburn  14127:                         }
                   14128:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   14129:                             $msg = 'ok';
1.1380    raeburn  14130:                             if ($backup) {
                   14131:                                 my (%oldnums,%newnums);
                   14132:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   14133:                                     while (<PIPE>) {
                   14134:                                         $oldnums{(split(/:/))[1]} = 1;
                   14135:                                     }
                   14136:                                     close(PIPE);
                   14137:                                 }
                   14138:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   14139:                                     while(<PIPE>) {
                   14140:                                         $newnums{(split(/:/))[1]} = 1;
                   14141:                                     }
                   14142:                                     close(PIPE);
                   14143:                                 }
                   14144:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   14145:                                     unless (exists($oldnums{$key})) {
                   14146:                                         $hadchanges = 1;
                   14147:                                         last;
                   14148:                                     }
                   14149:                                 }
                   14150:                                 unless ($hadchanges) {
                   14151:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   14152:                                         unless (exists($newnums{$key})) {
                   14153:                                             $hadchanges = 1;
                   14154:                                             last;
                   14155:                                         }
                   14156:                                     }
                   14157:                                 }
                   14158:                             }
1.1379    raeburn  14159:                         }
                   14160:                     } else {
                   14161:                         unlink($tmpcrl);
                   14162:                     }
                   14163:                 } else {
                   14164:                     unlink($tmpcrl);
                   14165:                 }
                   14166:             } else {
                   14167:                 unlink($tmpcrl);
                   14168:             }
                   14169:         }
                   14170:     }
1.1380    raeburn  14171:     return ($msg,$hadchanges);
1.1379    raeburn  14172: }
                   14173: 
1.327     albertel 14174: # ------------------------------------------------------------ Read domain file
                   14175: {
1.852     albertel 14176:     my $loaded;
1.846     albertel 14177:     my %domain;
                   14178: 
1.852     albertel 14179:     sub parse_domain_tab {
                   14180: 	my ($lines) = @_;
                   14181: 	foreach my $line (@$lines) {
                   14182: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      14183: 
1.846     albertel 14184: 	    chomp($line);
1.852     albertel 14185: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 14186: 	    my %this_domain;
                   14187: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   14188: 			       'lang_def', 'city', 'longi', 'lati',
                   14189: 			       'primary') {
                   14190: 		$this_domain{$field} = shift(@elements);
                   14191: 	    }
                   14192: 	    $domain{$name} = \%this_domain;
1.852     albertel 14193: 	}
                   14194:     }
1.864     albertel 14195: 
                   14196:     sub reset_domain_info {
                   14197: 	undef($loaded);
                   14198: 	undef(%domain);
                   14199:     }
                   14200: 
1.852     albertel 14201:     sub load_domain_tab {
1.1293    raeburn  14202: 	my ($ignore_cache,$nocache) = @_;
                   14203: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 14204: 	my $fh;
1.1359    raeburn  14205: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 14206: 	    my @lines = <$fh>;
                   14207: 	    &parse_domain_tab(\@lines);
1.448     albertel 14208: 	}
1.852     albertel 14209: 	close($fh);
                   14210: 	$loaded = 1;
1.327     albertel 14211:     }
1.846     albertel 14212: 
                   14213:     sub domain {
1.852     albertel 14214: 	&load_domain_tab() if (!$loaded);
                   14215: 
1.846     albertel 14216: 	my ($name,$what) = @_;
                   14217: 	return if ( !exists($domain{$name}) );
                   14218: 
                   14219: 	if (!$what) {
                   14220: 	    return $domain{$name}{'description'};
                   14221: 	}
                   14222: 	return $domain{$name}{$what};
                   14223:     }
1.974     raeburn  14224: 
                   14225:     sub domain_info {
                   14226:         &load_domain_tab() if (!$loaded);
                   14227:         return %domain;
                   14228:     }
                   14229: 
1.327     albertel 14230: }
                   14231: 
                   14232: 
1.1       albertel 14233: # ------------------------------------------------------------- Read hosts file
                   14234: {
1.838     albertel 14235:     my %hostname;
1.844     albertel 14236:     my %hostdom;
1.845     albertel 14237:     my %libserv;
1.852     albertel 14238:     my $loaded;
1.888     albertel 14239:     my %name_to_host;
1.1074    raeburn  14240:     my %internetdom;
1.1107    raeburn  14241:     my %LC_dns_serv;
1.852     albertel 14242: 
                   14243:     sub parse_hosts_tab {
                   14244: 	my ($file) = @_;
                   14245: 	foreach my $configline (@$file) {
                   14246: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  14247:             chomp($configline);
                   14248: 	    if ($configline =~ /^\^/) {
                   14249:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   14250:                     $LC_dns_serv{$1} = 1;
                   14251:                 }
                   14252:                 next;
                   14253:             }
1.1074    raeburn  14254: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 14255: 	    $name=~s/\s//g;
                   14256: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  14257:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   14258:                     my $curr = $hostname{$id};
                   14259:                     my $skip;
                   14260:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   14261:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   14262:                             $skip = 1;
                   14263:                         } else {
                   14264:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   14265:                         }
                   14266:                     }
                   14267:                     unless ($skip) {
                   14268:                         push(@{$name_to_host{$name}},$id);
                   14269:                     }
                   14270:                 } else {
                   14271:                     push(@{$name_to_host{$name}},$id);
                   14272:                 }
1.852     albertel 14273: 		$hostname{$id}=$name;
                   14274: 		$hostdom{$id}=$domain;
                   14275: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  14276:                 if (defined($protocol)) {
                   14277:                     if ($protocol eq 'https') {
                   14278:                         $protocol{$id} = $protocol;
                   14279:                     } else {
                   14280:                         $protocol{$id} = 'http'; 
                   14281:                     }
1.968     raeburn  14282:                 } else {
1.969     raeburn  14283:                     $protocol{$id} = 'http';
1.968     raeburn  14284:                 }
1.1074    raeburn  14285:                 if (defined($intdom)) {
                   14286:                     $internetdom{$id} = $intdom;
                   14287:                 }
1.852     albertel 14288: 	    }
                   14289: 	}
                   14290:     }
1.864     albertel 14291:     
                   14292:     sub reset_hosts_info {
1.897     albertel 14293: 	&purge_remembered();
1.864     albertel 14294: 	&reset_domain_info();
                   14295: 	&reset_hosts_ip_info();
1.1339    raeburn  14296:         undef(%internetdom);
1.892     albertel 14297: 	undef(%name_to_host);
1.864     albertel 14298: 	undef(%hostname);
                   14299: 	undef(%hostdom);
                   14300: 	undef(%libserv);
                   14301: 	undef($loaded);
                   14302:     }
1.1       albertel 14303: 
1.852     albertel 14304:     sub load_hosts_tab {
1.1293    raeburn  14305: 	my ($ignore_cache,$nocache) = @_;
                   14306: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  14307: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 14308: 	my @config = <$config>;
                   14309: 	&parse_hosts_tab(\@config);
                   14310: 	close($config);
                   14311: 	$loaded=1;
1.1       albertel 14312:     }
1.852     albertel 14313: 
1.838     albertel 14314:     sub hostname {
1.852     albertel 14315: 	&load_hosts_tab() if (!$loaded);
                   14316: 
1.838     albertel 14317: 	my ($lonid) = @_;
                   14318: 	return $hostname{$lonid};
                   14319:     }
1.845     albertel 14320: 
1.838     albertel 14321:     sub all_hostnames {
1.852     albertel 14322: 	&load_hosts_tab() if (!$loaded);
                   14323: 
1.838     albertel 14324: 	return %hostname;
                   14325:     }
1.845     albertel 14326: 
1.888     albertel 14327:     sub all_names {
1.1293    raeburn  14328:         my ($ignore_cache,$nocache) = @_;
                   14329: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 14330: 
                   14331: 	return %name_to_host;
                   14332:     }
                   14333: 
1.974     raeburn  14334:     sub all_host_domain {
                   14335:         &load_hosts_tab() if (!$loaded);
                   14336:         return %hostdom;
                   14337:     }
                   14338: 
1.1339    raeburn  14339:     sub all_host_intdom {
                   14340:         &load_hosts_tab() if (!$loaded);
                   14341:         return %internetdom;
                   14342:     }
                   14343: 
1.845     albertel 14344:     sub is_library {
1.852     albertel 14345: 	&load_hosts_tab() if (!$loaded);
                   14346: 
1.845     albertel 14347: 	return exists($libserv{$_[0]});
                   14348:     }
                   14349: 
                   14350:     sub all_library {
1.852     albertel 14351: 	&load_hosts_tab() if (!$loaded);
                   14352: 
1.845     albertel 14353: 	return %libserv;
                   14354:     }
                   14355: 
1.1062    droeschl 14356:     sub unique_library {
                   14357: 	#2x reverse removes all hostnames that appear more than once
                   14358:         my %unique = reverse &all_library();
                   14359:         return reverse %unique;
                   14360:     }
                   14361: 
1.841     albertel 14362:     sub get_servers {
1.852     albertel 14363: 	&load_hosts_tab() if (!$loaded);
                   14364: 
1.841     albertel 14365: 	my ($domain,$type) = @_;
                   14366: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14367: 	                                          : %hostname;
                   14368: 	my %result;
1.842     albertel 14369: 	if (ref($domain) eq 'ARRAY') {
                   14370: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14371: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14372: 		    $result{$host} = $hostname;
                   14373: 		}
                   14374: 	    }
                   14375: 	} else {
                   14376: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14377: 		if ($hostdom{$host} eq $domain) {
                   14378: 		    $result{$host} = $hostname;
                   14379: 		}
1.841     albertel 14380: 	    }
                   14381: 	}
                   14382: 	return %result;
                   14383:     }
1.845     albertel 14384: 
1.1062    droeschl 14385:     sub get_unique_servers {
                   14386:         my %unique = reverse &get_servers(@_);
                   14387: 	return reverse %unique;
                   14388:     }
                   14389: 
1.844     albertel 14390:     sub host_domain {
1.852     albertel 14391: 	&load_hosts_tab() if (!$loaded);
                   14392: 
1.844     albertel 14393: 	my ($lonid) = @_;
                   14394: 	return $hostdom{$lonid};
                   14395:     }
                   14396: 
1.841     albertel 14397:     sub all_domains {
1.852     albertel 14398: 	&load_hosts_tab() if (!$loaded);
                   14399: 
1.841     albertel 14400: 	my %seen;
                   14401: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14402: 	return @uniq;
                   14403:     }
1.1074    raeburn  14404: 
                   14405:     sub internet_dom {
                   14406:         &load_hosts_tab() if (!$loaded);
                   14407: 
                   14408:         my ($lonid) = @_;
                   14409:         return $internetdom{$lonid};
                   14410:     }
1.1107    raeburn  14411: 
                   14412:     sub is_LC_dns {
                   14413:         &load_hosts_tab() if (!$loaded);
                   14414: 
                   14415:         my ($hostname) = @_;
                   14416:         return exists($LC_dns_serv{$hostname});
                   14417:     }
                   14418: 
1.1       albertel 14419: }
                   14420: 
1.847     albertel 14421: { 
                   14422:     my %iphost;
1.856     albertel 14423:     my %name_to_ip;
                   14424:     my %lonid_to_ip;
1.869     albertel 14425: 
1.847     albertel 14426:     sub get_hosts_from_ip {
                   14427: 	my ($ip) = @_;
                   14428: 	my %iphosts = &get_iphost();
                   14429: 	if (ref($iphosts{$ip})) {
                   14430: 	    return @{$iphosts{$ip}};
                   14431: 	}
                   14432: 	return;
1.839     albertel 14433:     }
1.864     albertel 14434:     
                   14435:     sub reset_hosts_ip_info {
                   14436: 	undef(%iphost);
                   14437: 	undef(%name_to_ip);
                   14438: 	undef(%lonid_to_ip);
                   14439:     }
1.856     albertel 14440: 
                   14441:     sub get_host_ip {
                   14442: 	my ($lonid) = @_;
                   14443: 	if (exists($lonid_to_ip{$lonid})) {
                   14444: 	    return $lonid_to_ip{$lonid};
                   14445: 	}
                   14446: 	my $name=&hostname($lonid);
                   14447:    	my $ip = gethostbyname($name);
                   14448: 	return if (!$ip || length($ip) ne 4);
                   14449: 	$ip=inet_ntoa($ip);
                   14450: 	$name_to_ip{$name}   = $ip;
                   14451: 	$lonid_to_ip{$lonid} = $ip;
                   14452: 	return $ip;
                   14453:     }
1.847     albertel 14454:     
                   14455:     sub get_iphost {
1.1293    raeburn  14456: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14457: 
1.869     albertel 14458: 	if (!$ignore_cache) {
                   14459: 	    if (%iphost) {
                   14460: 		return %iphost;
                   14461: 	    }
                   14462: 	    my ($ip_info,$cached)=
                   14463: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14464: 	    if ($cached) {
                   14465: 		%iphost      = %{$ip_info->[0]};
                   14466: 		%name_to_ip  = %{$ip_info->[1]};
                   14467: 		%lonid_to_ip = %{$ip_info->[2]};
                   14468: 		return %iphost;
                   14469: 	    }
                   14470: 	}
1.894     albertel 14471: 
                   14472: 	# get yesterday's info for fallback
                   14473: 	my %old_name_to_ip;
                   14474: 	my ($ip_info,$cached)=
                   14475: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14476: 	if ($cached) {
                   14477: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14478: 	}
                   14479: 
1.1293    raeburn  14480: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14481: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14482: 	    my $ip;
                   14483: 	    if (!exists($name_to_ip{$name})) {
                   14484: 		$ip = gethostbyname($name);
                   14485: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14486: 		    if (defined($old_name_to_ip{$name})) {
                   14487: 			$ip = $old_name_to_ip{$name};
                   14488: 			&logthis("Can't find $name defaulting to old $ip");
                   14489: 		    } else {
                   14490: 			&logthis("Name $name no IP found");
                   14491: 			next;
                   14492: 		    }
                   14493: 		} else {
                   14494: 		    $ip=inet_ntoa($ip);
1.847     albertel 14495: 		}
                   14496: 		$name_to_ip{$name} = $ip;
                   14497: 	    } else {
                   14498: 		$ip = $name_to_ip{$name};
1.653     albertel 14499: 	    }
1.888     albertel 14500: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14501: 		$lonid_to_ip{$id} = $ip;
                   14502: 	    }
                   14503: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14504: 	}
1.1293    raeburn  14505:         unless ($nocache) {
                   14506: 	    &do_cache_new('iphost','iphost',
                   14507: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14508: 		          48*60*60);
                   14509:         }
1.869     albertel 14510: 
1.847     albertel 14511: 	return %iphost;
1.598     albertel 14512:     }
                   14513: 
1.992     raeburn  14514:     #
                   14515:     #  Given a DNS returns the loncapa host name for that DNS 
                   14516:     # 
                   14517:     sub host_from_dns {
                   14518:         my ($dns) = @_;
                   14519:         my @hosts;
                   14520:         my $ip;
                   14521: 
1.993     raeburn  14522:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14523:             $ip = $name_to_ip{$dns};
                   14524:         }
                   14525:         if (!$ip) {
                   14526:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14527:             if (length($ip) == 4) { 
                   14528: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14529:             }
                   14530:         }
                   14531:         if ($ip) {
                   14532: 	    @hosts = get_hosts_from_ip($ip);
                   14533: 	    return $hosts[0];
                   14534:         }
                   14535:         return undef;
1.986     foxr     14536:     }
1.992     raeburn  14537: 
1.1074    raeburn  14538:     sub get_internet_names {
                   14539:         my ($lonid) = @_;
                   14540:         return if ($lonid eq '');
                   14541:         my ($idnref,$cached)=
                   14542:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14543:         if ($cached) {
                   14544:             return $idnref;
                   14545:         }
                   14546:         my $ip = &get_host_ip($lonid);
                   14547:         my @hosts = &get_hosts_from_ip($ip);
                   14548:         my %iphost = &get_iphost();
                   14549:         my (@idns,%seen);
                   14550:         foreach my $id (@hosts) {
                   14551:             my $dom = &host_domain($id);
                   14552:             my $prim_id = &domain($dom,'primary');
                   14553:             my $prim_ip = &get_host_ip($prim_id);
                   14554:             next if ($seen{$prim_ip});
                   14555:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14556:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14557:                     my $intdom = &internet_dom($id);
                   14558:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14559:                         push(@idns,$intdom);
                   14560:                     }
                   14561:                 }
                   14562:             }
                   14563:             $seen{$prim_ip} = 1;
                   14564:         }
1.1219    raeburn  14565:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14566:     }
                   14567: 
1.986     foxr     14568: }
                   14569: 
1.1079    raeburn  14570: sub all_loncaparevs {
1.1249    raeburn  14571:     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  14572: }
                   14573: 
1.1227    raeburn  14574: # ---------------------------------------------------------- Read loncaparev table
                   14575: {
                   14576:     sub load_loncaparevs { 
                   14577:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  14578:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  14579:                 while (my $configline=<$config>) {
                   14580:                     chomp($configline);
                   14581:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14582:                     $loncaparevs{$hostid}=$loncaparev;
                   14583:                 }
                   14584:                 close($config);
                   14585:             }
                   14586:         }
                   14587:     }
                   14588: }
                   14589: 
                   14590: # ---------------------------------------------------------- Read serverhostID table
                   14591: {
                   14592:     sub load_serverhomeIDs {
                   14593:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  14594:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  14595:                 while (my $configline=<$config>) {
                   14596:                     chomp($configline);
                   14597:                     my ($name,$id)=split(/:/,$configline);
                   14598:                     $serverhomeIDs{$name}=$id;
                   14599:                 }
                   14600:                 close($config);
                   14601:             }
                   14602:         }
                   14603:     }
                   14604: }
                   14605: 
                   14606: 
1.862     albertel 14607: BEGIN {
                   14608: 
                   14609: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14610:     unless ($readit) {
                   14611: {
                   14612:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14613:     %perlvar = (%perlvar,%{$configvars});
                   14614: }
                   14615: 
                   14616: 
1.1       albertel 14617: # ------------------------------------------------------ Read spare server file
                   14618: {
1.1359    raeburn  14619:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14620: 
                   14621:     while (my $configline=<$config>) {
                   14622:        chomp($configline);
1.284     matthew  14623:        if ($configline) {
1.784     albertel 14624: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14625: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14626: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14627:        }
                   14628:     }
1.448     albertel 14629:     close($config);
1.1       albertel 14630: }
1.11      www      14631: # ------------------------------------------------------------ Read permissions
                   14632: {
1.1359    raeburn  14633:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14634: 
                   14635:     while (my $configline=<$config>) {
1.448     albertel 14636: 	chomp($configline);
                   14637: 	if ($configline) {
                   14638: 	    my ($role,$perm)=split(/ /,$configline);
                   14639: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14640: 	}
1.11      www      14641:     }
1.448     albertel 14642:     close($config);
1.11      www      14643: }
                   14644: 
                   14645: # -------------------------------------------- Read plain texts for permissions
                   14646: {
1.1359    raeburn  14647:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14648: 
                   14649:     while (my $configline=<$config>) {
1.448     albertel 14650: 	chomp($configline);
                   14651: 	if ($configline) {
1.742     raeburn  14652: 	    my ($short,@plain)=split(/:/,$configline);
                   14653:             %{$prp{$short}} = ();
                   14654: 	    if (@plain > 0) {
                   14655:                 $prp{$short}{'std'} = $plain[0];
                   14656:                 for (my $i=1; $i<@plain; $i++) {
                   14657:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14658:                 }
                   14659:             }
1.448     albertel 14660: 	}
1.135     www      14661:     }
1.448     albertel 14662:     close($config);
1.135     www      14663: }
                   14664: 
                   14665: # ---------------------------------------------------------- Read package table
                   14666: {
1.1359    raeburn  14667:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14668: 
                   14669:     while (my $configline=<$config>) {
1.483     albertel 14670: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14671: 	chomp($configline);
                   14672: 	my ($short,$plain)=split(/:/,$configline);
                   14673: 	my ($pack,$name)=split(/\&/,$short);
                   14674: 	if ($plain ne '') {
                   14675: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14676: 	    $packagetab{$short}=$plain; 
                   14677: 	}
1.11      www      14678:     }
1.448     albertel 14679:     close($config);
1.329     matthew  14680: }
                   14681: 
1.1073    raeburn  14682: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  14683: 
                   14684: &load_loncaparevs();
1.1073    raeburn  14685: 
1.1074    raeburn  14686: # ---------------------------------------------------------- Read serverhostID table
                   14687: 
1.1227    raeburn  14688: &load_serverhomeIDs();
                   14689: 
                   14690: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14691: {
                   14692:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14693:     if (-e $file) {
                   14694:         my $parser = HTML::LCParser->new($file);
                   14695:         while (my $token = $parser->get_token()) {
                   14696:             if ($token->[0] eq 'S') {
                   14697:                 my $item = $token->[1];
                   14698:                 my $name = $token->[2]{'name'};
                   14699:                 my $value = $token->[2]{'value'};
1.1285    raeburn  14700:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  14701:                 my $namematch = $token->[2]{'namematch'};
                   14702:                 if ($item eq 'parameter') {
                   14703:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   14704:                         my $release = $parser->get_text();
                   14705:                         $release =~ s/(^\s*|\s*$ )//gx;
                   14706:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   14707:                     }
                   14708:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  14709:                     my $release = $parser->get_text();
                   14710:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  14711:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  14712:                 }
                   14713:             }
                   14714:         }
                   14715:     }
1.1073    raeburn  14716: }
                   14717: 
1.1138    raeburn  14718: # ---------------------------------------------------------- Read managers table
                   14719: {
                   14720:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  14721:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14722:             while (my $configline=<$config>) {
                   14723:                 chomp($configline);
                   14724:                 next if ($configline =~ /^\#/);
                   14725:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14726:                     $managerstab{$configline} = 1;
                   14727:                 }
                   14728:             }
                   14729:             close($config);
                   14730:         }
                   14731:     }
                   14732: }
                   14733: 
1.329     matthew  14734: # ------------- set up temporary directory
                   14735: {
1.1117    foxr     14736:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14737: 
1.11      www      14738: }
                   14739: 
1.794     albertel 14740: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14741: 				'compress_threshold'=> 20_000,
                   14742:  			        });
1.185     www      14743: 
1.281     www      14744: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14745: $dumpcount=0;
1.958     www      14746: $locknum=0;
1.22      www      14747: 
1.163     harris41 14748: &logtouch();
1.672     albertel 14749: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14750: $readit=1;
1.564     albertel 14751:     {
                   14752: 	use integer;
                   14753: 	my $test=(2**32)+1;
1.568     albertel 14754: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14755: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14756:     }
1.195     www      14757: }
1.1       albertel 14758: }
1.179     www      14759: 
1.1       albertel 14760: 1;
1.191     harris41 14761: __END__
                   14762: 
1.243     albertel 14763: =pod
                   14764: 
1.191     harris41 14765: =head1 NAME
                   14766: 
1.243     albertel 14767: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14768: 
                   14769: =head1 SYNOPSIS
                   14770: 
1.243     albertel 14771: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14772: 
                   14773:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14774: 
1.243     albertel 14775: Common parameters:
                   14776: 
                   14777: =over 4
                   14778: 
                   14779: =item *
                   14780: 
                   14781: $uname : an internal username (if $cname expecting a course Id specifically)
                   14782: 
                   14783: =item *
                   14784: 
                   14785: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14786: 
                   14787: =item *
                   14788: 
                   14789: $symb : a resource instance identifier
                   14790: 
                   14791: =item *
                   14792: 
                   14793: $namespace : the name of a .db file that contains the data needed or
                   14794: being set.
                   14795: 
                   14796: =back
                   14797: 
1.394     bowersj2 14798: =head1 OVERVIEW
1.191     harris41 14799: 
1.394     bowersj2 14800: lonnet provides subroutines which interact with the
                   14801: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14802: about classes, users, and resources.
1.243     albertel 14803: 
                   14804: For many of these objects you can also use this to store data about
                   14805: them or modify them in various ways.
1.191     harris41 14806: 
1.394     bowersj2 14807: =head2 Symbs
1.191     harris41 14808: 
1.394     bowersj2 14809: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14810: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14811: map, the resource number of the resource in the map, and the URL of
                   14812: the resource itself. The latter is somewhat redundant, but might help
                   14813: if maps change.
                   14814: 
                   14815: An example is
                   14816: 
                   14817:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14818: 
                   14819: The respective map entry is
                   14820: 
                   14821:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14822:   title="Problem 2">
                   14823:  </resource>
                   14824: 
                   14825: Symbs are used by the random number generator, as well as to store and
                   14826: restore data specific to a certain instance of for example a problem.
                   14827: 
                   14828: =head2 Storing And Retrieving Data
                   14829: 
                   14830: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14831: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14832: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14833: is is the non-critical message twin of cstore. These functions are for
                   14834: handlers to store a perl hash to a user's permanent data space in an
                   14835: easy manner, and to retrieve it again on another call. It is expected
                   14836: that a handler would use this once at the beginning to retrieve data,
                   14837: and then again once at the end to send only the new data back.
                   14838: 
                   14839: The data is stored in the user's data directory on the user's
                   14840: homeserver under the ID of the course.
                   14841: 
                   14842: The hash that is returned by restore will have all of the previous
                   14843: value for all of the elements of the hash.
                   14844: 
                   14845: Example:
                   14846: 
                   14847:  #creating a hash
                   14848:  my %hash;
                   14849:  $hash{'foo'}='bar';
                   14850: 
                   14851:  #storing it
                   14852:  &Apache::lonnet::cstore(\%hash);
                   14853: 
                   14854:  #changing a value
                   14855:  $hash{'foo'}='notbar';
                   14856: 
                   14857:  #adding a new value
                   14858:  $hash{'bar'}='foo';
                   14859:  &Apache::lonnet::cstore(\%hash);
                   14860: 
                   14861:  #retrieving the hash
                   14862:  my %history=&Apache::lonnet::restore();
                   14863: 
                   14864:  #print the hash
                   14865:  foreach my $key (sort(keys(%history))) {
                   14866:    print("\%history{$key} = $history{$key}");
                   14867:  }
                   14868: 
                   14869: Will print out:
1.191     harris41 14870: 
1.394     bowersj2 14871:  %history{1:foo} = bar
                   14872:  %history{1:keys} = foo:timestamp
                   14873:  %history{1:timestamp} = 990455579
                   14874:  %history{2:bar} = foo
                   14875:  %history{2:foo} = notbar
                   14876:  %history{2:keys} = foo:bar:timestamp
                   14877:  %history{2:timestamp} = 990455580
                   14878:  %history{bar} = foo
                   14879:  %history{foo} = notbar
                   14880:  %history{timestamp} = 990455580
                   14881:  %history{version} = 2
                   14882: 
                   14883: Note that the special hash entries C<keys>, C<version> and
                   14884: C<timestamp> were added to the hash. C<version> will be equal to the
                   14885: total number of versions of the data that have been stored. The
                   14886: C<timestamp> attribute will be the UNIX time the hash was
                   14887: stored. C<keys> is available in every historical section to list which
                   14888: keys were added or changed at a specific historical revision of a
                   14889: hash.
                   14890: 
                   14891: B<Warning>: do not store the hash that restore returns directly. This
                   14892: will cause a mess since it will restore the historical keys as if the
                   14893: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14894: 
1.394     bowersj2 14895: Calling convention:
1.191     harris41 14896: 
1.1225    raeburn  14897:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  14898:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14899: 
1.394     bowersj2 14900: For more detailed information, see lonnet specific documentation.
1.191     harris41 14901: 
1.394     bowersj2 14902: =head1 RETURN MESSAGES
1.191     harris41 14903: 
1.394     bowersj2 14904: =over 4
1.191     harris41 14905: 
1.394     bowersj2 14906: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14907: 
1.394     bowersj2 14908: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14909: when the connection is brought back up
1.191     harris41 14910: 
1.394     bowersj2 14911: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14912: for later delivery
1.191     harris41 14913: 
1.967     bisitz   14914: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14915: 
1.394     bowersj2 14916: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14917: that was requested
1.191     harris41 14918: 
1.243     albertel 14919: =back
1.191     harris41 14920: 
1.243     albertel 14921: =head1 PUBLIC SUBROUTINES
1.191     harris41 14922: 
1.243     albertel 14923: =head2 Session Environment Functions
1.191     harris41 14924: 
1.243     albertel 14925: =over 4
1.191     harris41 14926: 
1.394     bowersj2 14927: =item * 
                   14928: X<appenv()>
1.949     raeburn  14929: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14930: the user envirnoment file, and will be restored for each access this
1.620     albertel 14931: user makes during this session, also modifies the %env for the current
1.949     raeburn  14932: process. Optional rolesarrayref - if defined contains a reference to an array
                   14933: of roles which are exempt from the restriction on modifying user.role entries 
                   14934: in the user's environment.db and in %env.    
1.191     harris41 14935: 
                   14936: =item *
1.394     bowersj2 14937: X<delenv()>
1.987     raeburn  14938: B<delenv($delthis,$regexp)>: removes all items from the session
                   14939: environment file that begin with $delthis. If the 
                   14940: optional second arg - $regexp - is true, $delthis is treated as a 
                   14941: regular expression, otherwise \Q$delthis\E is used. 
                   14942: The values are also deleted from the current processes %env.
1.191     harris41 14943: 
1.795     albertel 14944: =item * get_env_multiple($name) 
                   14945: 
                   14946: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14947: values may be defined and end up as an array ref.
                   14948: 
                   14949: returns an array of values
                   14950: 
1.243     albertel 14951: =back
                   14952: 
                   14953: =head2 User Information
1.191     harris41 14954: 
1.243     albertel 14955: =over 4
1.191     harris41 14956: 
                   14957: =item *
1.394     bowersj2 14958: X<queryauthenticate()>
                   14959: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14960: authentication scheme
                   14961: 
                   14962: =item *
1.394     bowersj2 14963: X<authenticate()>
1.1073    raeburn  14964: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14965: authenticate user from domain's lib servers (first use the current
                   14966: one). C<$upass> should be the users password.
1.1073    raeburn  14967: $checkdefauth is optional (value is 1 if a check should be made to
                   14968:    authenticate user using default authentication method, and allow
                   14969:    account creation if username does not have account in the domain).
                   14970: $clientcancheckhost is optional (value is 1 if checking whether the
                   14971:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14972: 
                   14973: =item *
1.394     bowersj2 14974: X<homeserver()>
                   14975: B<homeserver($uname,$udom)>: find the server which has
                   14976: the user's directory and files (there must be only one), this caches
                   14977: the answer, and also caches if there is a borken connection.
1.191     harris41 14978: 
                   14979: =item *
1.394     bowersj2 14980: X<idget()>
1.1300    raeburn  14981: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   14982: a list of student/employee IDs or clicker IDs
                   14983: (student/employee IDs are a unique resource in a domain, there must be 
                   14984: only 1 ID per username, and only 1 username per ID in a specific domain).
                   14985: clickerIDs are not necessarily unique, as students might share clickers.
                   14986: (returns hash: id=>name,id=>name)
1.191     harris41 14987: 
                   14988: =item *
1.394     bowersj2 14989: X<idrget()>
                   14990: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14991: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14992: 
                   14993: =item *
1.394     bowersj2 14994: X<idput()>
1.1300    raeburn  14995: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   14996: names and associated student/employee IDs or clicker IDs.
                   14997: 
                   14998: =item *
                   14999: X<iddel()>
                   15000: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   15001: student/employee ID or clicker ID username look-ups from domain.
                   15002: The homeserver ($uhome) and namespace ($namespace) are optional.
                   15003: If no $uhome is provided, it will be determined usig &homeserver()
                   15004: for each user.  If no $namespace is provided, the default is ids.
                   15005: 
                   15006: =item *
                   15007: X<updateclickers()>
                   15008: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   15009: clicker ID-to-username look-ups in clickers.db on library server.
                   15010: Permitted actions are add or del (i.e., add or delete). The 
                   15011: clickers.db contains clickerID as keys (escaped), and each corresponding
                   15012: value is an escaped comma-separated list of usernames (for whom the
                   15013: library server is the homeserver), who registered that particular ID.
                   15014: If $critical is true, the update will be sent via &critical, otherwise
                   15015: &reply() will be used.
1.191     harris41 15016: 
                   15017: =item *
1.394     bowersj2 15018: X<rolesinit()>
1.1169    droeschl 15019: B<rolesinit($udom,$username)>: get user privileges.
                   15020: returns user role, first access and timer interval hashes
1.243     albertel 15021: 
                   15022: =item *
1.1171    droeschl 15023: X<privileged()>
                   15024: B<privileged($username,$domain)>: returns a true if user has a
                   15025: privileged and active role (i.e. su or dc), false otherwise.
                   15026: 
                   15027: =item *
1.551     albertel 15028: X<getsection()>
                   15029: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 15030: course $cname, return section name/number or '' for "not in course"
                   15031: and '-1' for "no section"
                   15032: 
                   15033: =item *
1.394     bowersj2 15034: X<userenvironment()>
                   15035: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 15036: passed in @what from the requested user's environment, returns a hash
                   15037: 
1.858     raeburn  15038: =item * 
                   15039: X<userlog_query()>
1.859     albertel 15040: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   15041: activity.log file. %filters defines filters applied when parsing the
                   15042: log file. These can be start or end timestamps, or the type of action
                   15043: - log to look for Login or Logout events, check for Checkin or
                   15044: Checkout, role for role selection. The response is in the form
                   15045: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   15046: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  15047: 
1.243     albertel 15048: =back
                   15049: 
                   15050: =head2 User Roles
                   15051: 
                   15052: =over 4
                   15053: 
                   15054: =item *
                   15055: 
1.1284    raeburn  15056: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   15057: returns codes for allowed actions.
                   15058: 
                   15059: The first argument is required, all others are optional.
                   15060: 
                   15061: $priv is the privilege being checked.
                   15062: $uri contains additional information about what is being checked for access (e.g.,
                   15063: URL, course ID etc.). 
                   15064: $symb is the unique resource instance identifier in a course; if needed,
                   15065: but not provided, it will be retrieved via a call to &symbread(). 
                   15066: $role is the role for which a priv is being checked (only used if priv is evb). 
                   15067: $clientip is the user's IP address (only used when checking for access to portfolio 
                   15068: files).
                   15069: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   15070: prevents recursive calls to &allowed.
                   15071: 
1.243     albertel 15072:  F: full access
                   15073:  U,I,K: authentication modes (cxx only)
                   15074:  '': forbidden
                   15075:  1: user needs to choose course
                   15076:  2: browse allowed
1.766     albertel 15077:  A: passphrase authentication needed
1.1284    raeburn  15078:  B: access temporarily blocked because of a blocking event in a course.
1.1402  ! raeburn  15079:  D: access blocked because access is required via session initiated via deep-link 
1.243     albertel 15080: 
                   15081: =item *
                   15082: 
1.1192    raeburn  15083: constructaccess($url,$setpriv) : check for access to construction space URL
                   15084: 
                   15085: See if the owner domain and name in the URL match those in the
                   15086: expected environment.  If so, return three element list
                   15087: ($ownername,$ownerdomain,$ownerhome).
                   15088: 
                   15089: Otherwise return the null string.
                   15090: 
                   15091: If second argument 'setpriv' is true, it assigns the privileges,
                   15092: and returns the same three element list, unless the owner has
                   15093: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   15094: in which case the null string is returned.
                   15095: 
                   15096: =item *
                   15097: 
1.1326    raeburn  15098: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   15099: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   15100: for system, domain, and course level. $uname and $udom are optional (current
                   15101: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 15102: 
                   15103: =item *
                   15104: 
1.988     raeburn  15105: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   15106: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  15107: $type is Course (default) or Community.
1.988     raeburn  15108: If $forcedefault evaluates to true, text returned will be default 
                   15109: text for $type. Otherwise, if this is a course, the text returned 
                   15110: will be a custom name for the role (if defined in the course's 
                   15111: environment).  If no custom name is defined the default is returned.
                   15112:    
1.832     raeburn  15113: =item *
                   15114: 
1.1219    raeburn  15115: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  15116: All arguments are optional. Returns a hash of a roles, either for
                   15117: co-author/assistant author roles for a user's Construction Space
1.906     albertel 15118: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  15119: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   15120: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   15121: For each key, value is set to colon-separated start and end times for
                   15122: the role.  If no username and domain are specified, will default to
1.934     raeburn  15123: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  15124: of role statuses (active, future or previous), roles 
                   15125: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   15126: to restrict the list of roles reported. If no array ref is 
                   15127: provided for types, will default to return only active roles.
1.834     albertel 15128: 
1.1195    raeburn  15129: =item *
                   15130: 
                   15131: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  15132: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   15133: 
                   15134: Additional optional arguments are: $type (if role checking is to be restricted 
                   15135: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  15136: available roles) or future (roles available in the future), and
                   15137: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  15138: have active Domain Coordinator role in course's domain or in additional
                   15139: domains (specified in 'Domains to check for privileged users' in course
                   15140: environment -- set via:  Course Settings -> Classlists and staff listing).
                   15141: 
                   15142: =item *
                   15143: 
                   15144: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   15145: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   15146: $possdomains and $possroles are optional array refs -- to domains to check and
                   15147: roles to check.  If $possdomains is not specified, a dump will be done of the
                   15148: users' roles.db to check for a dc or su role in any domain. This can be
                   15149: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   15150: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   15151: this then allows &privileged_by_domain() to be used, which caches the identity
                   15152: of privileged users, eliminating the need for repeated calls to &dump().
                   15153: 
                   15154: =item *
                   15155: 
                   15156: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15157: where the outer hash keys are domains specified in the $possdomains array ref,
                   15158: next inner hash keys are privileged roles specified in the $roles array ref,
                   15159: and the innermost hash contains key = value pairs for username:domain = end:start
                   15160: for active or future "privileged" users with that role in that domain. To avoid
                   15161: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15162: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  15163: 
1.243     albertel 15164: =back
                   15165: 
                   15166: =head2 User Modification
                   15167: 
                   15168: =over 4
                   15169: 
                   15170: =item *
                   15171: 
1.957     raeburn  15172: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15173: user for the level given by URL.  Optional start and end dates (leave empty
                   15174: string or zero for "no date")
1.191     harris41 15175: 
                   15176: =item *
                   15177: 
1.243     albertel 15178: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15179: change a users, password, possible return values are: ok,
                   15180: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15181: refused
1.191     harris41 15182: 
                   15183: =item *
                   15184: 
1.243     albertel 15185: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15186: 
                   15187: =item *
                   15188: 
1.1058    raeburn  15189: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   15190:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   15191: 
                   15192: will update user information (firstname,middlename,lastname,generation,
                   15193: permanentemail), and if forceid is true, student/employee ID also.
                   15194: A user's institutional affiliation(s) can also be updated.
                   15195: User information fields will not be overwritten with empty entries 
                   15196: unless the field is included in the $candelete array reference.
                   15197: This array is included when a single user is modified via "Manage Users",
                   15198: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 15199: 
                   15200: =item *
                   15201: 
1.286     matthew  15202: modifystudent
                   15203: 
1.957     raeburn  15204: modify a student's enrollment and identification information.
1.1235    raeburn  15205: The course id is resolved based on the current user's environment.  
                   15206: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  15207: associated with a course.
                   15208: 
1.297     matthew  15209: This call is essentially a wrapper for lonnet::modifyuser and
                   15210: lonnet::modify_student_enrollment
1.286     matthew  15211: 
                   15212: Inputs: 
                   15213: 
                   15214: =over 4
                   15215: 
1.957     raeburn  15216: =item B<$udom> Student's loncapa domain
1.286     matthew  15217: 
1.957     raeburn  15218: =item B<$uname> Student's loncapa login name
1.286     matthew  15219: 
1.964     bisitz   15220: =item B<$uid> Student/Employee ID
1.286     matthew  15221: 
1.957     raeburn  15222: =item B<$umode> Student's authentication mode
1.286     matthew  15223: 
1.957     raeburn  15224: =item B<$upass> Student's password
1.286     matthew  15225: 
1.957     raeburn  15226: =item B<$first> Student's first name
1.286     matthew  15227: 
1.957     raeburn  15228: =item B<$middle> Student's middle name
1.286     matthew  15229: 
1.957     raeburn  15230: =item B<$last> Student's last name
1.286     matthew  15231: 
1.957     raeburn  15232: =item B<$gene> Student's generation
1.286     matthew  15233: 
1.957     raeburn  15234: =item B<$usec> Student's section in course
1.286     matthew  15235: 
                   15236: =item B<$end> Unix time of the roles expiration
                   15237: 
                   15238: =item B<$start> Unix time of the roles start date
                   15239: 
                   15240: =item B<$forceid> If defined, allow $uid to be changed
                   15241: 
                   15242: =item B<$desiredhome> server to use as home server for student
                   15243: 
1.957     raeburn  15244: =item B<$email> Student's permanent e-mail address
                   15245: 
                   15246: =item B<$type> Type of enrollment (auto or manual)
                   15247: 
1.963     raeburn  15248: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   15249: 
                   15250: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  15251: 
1.963     raeburn  15252: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  15253: 
1.963     raeburn  15254: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  15255: 
1.1216    raeburn  15256: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   15257: 
                   15258: =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  15259: 
1.286     matthew  15260: =back
1.297     matthew  15261: 
                   15262: =item *
                   15263: 
                   15264: modify_student_enrollment
                   15265: 
1.1235    raeburn  15266: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  15267: 'role.request.course' must be defined for this function to proceed.
                   15268: 
                   15269: Inputs:
                   15270: 
                   15271: =over 4
                   15272: 
1.1235    raeburn  15273: =item $udom, student's domain
1.297     matthew  15274: 
1.1235    raeburn  15275: =item $uname, student's name
1.297     matthew  15276: 
1.1235    raeburn  15277: =item $uid, student's user id
1.297     matthew  15278: 
1.1235    raeburn  15279: =item $first, student's first name
1.297     matthew  15280: 
                   15281: =item $middle
                   15282: 
                   15283: =item $last
                   15284: 
                   15285: =item $gene
                   15286: 
                   15287: =item $usec
                   15288: 
                   15289: =item $end
                   15290: 
                   15291: =item $start
                   15292: 
1.957     raeburn  15293: =item $type
                   15294: 
                   15295: =item $locktype
                   15296: 
                   15297: =item $cid
                   15298: 
                   15299: =item $selfenroll
                   15300: 
                   15301: =item $context
                   15302: 
1.1216    raeburn  15303: =item $credits, number of credits student will earn from this class
                   15304: 
1.1314    raeburn  15305: =item $instsec, institutional course section code for student
                   15306: 
1.297     matthew  15307: =back
                   15308: 
1.191     harris41 15309: 
                   15310: =item *
                   15311: 
1.243     albertel 15312: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   15313: custom role; give a custom role to a user for the level given by URL.  Specify
                   15314: name and domain of role author, and role name
1.191     harris41 15315: 
                   15316: =item *
                   15317: 
1.243     albertel 15318: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 15319: 
                   15320: =item *
                   15321: 
1.243     albertel 15322: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   15323: 
                   15324: =back
                   15325: 
                   15326: =head2 Course Infomation
                   15327: 
                   15328: =over 4
1.191     harris41 15329: 
                   15330: =item *
                   15331: 
1.1118    foxr     15332: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 15333: specified course id, including all environment settings for the
                   15334: course, the description of the course will be in the hash under the
                   15335: key 'description'
1.191     harris41 15336: 
1.1118    foxr     15337: $options is an optional parameter that if supplied is a hash reference that controls
                   15338: what how this function works.  It has the following key/values:
                   15339: 
                   15340: =over 4
                   15341: 
                   15342: =item freshen_cache
                   15343: 
                   15344: If defined, and the environment cache for the course is valid, it is 
                   15345: returned in the returned hash.
                   15346: 
                   15347: =item one_time
                   15348: 
                   15349: If defined, the last cache time is set to _now_
                   15350: 
                   15351: =item user
                   15352: 
                   15353: If defined, the supplied username is used instead of the current user.
                   15354: 
                   15355: 
                   15356: =back
                   15357: 
1.191     harris41 15358: =item *
                   15359: 
1.624     albertel 15360: resdata($name,$domain,$type,@which) : request for current parameter
                   15361: setting for a specific $type, where $type is either 'course' or 'user',
                   15362: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  15363: answers for 10 minutes.
1.243     albertel 15364: 
1.877     foxr     15365: =item *
                   15366: 
                   15367: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15368: data base, returning a hash that is keyed by the resource name and has
                   15369: values that are the resource value.  I believe that the timestamps and
                   15370: versions are also returned.
                   15371: 
1.1236    raeburn  15372: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15373: supplemental content area. This routine caches the number of files for 
                   15374: 10 minutes.
                   15375: 
1.243     albertel 15376: =back
                   15377: 
                   15378: =head2 Course Modification
                   15379: 
                   15380: =over 4
1.191     harris41 15381: 
                   15382: =item *
                   15383: 
1.243     albertel 15384: writecoursepref($courseid,%prefs) : write preferences (environment
                   15385: database) for a course
1.191     harris41 15386: 
                   15387: =item *
                   15388: 
1.1011    raeburn  15389: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15390: 
                   15391: =item *
                   15392: 
1.1038    raeburn  15393: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15394: 
1.1167    droeschl 15395: =item *
                   15396: 
                   15397: is_course($courseid), is_course($cdom, $cnum)
                   15398: 
                   15399: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15400: two component version $cdom, $cnum. It checks if the specified course exists.
                   15401: 
                   15402: Returns:
                   15403:     undef if the course doesn't exist, otherwise
                   15404:     in scalar context the combined courseid.
                   15405:     in list context the two components of the course identifier, domain and 
                   15406:     courseid.    
                   15407: 
1.243     albertel 15408: =back
                   15409: 
1.1401    raeburn  15410: =head2 Bubblesheet Configuration
                   15411: 
                   15412: =over 4
                   15413: 
                   15414: =item *
                   15415: 
                   15416: get_scantron_config($which)
                   15417: 
                   15418: $which - the name of the configuration to parse from the file.
                   15419: 
                   15420: Parses and returns the bubblesheet configuration line selected as a
                   15421: hash of configuration file fields.
                   15422: 
                   15423: 
                   15424: Returns:
                   15425:     If the named configuration is not in the file, an empty
                   15426:     hash is returned.
                   15427: 
                   15428:     a hash with the fields
                   15429:       name         - internal name for the this configuration setup
                   15430:       description  - text to display to operator that describes this config
                   15431:       CODElocation - if 0 or the string 'none'
                   15432:                           - no CODE exists for this config
                   15433:                      if -1 || the string 'letter'
                   15434:                           - a CODE exists for this config and is
                   15435:                             a string of letters
                   15436:                      Unsupported value (but planned for future support)
                   15437:                           if a positive integer
                   15438:                                - The CODE exists as the first n items from
                   15439:                                  the question section of the form
                   15440:                           if the string 'number'
                   15441:                                - The CODE exists for this config and is
                   15442:                                  a string of numbers
                   15443:       CODEstart   - (only matter if a CODE exists) column in the line where
                   15444:                      the CODE starts
                   15445:       CODElength  - length of the CODE
                   15446:       IDstart     - column where the student/employee ID starts
                   15447:       IDlength    - length of the student/employee ID info
                   15448:       Qstart      - column where the information from the bubbled
                   15449:                     'questions' start
                   15450:       Qlength     - number of columns comprising a single bubble line from
                   15451:                     the sheet. (usually either 1 or 10)
                   15452:       Qon         - either a single character representing the character used
                   15453:                     to signal a bubble was chosen in the positional setup, or
                   15454:                     the string 'letter' if the letter of the chosen bubble is
                   15455:                     in the final, or 'number' if a number representing the
                   15456:                     chosen bubble is in the file (1->A 0->J)
                   15457:       Qoff        - the character used to represent that a bubble was
                   15458:                     left blank
                   15459:       PaperID     - if the scanning process generates a unique number for each
                   15460:                     sheet scanned the column that this ID number starts in
                   15461:       PaperIDlength - number of columns that comprise the unique ID number
                   15462:                       for the sheet of paper
                   15463:       FirstName   - column that the first name starts in
                   15464:       FirstNameLength - number of columns that the first name spans
                   15465: 
                   15466:       LastName    - column that the last name starts in
                   15467:       LastNameLength - number of columns that the last name spans
                   15468:       BubblesPerRow - number of bubbles available in each row used to
                   15469:                       bubble an answer. (If not specified, 10 assumed).
                   15470: 
                   15471: 
                   15472: =item *
                   15473: 
                   15474: get_scantronformat_file($cdom)
                   15475: 
                   15476: $cdom - the course's domain (optional); if not supplied, uses
                   15477: domain for current $env{'request.course.id'}.
                   15478: 
                   15479: Returns an array containing lines from the scantron format file for
                   15480: the domain of the course.
                   15481: 
                   15482: If a url for a custom.tab file is listed in domain's configuration.db,
                   15483: lines are from this file.
                   15484: 
                   15485: Otherwise, if a default.tab has been published in RES space by the
                   15486: domainconfig user, lines are from this file.
                   15487: 
                   15488: Otherwise, fall back to getting lines from the legacy file on the
                   15489: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   15490: 
                   15491: =back
                   15492: 
1.243     albertel 15493: =head2 Resource Subroutines
                   15494: 
                   15495: =over 4
1.191     harris41 15496: 
                   15497: =item *
                   15498: 
1.243     albertel 15499: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15500: 
                   15501: =item *
                   15502: 
1.243     albertel 15503: repcopy($filename) : subscribes to the requested file, and attempts to
                   15504: replicate from the owning library server, Might return
1.607     raeburn  15505: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15506: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15507: resource. Expects the local filesystem pathname
                   15508: (/home/httpd/html/res/....)
                   15509: 
                   15510: =back
                   15511: 
                   15512: =head2 Resource Information
                   15513: 
                   15514: =over 4
1.191     harris41 15515: 
                   15516: =item *
                   15517: 
1.1228    raeburn  15518: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15519: and returns the value of a variety of different possible values,
                   15520: $varname should be a request string, and the other parameters can be
                   15521: used to specify who and what one is asking about. Ordinarily, $cid 
                   15522: does not need to be specified, as it is retrived from 
                   15523: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15524: within lonuserstate::loadmap() when initializing a course, before
                   15525: $env{'request.course.id'} has been set, so it needs to be provided
                   15526: in that one case.
1.243     albertel 15527: 
                   15528: Possible values for $varname are environment.lastname (or other item
                   15529: from the envirnment hash), user.name (or someother aspect about the
                   15530: user), resource.0.maxtries (or some other part and parameter of a
                   15531: resource)
1.204     albertel 15532: 
                   15533: =item *
                   15534: 
1.243     albertel 15535: directcondval($number) : get current value of a condition; reads from a state
                   15536: string
1.204     albertel 15537: 
                   15538: =item *
                   15539: 
1.243     albertel 15540: condval($condidx) : value of condition index based on state
1.204     albertel 15541: 
                   15542: =item *
                   15543: 
1.1362    raeburn  15544: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 15545: resource's metadata, $what should be either a specific key, or either
                   15546: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  15547: packages that this resource currently uses, the last 3 arguments are 
                   15548: only used internally for recursive metadata.
                   15549: 
                   15550: the toolsymb is only used where the uri is for an external tool (for which
                   15551: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 15552: 
1.1371    raeburn  15553: this function automatically caches all requests except any made recursively
                   15554: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   15555: defined).
1.191     harris41 15556: 
                   15557: =item *
                   15558: 
1.243     albertel 15559: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15560: network of library servers; returns file handle of where SQL and regex results
                   15561: will be stored for query
1.191     harris41 15562: 
                   15563: =item *
                   15564: 
1.1282    raeburn  15565: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   15566: return symbolic list entry (all arguments optional). 
                   15567: 
                   15568: Args: filename is the filename (including path) for the file for which a symb 
                   15569: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   15570: to check access status if more than one resource was found in the bighash 
                   15571: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   15572: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   15573: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15574: cause possible symbs to be checked to determine if they are subject to content
                   15575: blocking, if so they will not be included as possible symbs; possibles is a
                   15576: ref to a hash, which, as a side effect, will be populated with all possible 
                   15577: symbs (content blocking not tested).
                   15578:  
1.243     albertel 15579: returns the data handle
1.191     harris41 15580: 
                   15581: =item *
                   15582: 
1.1190    raeburn  15583: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   15584: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15585: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  15586: on failure, user must be in a course, as it assumes the existence of
                   15587: the course initial hash, and uses $env('request.course.id'}.  The third
                   15588: arg is an optional reference to a scalar.  If this arg is passed in the 
                   15589: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15590: encrypted; otherwise it will be null.  
1.191     harris41 15591: 
                   15592: =item *
                   15593: 
1.243     albertel 15594: symbclean($symb) : removes versions numbers from a symb, returns the
                   15595: cleaned symb
1.191     harris41 15596: 
                   15597: =item *
                   15598: 
1.243     albertel 15599: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15600: course map, user must be in a course for it to work.
1.191     harris41 15601: 
                   15602: =item *
                   15603: 
1.243     albertel 15604: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15605: 
                   15606: =item *
                   15607: 
1.243     albertel 15608: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15609: a random seed, all arguments are optional, if they aren't sent it uses the
                   15610: environment to derive them. Note: if symb isn't sent and it can't get one
                   15611: from &symbread it will use the current time as its return value
1.191     harris41 15612: 
                   15613: =item *
                   15614: 
1.243     albertel 15615: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15616: unfakeable, receipt
1.191     harris41 15617: 
                   15618: =item *
                   15619: 
1.620     albertel 15620: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15621: 
                   15622: =item *
                   15623: 
1.243     albertel 15624: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15625: 
                   15626: =item *
                   15627: 
1.243     albertel 15628: 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 15629: 
                   15630: =item *
                   15631: 
1.243     albertel 15632: 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 15633: 
                   15634: =item *
                   15635: 
1.243     albertel 15636: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15637: 
                   15638: =item *
                   15639: 
1.243     albertel 15640: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15641: forcing spreadsheet to reevaluate the resource scores next time.
                   15642: 
1.1195    raeburn  15643: =item * 
                   15644: 
1.1196    raeburn  15645: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15646: when viewing in course context.
1.1195    raeburn  15647: 
1.1196    raeburn  15648:  input: six args -- filename (decluttered), course number, course domain,
                   15649:                     url, symb (if registered) and group (if this is a 
                   15650:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  15651: 
1.1196    raeburn  15652:  output: array of five scalars --
1.1195    raeburn  15653:          $cfile -- url for file editing if editable on current server
                   15654:          $home -- homeserver of resource (i.e., for author if published,
                   15655:                                           or course if uploaded.).
                   15656:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  15657:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   15658:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  15659: 
                   15660: =item *
                   15661: 
                   15662: is_course_upload($file,$cnum,$cdom)
                   15663: 
                   15664: Used in course context to determine if current file was uploaded to 
                   15665: the course (i.e., would be found in /userfiles/docs on the course's 
                   15666: homeserver.
                   15667: 
                   15668:   input: 3 args -- filename (decluttered), course number and course domain.
                   15669:   output: boolean -- 1 if file was uploaded.
                   15670: 
1.243     albertel 15671: =back
                   15672: 
                   15673: =head2 Storing/Retreiving Data
                   15674: 
                   15675: =over 4
1.191     harris41 15676: 
                   15677: =item *
                   15678: 
1.1269    raeburn  15679: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   15680: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15681: the remaining args aren't required and if they aren't passed or are '' they will
                   15682: be derived from the env (with the exception of $laststore, which is an 
                   15683: optional arg used when a user's submission is stored in grading).
                   15684: $laststore is $version=$timestamp, where $version is the most recent version
                   15685: number retrieved for the corresponding $symb in the $namespace db file, and
                   15686: $timestamp is the timestamp for that transaction (UNIX time).
                   15687: $laststore is currently only passed when cstore() is called by 
                   15688: structuretags::finalize_storage().
1.191     harris41 15689: 
                   15690: =item *
                   15691: 
1.1269    raeburn  15692: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   15693: but uses critical subroutine
1.191     harris41 15694: 
                   15695: =item *
                   15696: 
1.243     albertel 15697: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15698: all args are optional
1.191     harris41 15699: 
                   15700: =item *
                   15701: 
1.717     albertel 15702: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15703: dumps the complete (or key matching regexp) namespace into a hash
                   15704: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15705: normally &store()ed into
                   15706: 
                   15707: $range should be either an integer '100' (give me the first 100
                   15708:                                            matching records)
                   15709:               or be  two integers sperated by a - with no spaces
                   15710:                  '30-50' (give me the 30th through the 50th matching
                   15711:                           records)
                   15712: 
                   15713: 
                   15714: =item *
                   15715: 
1.1269    raeburn  15716: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15717: replaces a &store() version of data with a replacement set of data
                   15718: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  15719: reference. If $tolog is true, the transaction is logged in the courselog
                   15720: with an action=PUTSTORE.
1.717     albertel 15721: 
                   15722: =item *
                   15723: 
1.243     albertel 15724: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15725: works very similar to store/cstore, but all data is stored in a
                   15726: temporary location and can be reset using tmpreset, $storehash should
                   15727: be a hash reference, returns nothing on success
1.191     harris41 15728: 
                   15729: =item *
                   15730: 
1.243     albertel 15731: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15732: similar to restore, but all data is stored in a temporary location and
                   15733: can be reset using tmpreset. Returns a hash of values on success,
                   15734: error string otherwise.
1.191     harris41 15735: 
                   15736: =item *
                   15737: 
1.243     albertel 15738: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15739: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15740: 
                   15741: =item *
                   15742: 
1.243     albertel 15743: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15744: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15745: 
                   15746: =item *
                   15747: 
1.243     albertel 15748: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15749: namesp ($udom and $uname are optional)
1.191     harris41 15750: 
                   15751: =item *
                   15752: 
1.702     albertel 15753: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15754: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15755: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15756: 
1.702     albertel 15757: $range should be either an integer '100' (give me the first 100
                   15758:                                            matching records)
                   15759:               or be  two integers sperated by a - with no spaces
                   15760:                  '30-50' (give me the 30th through the 50th matching
                   15761:                           records)
1.449     matthew  15762: =item *
                   15763: 
                   15764: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15765: $store can be a scalar, an array reference, or if the amount to be 
                   15766: incremented is > 1, a hash reference.
                   15767: 
                   15768: ($udom and $uname are optional)
1.191     harris41 15769: 
                   15770: =item *
                   15771: 
1.243     albertel 15772: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15773: ($udom and $uname are optional)
1.191     harris41 15774: 
                   15775: =item *
                   15776: 
1.243     albertel 15777: cput($namespace,$storehash,$udom,$uname) : critical put
                   15778: ($udom and $uname are optional)
1.191     harris41 15779: 
                   15780: =item *
                   15781: 
1.748     albertel 15782: newput($namespace,$storehash,$udom,$uname) :
                   15783: 
                   15784: Attempts to store the items in the $storehash, but only if they don't
                   15785: currently exist, if this succeeds you can be certain that you have 
                   15786: successfully created a new key value pair in the $namespace db.
                   15787: 
                   15788: 
                   15789: Args:
                   15790:  $namespace: name of database to store values to
                   15791:  $storehash: hashref to store to the db
                   15792:  $udom: (optional) domain of user containing the db
                   15793:  $uname: (optional) name of user caontaining the db
                   15794: 
                   15795: Returns:
                   15796:  'ok' -> succeeded in storing all keys of $storehash
                   15797:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15798:                         least <key> already existed in the db (other
                   15799:                         requested keys may also already exist)
1.967     bisitz   15800:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15801:  'con_lost' -> unable to contact request server
                   15802:  'refused' -> action was not allowed by remote machine
                   15803: 
                   15804: 
                   15805: =item *
                   15806: 
1.243     albertel 15807: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15808: reference filled in from namesp (encrypts the return communication)
                   15809: ($udom and $uname are optional)
1.191     harris41 15810: 
                   15811: =item *
                   15812: 
1.243     albertel 15813: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15814: critical subroutine
                   15815: 
1.806     raeburn  15816: =item *
                   15817: 
1.860     raeburn  15818: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15819: array reference filled in from namespace found in domain level on either
                   15820: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15821: 
                   15822: =item *
                   15823: 
1.860     raeburn  15824: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15825: domain level either on specified domain server ($uhome) or primary domain 
                   15826: server ($udom and $uhome are optional)
1.806     raeburn  15827: 
1.943     raeburn  15828: =item * 
                   15829: 
1.1240    raeburn  15830: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   15831: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15832: the target domain.
                   15833: 
                   15834: May also include additional key => value pairs for the following groups:
                   15835: 
                   15836: =over
                   15837: 
                   15838: =item
                   15839: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15840: 
                   15841: =over
                   15842: 
                   15843: =item defaultquota, authorquota
                   15844: 
                   15845: =back
                   15846: 
                   15847: =item
                   15848: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15849: portfolio for users).
                   15850: 
                   15851: =over
                   15852: 
                   15853: =item
                   15854: aboutme, blog, webdav, portfolio
                   15855: 
                   15856: =back
                   15857: 
                   15858: =item
                   15859: requestcourses: ability to request courses, and how requests are processed.
                   15860: 
                   15861: =over
                   15862: 
                   15863: =item
1.1305    raeburn  15864: official, unofficial, community, textbook, placement
1.1240    raeburn  15865: 
                   15866: =back
                   15867: 
                   15868: =item
                   15869: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15870: 
                   15871: =over
                   15872: 
                   15873: =item
1.1256    raeburn  15874: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  15875: 
                   15876: =back
                   15877: 
                   15878: =item
                   15879: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15880: for course's uploaded content.
                   15881: 
                   15882: =over
                   15883: 
                   15884: =item
1.1246    raeburn  15885: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  15886: communityquota, textbookquota, placementquota
1.1240    raeburn  15887: 
                   15888: =back
                   15889: 
                   15890: =item
                   15891: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15892: on your servers.
                   15893: 
                   15894: =over
                   15895: 
                   15896: =item 
                   15897: remotesessions, hostedsessions
                   15898: 
                   15899: =back
                   15900: 
                   15901: =back
                   15902: 
                   15903: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15904: utility to create a configuration.db file on a domain's primary library server 
                   15905: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15906: -- corresponding values are authentication type (internal, krb4, krb5,
                   15907: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   15908: will be available. Values are retrieved from cache (if current), unless the
                   15909: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15910: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15911: 
                   15912: Typical usage:
1.943     raeburn  15913: 
1.1240    raeburn  15914: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15915: 
1.243     albertel 15916: =back
                   15917: 
                   15918: =head2 Network Status Functions
                   15919: 
                   15920: =over 4
1.191     harris41 15921: 
                   15922: =item *
                   15923: 
1.1137    raeburn  15924: dirlist() : return directory list based on URI (first arg).
                   15925: 
                   15926: Inputs: 1 required, 5 optional.
                   15927: 
                   15928: =over
                   15929: 
                   15930: =item 
                   15931: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15932: 
                   15933: =item
                   15934: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15935: 
                   15936: =item
                   15937: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15938: 
                   15939: =item
                   15940: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15941: 
                   15942: =item
                   15943: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15944: 
                   15945: =item 
                   15946: $alternateRoot - path to prepend in place of path from $uri.
                   15947: 
                   15948: =back
                   15949: 
                   15950: Returns: Array of up to two items.
                   15951: 
                   15952: =over
                   15953: 
                   15954: a reference to an array of files/subdirectories
                   15955: 
                   15956: =over
                   15957: 
                   15958: Each element in the array of files/subdirectories is a & separated list of
                   15959: item name and the result of running stat on the item.  If dirlist was requested
                   15960: for a file instead of a directory, the item name will be ''. For a directory 
                   15961: listing, if the item is a metadata file, the element will end &N&M 
                   15962: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15963: default copyright set (1).  
                   15964: 
                   15965: =back
                   15966: 
                   15967: a scalar containing error condition (if encountered).
                   15968: 
                   15969: =over
                   15970: 
                   15971: =item 
                   15972: no_host (no homeserver identified for $username:$domain).
                   15973: 
                   15974: =item 
                   15975: no_such_host (server contacted for listing not identified as valid host).
                   15976: 
                   15977: =item 
                   15978: con_lost (connection to remote server failed).
                   15979: 
                   15980: =item 
                   15981: refused (invalid $username:$domain received on lond side).
                   15982: 
                   15983: =item 
                   15984: no_such_dir (directory at specified path on lond side does not exist). 
                   15985: 
                   15986: =item 
                   15987: empty (directory at specified path on lond side is empty).
                   15988: 
                   15989: =over
                   15990: 
                   15991: This is currently not encountered because the &ls3, &ls2, 
                   15992: &ls (_handler) routines on the lond side do not filter out
                   15993: . and .. from a directory listing. 
                   15994: 
                   15995: =back
                   15996: 
                   15997: =back
                   15998: 
                   15999: =back
1.191     harris41 16000: 
                   16001: =item *
                   16002: 
1.243     albertel 16003: spareserver() : find server with least workload from spare.tab
                   16004: 
1.986     foxr     16005: 
                   16006: =item *
                   16007: 
                   16008: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   16009: if there is no corresponding loncapa host.
                   16010: 
1.243     albertel 16011: =back
                   16012: 
1.986     foxr     16013: 
1.243     albertel 16014: =head2 Apache Request
                   16015: 
                   16016: =over 4
1.191     harris41 16017: 
                   16018: =item *
                   16019: 
1.243     albertel 16020: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   16021: localhost, posts hash
                   16022: 
                   16023: =back
                   16024: 
                   16025: =head2 Data to String to Data
                   16026: 
                   16027: =over 4
1.191     harris41 16028: 
                   16029: =item *
                   16030: 
1.243     albertel 16031: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   16032: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 16033: 
                   16034: =item *
                   16035: 
1.243     albertel 16036: hashref2str($hashref) : convert a hashref into a string complete with
                   16037: escaping and '=' and '&' separators, supports elements that are
                   16038: arrayrefs and hashrefs
1.191     harris41 16039: 
                   16040: =item *
                   16041: 
1.243     albertel 16042: arrayref2str($arrayref) : convert an arrayref into a string complete
                   16043: with escaping and '&' separators, supports elements that are arrayrefs
                   16044: and hashrefs
1.191     harris41 16045: 
                   16046: =item *
                   16047: 
1.243     albertel 16048: str2hash($string) : convert string to hash using unescaping and
                   16049: splitting on '=' and '&', supports elements that are arrayrefs and
                   16050: hashrefs
1.191     harris41 16051: 
                   16052: =item *
                   16053: 
1.243     albertel 16054: str2array($string) : convert string to hash using unescaping and
                   16055: splitting on '&', supports elements that are arrayrefs and hashrefs
                   16056: 
                   16057: =back
                   16058: 
                   16059: =head2 Logging Routines
                   16060: 
                   16061: 
                   16062: These routines allow one to make log messages in the lonnet.log and
                   16063: lonnet.perm logfiles.
1.191     harris41 16064: 
1.1119    foxr     16065: =over 4
                   16066: 
1.191     harris41 16067: =item *
                   16068: 
1.243     albertel 16069: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 16070: 
                   16071: =item *
                   16072: 
1.243     albertel 16073: logthis() : append message to the normal lonnet.log file, it gets
                   16074: preiodically rolled over and deleted.
1.191     harris41 16075: 
                   16076: =item *
                   16077: 
1.243     albertel 16078: logperm() : append a permanent message to lonnet.perm.log, this log
                   16079: file never gets deleted by any automated portion of the system, only
                   16080: messages of critical importance should go in here.
                   16081: 
1.1119    foxr     16082: 
1.243     albertel 16083: =back
                   16084: 
                   16085: =head2 General File Helper Routines
                   16086: 
                   16087: =over 4
1.191     harris41 16088: 
                   16089: =item *
                   16090: 
1.481     raeburn  16091: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   16092: (a) files in /uploaded
                   16093:   (i) If a local copy of the file exists - 
                   16094:       compares modification date of local copy with last-modified date for 
                   16095:       definitive version stored on home server for course. If local copy is 
                   16096:       stale, requests a new version from the home server and stores it. 
                   16097:       If the original has been removed from the home server, then local copy 
                   16098:       is unlinked.
                   16099:   (ii) If local copy does not exist -
                   16100:       requests the file from the home server and stores it. 
                   16101:   
                   16102:   If $caller is 'uploadrep':  
                   16103:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   16104:     for request for files originally uploaded via DOCS. 
                   16105:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   16106:   
                   16107:   Otherwise:
                   16108:      This indicates a call from the content generation phase of the request.
                   16109:      -  returns the entire contents of the file or -1.
                   16110:      
                   16111: (b) files in /res
                   16112:    - returns the entire contents of a file or -1; 
                   16113:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 16114: 
1.712     albertel 16115: 
                   16116: =item *
                   16117: 
                   16118: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   16119:                   reference
                   16120: 
                   16121: returns either a stat() list of data about the file or an empty list
                   16122: if the file doesn't exist or couldn't find out about it (connection
                   16123: problems or user unknown)
                   16124: 
1.191     harris41 16125: =item *
                   16126: 
1.243     albertel 16127: filelocation($dir,$file) : returns file system location of a file
                   16128: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   16129: directory that relative $file lookups are to looked in ($dir of /a/dir
                   16130: and a file of ../bob will become /a/bob)
1.191     harris41 16131: 
                   16132: =item *
                   16133: 
                   16134: hreflocation($dir,$file) : returns file system location or a URL; same as
                   16135: filelocation except for hrefs
                   16136: 
                   16137: =item *
                   16138: 
1.1261    raeburn  16139: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   16140: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 16141: 
1.243     albertel 16142: =back
                   16143: 
1.608     albertel 16144: =head2 Usererfile file routines (/uploaded*)
                   16145: 
                   16146: =over 4
                   16147: 
                   16148: =item *
                   16149: 
                   16150: userfileupload(): main rotine for putting a file in a user or course's
                   16151:                   filespace, arguments are,
                   16152: 
1.620     albertel 16153:  formname - required - this is the name of the element in $env where the
1.608     albertel 16154:            filename, and the contents of the file to create/modifed exist
1.620     albertel 16155:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   16156:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  16157:  context - if coursedoc, store the file in the course of the active role
                   16158:              of the current user; 
                   16159:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   16160:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 16161:  subdir - required - subdirectory to put the file in under ../userfiles/
                   16162:          if undefined, it will be placed in "unknown"
                   16163: 
                   16164:  (This routine calls clean_filename() to remove any dangerous
                   16165:  characters from the filename, and then calls finuserfileupload() to
                   16166:  complete the transaction)
                   16167: 
                   16168:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16169:  and /adm/notfound.html if unsuccessful
                   16170: 
                   16171: =item *
                   16172: 
                   16173: clean_filename(): routine for cleaing a filename up for storage in
                   16174:                  userfile space, argument is:
                   16175: 
                   16176:  filename - proposed filename
                   16177: 
                   16178: returns: the new clean filename
                   16179: 
                   16180: =item *
                   16181: 
1.1090    raeburn  16182: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16183: userspace, probably shouldn't be called directly
                   16184: 
                   16185:   docuname: username or courseid of destination for the file
                   16186:   docudom: domain of user/course of destination for the file
                   16187:   formname: same as for userfileupload()
1.1090    raeburn  16188:   fname: filename (including subdirectories) for the file
                   16189:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401    raeburn  16190:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16191:   allfiles: reference to hash used to store objects found by parser
                   16192:   codebase: reference to hash used for codebases of java objects found by parser
                   16193:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16194:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16195:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   16196:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   16197:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   16198:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  16199:   mimetype: reference to scalar to accommodate mime type determined
                   16200:             from File::MMagic if $parser = parse.
1.608     albertel 16201: 
                   16202:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  16203:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   16204:  was 'overwrite').
                   16205:  
1.608     albertel 16206: 
                   16207: =item *
                   16208: 
                   16209: renameuserfile(): renames an existing userfile to a new name
                   16210: 
                   16211:   Args:
                   16212:    docuname: username or courseid of destination for the file
                   16213:    docudom: domain of user/course of destination for the file
                   16214:    old: current file name (including any subdirs under userfiles)
                   16215:    new: desired file name (including any subdirs under userfiles)
                   16216: 
                   16217: =item *
                   16218: 
                   16219: mkdiruserfile(): creates a directory is a userfiles dir
                   16220: 
                   16221:   Args:
                   16222:    docuname: username or courseid of destination for the file
                   16223:    docudom: domain of user/course of destination for the file
                   16224:    dir: dir to create (including any subdirs under userfiles)
                   16225: 
                   16226: =item *
                   16227: 
                   16228: removeuserfile(): removes a file that exists in userfiles
                   16229: 
                   16230:   Args:
                   16231:    docuname: username or courseid of destination for the file
                   16232:    docudom: domain of user/course of destination for the file
                   16233:    fname: filname to delete (including any subdirs under userfiles)
                   16234: 
                   16235: =item *
                   16236: 
                   16237: removeuploadedurl(): convience function for removeuserfile()
                   16238: 
                   16239:   Args:
                   16240:    url:  a full /uploaded/... url to delete
                   16241: 
1.747     albertel 16242: =item * 
                   16243: 
                   16244: get_portfile_permissions():
                   16245:   Args:
                   16246:     domain: domain of user or course contain the portfolio files
                   16247:     user: name of user or num of course contain the portfolio files
                   16248:   Returns:
                   16249:     hashref of a dump of the proper file_permissions.db
                   16250:    
                   16251: 
                   16252: =item * 
                   16253: 
                   16254: get_access_controls():
                   16255: 
                   16256: Args:
                   16257:   current_permissions: the hash ref returned from get_portfile_permissions()
                   16258:   group: (optional) the group you want the files associated with
                   16259:   file: (optional) the file you want access info on
                   16260: 
                   16261: Returns:
1.749     raeburn  16262:     a hash (keys are file names) of hashes containing
                   16263:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   16264:         values are XML containing access control settings (see below) 
1.747     albertel 16265: 
                   16266: Internal notes:
                   16267: 
1.749     raeburn  16268:  access controls are stored in file_permissions.db as key=value pairs.
                   16269:     key -> path to file/file_name\0uniqueID:scope_end_start
                   16270:         where scope -> public,guest,course,group,domains or users.
                   16271:               end -> UNIX time for end of access (0 -> no end date)
                   16272:               start -> UNIX time for start of access
                   16273: 
                   16274:     value -> XML description of access control
                   16275:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   16276:             <start></start>
                   16277:             <end></end>
                   16278: 
                   16279:             <password></password>  for scope type = guest
                   16280: 
                   16281:             <domain></domain>     for scope type = course or group
                   16282:             <number></number>
                   16283:             <roles id="">
                   16284:              <role></role>
                   16285:              <access></access>
                   16286:              <section></section>
                   16287:              <group></group>
                   16288:             </roles>
                   16289: 
                   16290:             <dom></dom>         for scope type = domains
                   16291: 
                   16292:             <users>             for scope type = users
                   16293:              <user>
                   16294:               <uname></uname>
                   16295:               <udom></udom>
                   16296:              </user>
                   16297:             </users>
                   16298:            </scope> 
                   16299:               
                   16300:  Access data is also aggregated for each file in an additional key=value pair:
                   16301:  key -> path to file/file_name\0accesscontrol 
                   16302:  value -> reference to hash
                   16303:           hash contains key = value pairs
                   16304:           where key = uniqueID:scope_end_start
                   16305:                 value = UNIX time record was last updated
                   16306: 
                   16307:           Used to improve speed of look-ups of access controls for each file.  
                   16308:  
                   16309:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   16310: 
1.1198    raeburn  16311: =item *
                   16312: 
1.749     raeburn  16313: modify_access_controls():
                   16314: 
                   16315: Modifies access controls for a portfolio file
                   16316: Args
                   16317: 1. file name
                   16318: 2. reference to hash of required changes,
                   16319: 3. domain
                   16320: 4. username
                   16321:   where domain,username are the domain of the portfolio owner 
                   16322:   (either a user or a course) 
                   16323: 
                   16324: Returns:
                   16325: 1. result of additions or updates ('ok' or 'error', with error message). 
                   16326: 2. result of deletions ('ok' or 'error', with error message).
                   16327: 3. reference to hash of any new or updated access controls.
                   16328: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   16329:    key = integer (inbound ID)
1.1198    raeburn  16330:    value = uniqueID
                   16331: 
                   16332: =item *
                   16333: 
                   16334: get_timebased_id():
                   16335: 
                   16336: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   16337: course via the Course Editor (e.g., folders, composite pages, 
                   16338: group bulletin boards).
                   16339: 
                   16340: Args: (first three required; six others optional)
                   16341: 
                   16342: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   16343:    docssequence, or name of group
                   16344: 
                   16345: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   16346:    e.g., num, boardids
                   16347: 
                   16348: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   16349:    file will be named nohist_namespace.db
                   16350: 
                   16351: 4. cdom: domain of course; default is current course domain from %env
                   16352: 
                   16353: 5. cnum: course number; default is current course number from %env
                   16354: 
                   16355: 6. idtype: set to concat if an additional digit is to be appended to the 
                   16356:    unix timestamp to form the suffix, if the plain timestamp is already
                   16357:    in use.  Default is to not do this, but simply increment the unix 
                   16358:    timestamp by 1 until a unique key is obtained.
                   16359: 
                   16360: 7. who: holder of locking key; defaults to user:domain for user.
                   16361: 
                   16362: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   16363:    retrying); default is 3.
                   16364: 
                   16365: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   16366: 
                   16367: Returns:
                   16368: 
                   16369: 1. suffix obtained (numeric)
                   16370: 
                   16371: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   16372: 
                   16373: 3. error: contains (localized) error message if an error occurred.
                   16374: 
1.747     albertel 16375: 
1.608     albertel 16376: =back
                   16377: 
1.243     albertel 16378: =head2 HTTP Helper Routines
                   16379: 
                   16380: =over 4
                   16381: 
1.191     harris41 16382: =item *
                   16383: 
                   16384: escape() : unpack non-word characters into CGI-compatible hex codes
                   16385: 
                   16386: =item *
                   16387: 
                   16388: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   16389: 
1.243     albertel 16390: =back
                   16391: 
                   16392: =head1 PRIVATE SUBROUTINES
                   16393: 
                   16394: =head2 Underlying communication routines (Shouldn't call)
                   16395: 
                   16396: =over 4
                   16397: 
                   16398: =item *
                   16399: 
                   16400: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   16401: 
                   16402: =item *
                   16403: 
                   16404: reply() : uses subreply to send a message to remote machine, logs all failures
                   16405: 
                   16406: =item *
                   16407: 
                   16408: critical() : passes a critical message to another server; if cannot
                   16409: get through then place message in connection buffer directory and
                   16410: returns con_delayed, if incapable of saving message, returns
                   16411: con_failed
                   16412: 
                   16413: =item *
                   16414: 
                   16415: reconlonc() : tries to reconnect lonc client processes.
                   16416: 
                   16417: =back
                   16418: 
                   16419: =head2 Resource Access Logging
                   16420: 
                   16421: =over 4
                   16422: 
                   16423: =item *
                   16424: 
                   16425: flushcourselogs() : flush (save) buffer logs and access logs
                   16426: 
                   16427: =item *
                   16428: 
                   16429: courselog($what) : save message for course in hash
                   16430: 
                   16431: =item *
                   16432: 
                   16433: courseacclog($what) : save message for course using &courselog().  Perform
                   16434: special processing for specific resource types (problems, exams, quizzes, etc).
                   16435: 
1.191     harris41 16436: =item *
                   16437: 
                   16438: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16439: as a PerlChildExitHandler
1.243     albertel 16440: 
                   16441: =back
                   16442: 
                   16443: =head2 Other
                   16444: 
                   16445: =over 4
                   16446: 
                   16447: =item *
                   16448: 
                   16449: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16450: 
                   16451: =back
                   16452: 
                   16453: =cut
1.877     foxr     16454: 

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