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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1360  ! raeburn     4: # $Id: lonnet.pm,v 1.1359 2017/11/13 00:49:31 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;
                     76: 
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.890     albertel  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\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 {
                    233:     my ($lonhost,$context) = @_;
                    234:     my ($rep,$uselocal);
                    235:     if (grep { $_ eq $lonhost } &current_machine_ids()) {
                    236:         $uselocal = 1;
                    237:     }
1.1316    raeburn   238:     if (($context ne 'cgi') && ($uselocal)) {
1.1315    raeburn   239:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323    raeburn   240:         if ($distro eq '') {
                    241:             $uselocal = 0;
                    242:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315    raeburn   243:             if ($1 < 6) {
                    244:                 $uselocal = 0;
                    245:             }
1.1346    raeburn   246:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
                    247:             if ($1 < 12) {
                    248:                 $uselocal = 0;
                    249:             }
1.1315    raeburn   250:         }
                    251:     }
                    252:     if ($uselocal) {
                    253:         $rep = LONCAPA::Lond::server_certs(\%perlvar);
                    254:     } else {
                    255:         $rep=&reply('servercerts',$lonhost);
                    256:     }
                    257:     my ($result,%returnhash);
                    258:     if (defined($lonhost)) {
                    259:         if (!defined(&hostname($lonhost))) {
                    260:             return;
                    261:         }
                    262:     }
                    263:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    264:         ($rep eq 'unknown_cmd')) {
                    265:         $result = $rep;
                    266:     } else {
                    267:         $result = 'ok';
                    268:         my @pairs=split(/\&/,$rep);
                    269:         foreach my $item (@pairs) {
                    270:             my ($key,$value)=split(/=/,$item,2);
                    271:             my $what = &unescape($key);
                    272:             $returnhash{$what}=&thaw_unescape($value);
                    273:         }
                    274:     }
                    275:     return ($result,\%returnhash);
                    276: }
                    277: 
1.993     raeburn   278: sub get_server_loncaparev {
1.1073    raeburn   279:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   280:     if (defined($lonhost)) {
                    281:         if (!defined(&hostname($lonhost))) {
                    282:             undef($lonhost);
                    283:         }
                    284:     }
                    285:     if (!defined($lonhost)) {
                    286:         if (defined(&domain($dom,'primary'))) {
                    287:             $lonhost=&domain($dom,'primary');
                    288:             if ($lonhost eq 'no_host') {
                    289:                 undef($lonhost);
                    290:             }
                    291:         }
                    292:     }
                    293:     if (defined($lonhost)) {
1.1073    raeburn   294:         my $cachetime = 12*3600;
                    295:         if (!$ignore_cache) {
                    296:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    297:             if (defined($cached)) {
                    298:                 return $loncaparev;
                    299:             }
                    300:         }
                    301:         my ($answer,$loncaparev);
                    302:         my @ids=&current_machine_ids();
                    303:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    304:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   305:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   306:                 $loncaparev = $1;
                    307:             }
                    308:         } else {
                    309:             $answer = &reply('serverloncaparev',$lonhost);
                    310:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    311:                 if ($caller eq 'loncron') {
                    312:                     my $protocol = $protocol{$lonhost};
                    313:                     $protocol = 'http' if ($protocol ne 'https');
                    314:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    315:                     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn   316:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073    raeburn   317:                     unless ($response->is_error()) {
                    318:                         my $content = $response->content;
1.1081    raeburn   319:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   320:                             $loncaparev = $1;
                    321:                         }
                    322:                     }
                    323:                 } else {
                    324:                     $loncaparev = $loncaparevs{$lonhost};
                    325:                 }
1.1081    raeburn   326:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   327:                 $loncaparev = $1;
                    328:             }
1.993     raeburn   329:         }
1.1073    raeburn   330:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   331:     }
                    332: }
                    333: 
1.1074    raeburn   334: sub get_server_homeID {
                    335:     my ($hostname,$ignore_cache,$caller) = @_;
                    336:     unless ($ignore_cache) {
                    337:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    338:         if (defined($cached)) {
                    339:             return $serverhomeID;
                    340:         }
                    341:     }
                    342:     my $cachetime = 12*3600;
                    343:     my $serverhomeID;
                    344:     if ($caller eq 'loncron') { 
                    345:         my @machine_ids = &machine_ids($hostname);
                    346:         foreach my $id (@machine_ids) {
                    347:             my $response = &reply('serverhomeID',$id);
                    348:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    349:                 $serverhomeID = $response;
                    350:                 last;
                    351:             }
                    352:         }
                    353:         if ($serverhomeID eq '') {
                    354:             $serverhomeID = $machine_ids[-1];
                    355:         }
                    356:     } else {
                    357:         $serverhomeID = $serverhomeIDs{$hostname};
                    358:     }
                    359:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    360: }
                    361: 
1.1121    raeburn   362: sub get_remote_globals {
                    363:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   364:     my ($result,%returnhash,%whatneeded);
                    365:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   366:         foreach my $what (sort(keys(%{$whathash}))) {
                    367:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   368:             my ($response,$cached);
1.1121    raeburn   369:             unless ($ignore_cache) {
1.1125    raeburn   370:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   371:             }
                    372:             if (defined($cached)) {
1.1125    raeburn   373:                 $returnhash{$what} = $response;
1.1121    raeburn   374:             } else {
1.1125    raeburn   375:                 $whatneeded{$what} = 1;
1.1121    raeburn   376:             }
                    377:         }
1.1125    raeburn   378:         if (keys(%whatneeded) == 0) {
                    379:             $result = 'ok';
                    380:         } else {
1.1121    raeburn   381:             my $requested = &freeze_escape(\%whatneeded);
                    382:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   383:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    384:                 ($rep eq 'unknown_cmd')) {
                    385:                 $result = $rep;
                    386:             } else {
                    387:                 $result = 'ok';
1.1121    raeburn   388:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   389:                 foreach my $item (@pairs) {
                    390:                     my ($key,$value)=split(/=/,$item,2);
                    391:                     my $what = &unescape($key);
                    392:                     my $hashid = $lonhost.'-'.$what;
                    393:                     $returnhash{$what}=&thaw_unescape($value);
                    394:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   395:                 }
                    396:             }
                    397:         }
                    398:     }
1.1125    raeburn   399:     return ($result,\%returnhash);
1.1121    raeburn   400: }
                    401: 
1.1124    raeburn   402: sub remote_devalidate_cache {
1.1241    raeburn   403:     my ($lonhost,$cachekeys) = @_;
                    404:     my $items;
                    405:     return unless (ref($cachekeys) eq 'ARRAY');
                    406:     my $cachestr = join('&',@{$cachekeys});
                    407:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   408:     return $response;
                    409: }
                    410: 
1.1       albertel  411: # -------------------------------------------------- Non-critical communication
                    412: sub subreply {
                    413:     my ($cmd,$server)=@_;
1.838     albertel  414:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      415:     #
                    416:     #  With loncnew process trimming, there's a timing hole between lonc server
                    417:     #  process exit and the master server picking up the listen on the AF_UNIX
                    418:     #  socket.  In that time interval, a lock file will exist:
                    419: 
                    420:     my $lockfile=$peerfile.".lock";
                    421:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   422: 	sleep(0.1);
1.549     foxr      423:     }
                    424:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      425:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      426:     #
1.550     foxr      427:     #   We'll give the connection a few tries before abandoning it.  If
                    428:     #   connection is not possible, we'll con_lost back to the client.
                    429:     #   
                    430:     my $client;
                    431:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    432: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    433: 				      Type    => SOCK_STREAM,
                    434: 				      Timeout => 10);
1.869     albertel  435: 	if ($client) {
1.550     foxr      436: 	    last;		# Connected!
1.850     albertel  437: 	} else {
1.853     albertel  438: 	    &create_connection(&hostname($server),$server);
1.550     foxr      439: 	}
1.1289    damieng   440:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      441:     }
                    442:     my $answer;
                    443:     if ($client) {
1.704     albertel  444: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      445: 	$answer=<$client>;
                    446: 	if (!$answer) { $answer="con_lost"; }
                    447: 	chomp($answer);
                    448:     } else {
                    449: 	$answer = 'con_lost';	# Failed connection.
                    450:     }
1.1       albertel  451:     return $answer;
                    452: }
                    453: 
                    454: sub reply {
                    455:     my ($cmd,$server)=@_;
1.838     albertel  456:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  457:     my $answer=subreply($cmd,$server);
1.65      www       458:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  459:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       460:                 " $cmd to $server returned $answer</font>");
                    461:     }
1.1       albertel  462:     return $answer;
                    463: }
                    464: 
                    465: # ----------------------------------------------------------- Send USR1 to lonc
                    466: 
                    467: sub reconlonc {
1.891     albertel  468:     my ($lonid) = @_;
                    469:     if ($lonid) {
1.1295    raeburn   470:         my $hostname = &hostname($lonid);
1.891     albertel  471: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    472: 	if ($hostname && -e $peerfile) {
                    473: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    474: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    475: 					     Type    => SOCK_STREAM,
                    476: 					     Timeout => 10);
                    477: 	    if ($client) {
                    478: 		print $client ("reset_retries\n");
                    479: 		my $answer=<$client>;
                    480: 		#reset just this one.
                    481: 	    }
                    482: 	}
                    483: 	return;
                    484:     }
                    485: 
1.836     www       486:     &logthis("Trying to reconnect lonc");
1.1       albertel  487:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359    raeburn   488:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  489: 	my $loncpid=<$fh>;
                    490:         chomp($loncpid);
                    491:         if (kill 0 => $loncpid) {
                    492: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    493:             kill USR1 => $loncpid;
                    494:             sleep 1;
1.1295    raeburn   495:         } else {
1.12      www       496: 	    &logthis(
1.672     albertel  497:                "<font color=\"blue\">WARNING:".
1.12      www       498:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  499:         }
                    500:     } else {
1.836     www       501: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  502:     }
                    503: }
                    504: 
                    505: # ------------------------------------------------------ Critical communication
1.12      www       506: 
1.1       albertel  507: sub critical {
                    508:     my ($cmd,$server)=@_;
1.838     albertel  509:     unless (&hostname($server)) {
1.672     albertel  510:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       511:                " Critical message to unknown server ($server)</font>");
                    512:         return 'no_such_host';
                    513:     }
1.1       albertel  514:     my $answer=reply($cmd,$server);
                    515:     if ($answer eq 'con_lost') {
1.1295    raeburn   516: 	&reconlonc($server);
1.589     albertel  517: 	my $answer=reply($cmd,$server);
1.1       albertel  518:         if ($answer eq 'con_lost') {
                    519:             my $now=time;
                    520:             my $middlename=$cmd;
1.5       www       521:             $middlename=substr($middlename,0,16);
1.1       albertel  522:             $middlename=~s/\W//g;
                    523:             my $dfilename=
1.305     www       524:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    525:             $dumpcount++;
1.1       albertel  526:             {
1.448     albertel  527: 		my $dfh;
1.1359    raeburn   528: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  529: 		    print $dfh "$cmd\n"; 
                    530: 		    close($dfh);
                    531: 		}
1.1       albertel  532:             }
1.1288    damieng   533:             sleep 1;
1.1       albertel  534:             my $wcmd='';
                    535:             {
1.448     albertel  536: 		my $dfh;
1.1359    raeburn   537: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  538: 		    $wcmd=<$dfh>; 
                    539: 		    close($dfh);
                    540: 		}
1.1       albertel  541:             }
                    542:             chomp($wcmd);
1.7       www       543:             if ($wcmd eq $cmd) {
1.672     albertel  544: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       545:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  546:                 &logperm("D:$server:$cmd");
                    547: 	        return 'con_delayed';
                    548:             } else {
1.672     albertel  549:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       550:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  551:                 &logperm("F:$server:$cmd");
                    552:                 return 'con_failed';
                    553:             }
                    554:         }
                    555:     }
                    556:     return $answer;
1.405     albertel  557: }
                    558: 
1.755     albertel  559: # ------------------------------------------- check if return value is an error
                    560: 
                    561: sub error {
                    562:     my ($result) = @_;
1.756     albertel  563:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  564: 	if ($2 == 2) { return undef; }
                    565: 	return $1;
                    566:     }
                    567:     return undef;
                    568: }
                    569: 
1.783     albertel  570: sub convert_and_load_session_env {
                    571:     my ($lonidsdir,$handle)=@_;
                    572:     my @profile;
                    573:     {
1.917     albertel  574: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    575: 	if (!$opened) {
1.915     albertel  576: 	    return 0;
                    577: 	}
1.783     albertel  578: 	flock($idf,LOCK_SH);
                    579: 	@profile=<$idf>;
                    580: 	close($idf);
                    581:     }
                    582:     my %temp_env;
                    583:     foreach my $line (@profile) {
1.786     albertel  584: 	if ($line !~ m/=/) {
                    585: 	    return 0;
                    586: 	}
1.783     albertel  587: 	chomp($line);
                    588: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    589: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    590:     }
                    591:     unlink("$lonidsdir/$handle.id");
                    592:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    593: 	    0640)) {
                    594: 	%disk_env = %temp_env;
                    595: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    596: 	untie(%disk_env);
                    597:     }
1.786     albertel  598:     return 1;
1.783     albertel  599: }
                    600: 
1.374     www       601: # ------------------------------------------- Transfer profile into environment
1.780     albertel  602: my $env_loaded;
                    603: sub transfer_profile_to_env {
1.788     albertel  604:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    605:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       606: 
1.720     albertel  607:     if (!defined($lonidsdir)) {
                    608: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    609:     }
                    610:     if (!defined($handle)) {
                    611:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    612:     }
                    613: 
1.786     albertel  614:     my $convert;
                    615:     {
1.917     albertel  616:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    617: 	if (!$opened) {
1.915     albertel  618: 	    return;
                    619: 	}
1.786     albertel  620: 	flock($idf,LOCK_SH);
                    621: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    622: 		&GDBM_READER(),0640)) {
                    623: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    624: 	    untie(%disk_env);
                    625: 	} else {
                    626: 	    $convert = 1;
                    627: 	}
                    628:     }
                    629:     if ($convert) {
                    630: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    631: 	    &logthis("Failed to load session, or convert session.");
                    632: 	}
1.374     www       633:     }
1.783     albertel  634: 
1.786     albertel  635:     my %remove;
1.783     albertel  636:     while ( my $envname = each(%env) ) {
1.433     matthew   637:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    638:             if ($time < time-300) {
1.783     albertel  639:                 $remove{$key}++;
1.433     matthew   640:             }
                    641:         }
                    642:     }
1.783     albertel  643: 
1.619     albertel  644:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  645:     $env_loaded=1;
1.783     albertel  646:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   647:         &delenv($expired_key);
1.374     www       648:     }
1.1       albertel  649: }
                    650: 
1.916     albertel  651: # ---------------------------------------------------- Check for valid session 
                    652: sub check_for_valid_session {
1.1355    raeburn   653:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  654:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1337    raeburn   655:     my ($linkname,$pubname);
1.1155    raeburn   656:     if ($name eq '') {
                    657:         $name = 'lonID';
1.1337    raeburn   658:         $linkname = 'lonLinkID';
                    659:         $pubname = 'lonPubID';
1.1155    raeburn   660:     }
                    661:     my $lonid=$cookies{$name};
1.1337    raeburn   662:     if (!$lonid) {
                    663:         if (($name eq 'lonID') && ($ENV{'SERVER_PORT'} != 443) && ($linkname)) {
                    664:             $lonid=$cookies{$linkname};
                    665:         }
                    666:         if (!$lonid) {
                    667:             if (($name eq 'lonID') && ($pubname)) {
                    668:                 $lonid=$cookies{$pubname};
                    669:             }
                    670:         }
                    671:     }
1.916     albertel  672:     return undef if (!$lonid);
                    673: 
                    674:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   675:     my $lonidsdir;
                    676:     if ($name eq 'lonDAV') {
                    677:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    678:     } else {
                    679:         $lonidsdir=$r->dir_config('lonIDsDir');
                    680:     }
1.1355    raeburn   681:     if (!-e "$lonidsdir/$handle.id") {
                    682:         if ((ref($domref)) && ($name eq 'lonID') && 
                    683:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    684:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    685:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    686:                 $$domref = $possudom;
                    687:             }
                    688:         }
                    689:         return undef;
                    690:     }
1.916     albertel  691: 
1.917     albertel  692:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    693:     return undef if (!$opened);
1.916     albertel  694: 
                    695:     flock($idf,LOCK_SH);
                    696:     my %disk_env;
                    697:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    698: 	    &GDBM_READER(),0640)) {
                    699: 	return undef;	
                    700:     }
                    701: 
                    702:     if (!defined($disk_env{'user.name'})
                    703: 	|| !defined($disk_env{'user.domain'})) {
                    704: 	return undef;
                    705:     }
1.1245    raeburn   706: 
                    707:     if (ref($userhashref) eq 'HASH') {
                    708:         $userhashref->{'name'} = $disk_env{'user.name'};
                    709:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212    raeburn   710:     }
1.1245    raeburn   711: 
1.916     albertel  712:     return $handle;
                    713: }
                    714: 
1.830     albertel  715: sub timed_flock {
                    716:     my ($file,$lock_type) = @_;
                    717:     my $failed=0;
                    718:     eval {
                    719: 	local $SIG{__DIE__}='DEFAULT';
                    720: 	local $SIG{ALRM}=sub {
                    721: 	    $failed=1;
                    722: 	    die("failed lock");
                    723: 	};
                    724: 	alarm(13);
                    725: 	flock($file,$lock_type);
                    726: 	alarm(0);
                    727:     };
                    728:     if ($failed) {
                    729: 	return undef;
                    730:     } else {
                    731: 	return 1;
                    732:     }
                    733: }
                    734: 
1.5       www       735: # ---------------------------------------------------------- Append Environment
                    736: 
                    737: sub appenv {
1.949     raeburn   738:     my ($newenv,$roles) = @_;
                    739:     if (ref($newenv) eq 'HASH') {
                    740:         foreach my $key (keys(%{$newenv})) {
                    741:             my $refused = 0;
                    742: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    743:                 $refused = 1;
                    744:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   745:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   746:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    747:                         $refused = 0;
                    748:                     }
                    749:                 }
                    750:             }
                    751:             if ($refused) {
                    752:                 &logthis("<font color=\"blue\">WARNING: ".
                    753:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    754:                          .'</font>');
                    755: 	        delete($newenv->{$key});
                    756:             } else {
                    757:                 $env{$key}=$newenv->{$key};
                    758:             }
                    759:         }
                    760:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    761:         if ($opened
                    762: 	    && &timed_flock($env_file,LOCK_EX)
                    763: 	    &&
                    764: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    765: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    766: 	    while (my ($key,$value) = each(%{$newenv})) {
                    767: 	        $disk_env{$key} = $value;
                    768: 	    }
                    769: 	    untie(%disk_env);
1.35      www       770:         }
1.191     harris41  771:     }
1.56      www       772:     return 'ok';
                    773: }
                    774: # ----------------------------------------------------- Delete from Environment
                    775: 
                    776: sub delenv {
1.1104    raeburn   777:     my ($delthis,$regexp,$roles) = @_;
                    778:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    779:         my $refused = 1;
                    780:         if (ref($roles) eq 'ARRAY') {
                    781:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    782:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    783:                 $refused = 0;
                    784:             }
                    785:         }
                    786:         if ($refused) {
                    787:             &logthis("<font color=\"blue\">WARNING: ".
                    788:                      "Attempt to delete from environment ".$delthis);
                    789:             return 'error';
                    790:         }
1.56      www       791:     }
1.917     albertel  792:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    793:     if ($opened
1.915     albertel  794: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  795: 	&&
                    796: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    797: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  798: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   799: 	    if ($regexp) {
                    800:                 if ($key=~/^$delthis/) {
                    801:                     delete($env{$key});
                    802:                     delete($disk_env{$key});
                    803:                 } 
                    804:             } else {
                    805:                 if ($key=~/^\Q$delthis\E/) {
                    806: 		    delete($env{$key});
                    807: 		    delete($disk_env{$key});
                    808: 	        }
                    809:             }
1.448     albertel  810: 	}
1.783     albertel  811: 	untie(%disk_env);
1.5       www       812:     }
                    813:     return 'ok';
1.369     albertel  814: }
                    815: 
1.790     albertel  816: sub get_env_multiple {
                    817:     my ($name) = @_;
                    818:     my @values;
                    819:     if (defined($env{$name})) {
                    820:         # exists is it an array
                    821:         if (ref($env{$name})) {
                    822:             @values=@{ $env{$name} };
                    823:         } else {
                    824:             $values[0]=$env{$name};
                    825:         }
                    826:     }
                    827:     return(@values);
                    828: }
                    829: 
1.958     www       830: # ------------------------------------------------------------------- Locking
                    831: 
                    832: sub set_lock {
                    833:     my ($text)=@_;
                    834:     $locknum++;
                    835:     my $id=$$.'-'.$locknum;
                    836:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    837:              'session.lock.'.$id => $text});
                    838:     return $id;
                    839: }
                    840: 
                    841: sub get_locks {
                    842:     my $num=0;
                    843:     my %texts=();
                    844:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    845:        if ($lock=~/\w/) {
                    846:           $num++;
                    847:           $texts{$lock}=$env{'session.lock.'.$lock};
                    848:        }
                    849:    }
                    850:    return ($num,%texts);
                    851: }
                    852: 
                    853: sub remove_lock {
                    854:     my ($id)=@_;
                    855:     my $newlocks='';
                    856:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    857:        if (($lock=~/\w/) && ($lock ne $id)) {
                    858:           $newlocks.=','.$lock;
                    859:        }
                    860:     }
                    861:     &appenv({'session.locks' => $newlocks});
                    862:     &delenv('session.lock.'.$id);
                    863: }
                    864: 
                    865: sub remove_all_locks {
                    866:     my $activelocks=$env{'session.locks'};
                    867:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    868:        if ($lock=~/\w/) {
                    869:           &remove_lock($lock);
                    870:        }
                    871:     }
                    872: }
                    873: 
                    874: 
1.369     albertel  875: # ------------------------------------------ Find out current server userload
                    876: sub userload {
                    877:     my $numusers=0;
                    878:     {
                    879: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    880: 	my $filename;
                    881: 	my $curtime=time;
                    882: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  883: 	    next if ($filename eq '.' || $filename eq '..');
                    884: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  885: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  886: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  887: 	}
                    888: 	closedir(LONIDS);
                    889:     }
                    890:     my $userloadpercent=0;
                    891:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    892:     if ($maxuserload) {
1.371     albertel  893: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  894:     }
1.372     albertel  895:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  896:     return $userloadpercent;
1.283     www       897: }
                    898: 
1.1       albertel  899: # ------------------------------ Find server with least workload from spare.tab
1.11      www       900: 
1.1       albertel  901: sub spareserver {
1.1083    raeburn   902:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  903:     my $spare_server;
1.370     albertel  904:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  905:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    906:                                                      :  $userloadpercent;
1.1083    raeburn   907:     my ($uint_dom,$remotesessions);
                    908:     if (($udom ne '') && (&domain($udom) ne '')) {
                    909:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    910:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    911:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    912:         $remotesessions = $udomdefaults{'remotesessions'};
                    913:     }
1.1123    raeburn   914:     my $spareshash = &this_host_spares($udom);
                    915:     if (ref($spareshash) eq 'HASH') {
                    916:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    917:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   918:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    919:                                              $try_server));
1.1123    raeburn   920: 	        ($spare_server, $lowest_load) =
                    921: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    922:             }
1.1083    raeburn   923:         }
1.784     albertel  924: 
1.1123    raeburn   925:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    926: 
                    927:         if (!$found_server) {
                    928:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    929: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn   930:                     next unless (&spare_can_host($udom,$uint_dom,
                    931:                                                  $remotesessions,$try_server));
1.1123    raeburn   932: 	            ($spare_server, $lowest_load) =
                    933: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    934:                 }
                    935: 	    }
                    936:         }
1.784     albertel  937:     }
                    938: 
                    939:     if (!$want_server_name) {
1.968     raeburn   940:         my $protocol = 'http';
                    941:         if ($protocol{$spare_server} eq 'https') {
                    942:             $protocol = $protocol{$spare_server};
                    943:         }
1.1001    raeburn   944:         if (defined($spare_server)) {
                    945:             my $hostname = &hostname($spare_server);
1.1083    raeburn   946:             if (defined($hostname)) {
1.1001    raeburn   947: 	        $spare_server = $protocol.'://'.$hostname;
                    948:             }
                    949:         }
1.784     albertel  950:     }
                    951:     return $spare_server;
                    952: }
                    953: 
                    954: sub compare_server_load {
1.1253    raeburn   955:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    956: 
                    957:     if ($required) {
                    958:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    959:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    960:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    961:         if (($major eq '' && $minor eq '') ||
                    962:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    963:             return ($spare_server,$lowest_load);
                    964:         }
                    965:     }
1.784     albertel  966: 
                    967:     my $loadans     = &reply('load',    $try_server);
                    968:     my $userloadans = &reply('userload',$try_server);
                    969: 
                    970:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   971: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  972:     }
                    973: 
                    974:     my $load;
                    975:     if ($loadans =~ /\d/) {
                    976: 	if ($userloadans =~ /\d/) {
                    977: 	    #both are numbers, pick the bigger one
                    978: 	    $load = ($loadans > $userloadans) ? $loadans 
                    979: 		                              : $userloadans;
1.411     albertel  980: 	} else {
1.784     albertel  981: 	    $load = $loadans;
1.411     albertel  982: 	}
1.784     albertel  983:     } else {
                    984: 	$load = $userloadans;
                    985:     }
                    986: 
                    987:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    988: 	$spare_server = $try_server;
                    989: 	$lowest_load  = $load;
1.370     albertel  990:     }
1.784     albertel  991:     return ($spare_server,$lowest_load);
1.202     matthew   992: }
1.914     albertel  993: 
                    994: # --------------------------- ask offload servers if user already has a session
                    995: sub find_existing_session {
                    996:     my ($udom,$uname) = @_;
1.1123    raeburn   997:     my $spareshash = &this_host_spares($udom);
                    998:     if (ref($spareshash) eq 'HASH') {
                    999:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1000:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1001:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1002:             }
                   1003:         }
                   1004:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1005:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1006:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1007:             }
                   1008:         }
1.914     albertel 1009:     }
                   1010:     return;
                   1011: }
                   1012: 
                   1013: # -------------------------------- ask if server already has a session for user
                   1014: sub has_user_session {
                   1015:     my ($lonid,$udom,$uname) = @_;
                   1016:     my $result = &reply(join(':','userhassession',
                   1017: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1018:     return 1 if ($result eq 'ok');
                   1019: 
                   1020:     return 0;
                   1021: }
                   1022: 
1.1076    raeburn  1023: # --------- determine least loaded server in a user's domain which allows login
                   1024: 
                   1025: sub choose_server {
1.1259    raeburn  1026:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1027:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1028:     my %servers = &get_servers($udom);
1.1076    raeburn  1029:     my $lowest_load = 30000;
1.1259    raeburn  1030:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1031:     if ($skiploadbal) {
                   1032:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1033:         unless (defined($cached)) {
                   1034:             my $cachetime = 60*60*24;
                   1035:             my %domconfig =
                   1036:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1037:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1038:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1039:                                            $cachetime);
                   1040:             }
                   1041:         }
                   1042:     }
1.1076    raeburn  1043:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1044:         if ($skiploadbal) {
                   1045:             if (ref($balancers) eq 'HASH') {
                   1046:                 next if (exists($balancers->{$lonhost}));
                   1047:             }
                   1048:         }   
1.1115    raeburn  1049:         my $loginvia;
                   1050:         if ($checkloginvia) {
                   1051:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1052:             if ($loginvia) {
                   1053:                 my ($server,$path) = split(/:/,$loginvia);
                   1054:                 ($login_host, $lowest_load) =
1.1253    raeburn  1055:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1056:                 if ($login_host eq $server) {
                   1057:                     $portal_path = $path;
1.1151    raeburn  1058:                     $isredirect = 1;
1.1116    raeburn  1059:                 }
                   1060:             } else {
                   1061:                 ($login_host, $lowest_load) =
1.1253    raeburn  1062:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1063:                 if ($login_host eq $lonhost) {
                   1064:                     $portal_path = '';
1.1151    raeburn  1065:                     $isredirect = ''; 
1.1116    raeburn  1066:                 }
                   1067:             }
                   1068:         } else {
1.1076    raeburn  1069:             ($login_host, $lowest_load) =
1.1253    raeburn  1070:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1071:         }
                   1072:     }
                   1073:     if ($login_host ne '') {
1.1116    raeburn  1074:         $hostname = &hostname($login_host);
1.1076    raeburn  1075:     }
1.1331    raeburn  1076:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1077: }
                   1078: 
1.202     matthew  1079: # --------------------------------------------- Try to change a user's password
                   1080: 
                   1081: sub changepass {
1.799     raeburn  1082:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1083:     $currentpass = &escape($currentpass);
                   1084:     $newpass     = &escape($newpass);
1.1030    raeburn  1085:     my $lonhost = $perlvar{'lonHostID'};
                   1086:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1087: 		       $server);
                   1088:     if (! $answer) {
                   1089: 	&logthis("No reply on password change request to $server ".
                   1090: 		 "by $uname in domain $udom.");
                   1091:     } elsif ($answer =~ "^ok") {
                   1092:         &logthis("$uname in $udom successfully changed their password ".
                   1093: 		 "on $server.");
                   1094:     } elsif ($answer =~ "^pwchange_failure") {
                   1095: 	&logthis("$uname in $udom was unable to change their password ".
                   1096: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1097: 		 "or pwchange");
                   1098:     } elsif ($answer =~ "^non_authorized") {
                   1099:         &logthis("$uname in $udom did not get their password correct when ".
                   1100: 		 "attempting to change it on $server.");
                   1101:     } elsif ($answer =~ "^auth_mode_error") {
                   1102:         &logthis("$uname in $udom attempted to change their password despite ".
                   1103: 		 "not being locally or internally authenticated on $server.");
                   1104:     } elsif ($answer =~ "^unknown_user") {
                   1105:         &logthis("$uname in $udom attempted to change their password ".
                   1106: 		 "on $server but were unable to because $server is not ".
                   1107: 		 "their home server.");
                   1108:     } elsif ($answer =~ "^refused") {
                   1109: 	&logthis("$server refused to change $uname in $udom password because ".
                   1110: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1111:     } elsif ($answer =~ "invalid_client") {
                   1112:         &logthis("$server refused to change $uname in $udom password because ".
                   1113:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1114:     }
                   1115:     return $answer;
1.1       albertel 1116: }
                   1117: 
1.169     harris41 1118: # ----------------------- Try to determine user's current authentication scheme
                   1119: 
                   1120: sub queryauthenticate {
                   1121:     my ($uname,$udom)=@_;
1.456     albertel 1122:     my $uhome=&homeserver($uname,$udom);
                   1123:     if (!$uhome) {
                   1124: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1125: 	return 'no_host';
                   1126:     }
                   1127:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1128:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1129: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1130:     }
1.456     albertel 1131:     return $answer;
1.169     harris41 1132: }
                   1133: 
1.1       albertel 1134: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1135: 
1.1       albertel 1136: sub authenticate {
1.1073    raeburn  1137:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1138:     $upass=&escape($upass);
                   1139:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1140:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1141:     my $newhome;
1.836     www      1142:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1143: # Maybe the machine was offline and only re-appeared again recently?
                   1144:         &reconlonc();
                   1145: # One more
1.952     raeburn  1146: 	$uhome=&homeserver($uname,$udom,1);
                   1147:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1148:             if (defined(&domain($udom,'primary'))) {
                   1149:                 $newhome=&domain($udom,'primary');
                   1150:             }
                   1151:             if ($newhome ne '') {
                   1152:                 $uhome = $newhome;
                   1153:             }
                   1154:         }
1.836     www      1155: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1156: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1157: 	    return 'no_host';
                   1158:         }
1.1       albertel 1159:     }
1.1073    raeburn  1160:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1161:     if ($answer eq 'authorized') {
1.952     raeburn  1162:         if ($newhome) {
                   1163:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1164:             return 'no_account_on_host'; 
                   1165:         } else {
                   1166:             &logthis("User $uname at $udom authorized by $uhome");
                   1167:             return $uhome;
                   1168:         }
1.471     albertel 1169:     }
                   1170:     if ($answer eq 'non_authorized') {
                   1171: 	&logthis("User $uname at $udom rejected by $uhome");
                   1172: 	return 'no_host'; 
1.9       www      1173:     }
1.471     albertel 1174:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1175:     return 'no_host';
                   1176: }
                   1177: 
1.1073    raeburn  1178: sub can_host_session {
1.1074    raeburn  1179:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1180:     my $canhost = 1;
1.1074    raeburn  1181:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1182:     if (ref($remotesessions) eq 'HASH') {
                   1183:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1184:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1185:                 $canhost = 0;
                   1186:             } else {
                   1187:                 $canhost = 1;
                   1188:             }
                   1189:         }
                   1190:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1191:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1192:                 $canhost = 1;
                   1193:             } else {
                   1194:                 $canhost = 0;
                   1195:             }
                   1196:         }
                   1197:         if ($canhost) {
                   1198:             if ($remotesessions->{'version'} ne '') {
                   1199:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1200:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1201:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1202:                         my $major = $1;
                   1203:                         my $minor = $2;
                   1204:                         if (($major < $reqmajor ) ||
                   1205:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1206:                             $canhost = 0;
                   1207:                         }
                   1208:                     } else {
                   1209:                         $canhost = 0;
                   1210:                     }
                   1211:                 }
                   1212:             }
                   1213:         }
                   1214:     }
                   1215:     if ($canhost) {
                   1216:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1217:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1218:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1219:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1220:                 if (($uint_dom ne '') && 
                   1221:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1222:                     $canhost = 0;
                   1223:                 } else {
                   1224:                     $canhost = 1;
                   1225:                 }
                   1226:             }
                   1227:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1228:                 if (($uint_dom ne '') && 
                   1229:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1230:                     $canhost = 1;
                   1231:                 } else {
                   1232:                     $canhost = 0;
                   1233:                 }
                   1234:             }
                   1235:         }
                   1236:     }
                   1237:     return $canhost;
                   1238: }
                   1239: 
1.1083    raeburn  1240: sub spare_can_host {
                   1241:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1242:     my $canhost=1;
1.1279    raeburn  1243:     my $try_server_hostname = &hostname($try_server);
                   1244:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1245:     my $serverhomedom = &host_domain($serverhomeID);
                   1246:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1247:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1248:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1249:             $canhost = 0;
                   1250:         }
                   1251:     }
                   1252:     if (($canhost) && ($uint_dom)) {
                   1253:         my @intdoms;
                   1254:         my $internet_names = &get_internet_names($try_server);
                   1255:         if (ref($internet_names) eq 'ARRAY') {
                   1256:             @intdoms = @{$internet_names};
                   1257:         }
                   1258:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1259:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1260:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1261:                                          $remotesessions,
                   1262:                                          $defdomdefaults{'hostedsessions'});
                   1263:         }
1.1083    raeburn  1264:     }
                   1265:     return $canhost;
                   1266: }
                   1267: 
1.1123    raeburn  1268: sub this_host_spares {
                   1269:     my ($dom) = @_;
1.1126    raeburn  1270:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1271:     my @hosts = &current_machine_ids();
                   1272:     foreach my $lonhost (@hosts) {
                   1273:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1274:             $dom_in_use = $dom;
                   1275:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1276:             last;
                   1277:         }
                   1278:     }
1.1126    raeburn  1279:     if ($dom_in_use ne '') {
                   1280:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1281:     }
                   1282:     if (ref($result) ne 'HASH') {
                   1283:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1284:         $dom_in_use = &host_domain($lonhost_in_use);
                   1285:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1286:         if (ref($result) ne 'HASH') {
                   1287:             $result = \%spareid;
                   1288:         }
                   1289:     }
                   1290:     return $result;
                   1291: }
                   1292: 
                   1293: sub spares_for_offload  {
                   1294:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1295:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1296:     if (defined($cached)) {
                   1297:         return $result;
                   1298:     } else {
1.1126    raeburn  1299:         my $cachetime = 60*60*24;
                   1300:         my %domconfig =
                   1301:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1302:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1303:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1304:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1305:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1306:                 }
                   1307:             }
                   1308:         }
                   1309:     }
1.1126    raeburn  1310:     return;
1.1123    raeburn  1311: }
                   1312: 
1.1129    raeburn  1313: sub get_lonbalancer_config {
                   1314:     my ($servers) = @_;
                   1315:     my ($currbalancer,$currtargets);
                   1316:     if (ref($servers) eq 'HASH') {
                   1317:         foreach my $server (keys(%{$servers})) {
                   1318:             my %what = (
                   1319:                          spareid => 1,
                   1320:                          perlvar => 1,
                   1321:                        );
                   1322:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1323:             if ($result eq 'ok') {
                   1324:                 if (ref($returnhash) eq 'HASH') {
                   1325:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1326:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1327:                             $currbalancer = $server;
                   1328:                             $currtargets = {};
                   1329:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1330:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1331:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1332:                                 }
                   1333:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1334:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1335:                                 }
                   1336:                             }
                   1337:                             last;
                   1338:                         }
                   1339:                     }
                   1340:                 }
                   1341:             }
                   1342:         }
                   1343:     }
                   1344:     return ($currbalancer,$currtargets);
                   1345: }
                   1346: 
                   1347: sub check_loadbalancing {
1.1331    raeburn  1348:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1349:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1350:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1351:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1352:     my @hosts = &current_machine_ids();
1.1129    raeburn  1353:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1354:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1355:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1356:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1357:     my $domneedscache;
1.1129    raeburn  1358:     my $cachetime = 60*60*24;
                   1359: 
                   1360:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1361:         $dom_in_use = $udom;
                   1362:         $homeintdom = 1;
                   1363:     } else {
                   1364:         $dom_in_use = $serverhomedom;
                   1365:     }
                   1366:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1367:     unless (defined($cached)) {
                   1368:         my %domconfig =
                   1369:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1370:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1371:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1372:         } else {
                   1373:             $domneedscache = $dom_in_use;
1.1129    raeburn  1374:         }
                   1375:     }
                   1376:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1377:         ($is_balancer,$currtargets,$currrules) = 
                   1378:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1379:         if ($is_balancer) {
                   1380:             if (ref($currrules) eq 'HASH') {
                   1381:                 if ($homeintdom) {
                   1382:                     if ($uname ne '') {
                   1383:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1384:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1385:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1386:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1387:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1388:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1389:                             }
                   1390:                         }
                   1391:                         if ($rule_in_effect eq '') {
                   1392:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1393:                             if ($userenv{'inststatus'} ne '') {
                   1394:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1395:                                 my ($othertitle,$usertypes,$types) =
                   1396:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1397:                                 if (ref($types) eq 'ARRAY') {
                   1398:                                     foreach my $type (@{$types}) {
                   1399:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1400:                                             if (exists($currrules->{$type})) {
                   1401:                                                 $rule_in_effect = $currrules->{$type};
                   1402:                                             }
                   1403:                                         }
                   1404:                                     }
                   1405:                                 }
                   1406:                             } else {
                   1407:                                 if (exists($currrules->{'default'})) {
                   1408:                                     $rule_in_effect = $currrules->{'default'};
                   1409:                                 }
                   1410:                             }
                   1411:                         }
                   1412:                     } else {
                   1413:                         if (exists($currrules->{'default'})) {
                   1414:                             $rule_in_effect = $currrules->{'default'};
                   1415:                         }
                   1416:                     }
                   1417:                 } else {
                   1418:                     if ($currrules->{'_LC_external'} ne '') {
                   1419:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1420:                     }
                   1421:                 }
                   1422:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1423:                                                        $uname,$udom);
                   1424:             }
                   1425:         }
                   1426:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1427:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1428:         unless (defined($cached)) {
                   1429:             my %domconfig =
                   1430:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1431:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1432:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1433:             } else {
                   1434:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1435:             }
                   1436:         }
                   1437:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1438:             ($is_balancer,$currtargets,$currrules) = 
                   1439:                 &check_balancer_result($result,@hosts);
                   1440:             if ($is_balancer) {
1.1129    raeburn  1441:                 if (ref($currrules) eq 'HASH') {
                   1442:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1443:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1444:                     }
                   1445:                 }
                   1446:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1447:                                                        $uname,$udom);
                   1448:             }
                   1449:         } else {
                   1450:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1451:                 $is_balancer = 1;
                   1452:                 $offloadto = &this_host_spares($dom_in_use);
                   1453:             }
1.1307    raeburn  1454:             unless (defined($cached)) {
                   1455:                 $domneedscache = $serverhomedom;
                   1456:             }
1.1129    raeburn  1457:         }
                   1458:     } else {
                   1459:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1460:             $is_balancer = 1;
                   1461:             $offloadto = &this_host_spares($dom_in_use);
                   1462:         }
1.1307    raeburn  1463:         unless (defined($cached)) {
                   1464:             $domneedscache = $serverhomedom;
                   1465:         }
                   1466:     }
                   1467:     if ($domneedscache) {
                   1468:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1469:     }
1.1176    raeburn  1470:     if ($is_balancer) {
                   1471:         my $lowest_load = 30000;
                   1472:         if (ref($offloadto) eq 'HASH') {
                   1473:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1474:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1475:                     ($otherserver,$lowest_load) =
                   1476:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1477:                 }
1.1129    raeburn  1478:             }
1.1176    raeburn  1479:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1480: 
1.1176    raeburn  1481:             if (!$found_server) {
                   1482:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1483:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1484:                         ($otherserver,$lowest_load) =
                   1485:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1486:                     }
                   1487:                 }
                   1488:             }
                   1489:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1490:             if (@{$offloadto} == 1) {
                   1491:                 $otherserver = $offloadto->[0];
                   1492:             } elsif (@{$offloadto} > 1) {
                   1493:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1494:                     ($otherserver,$lowest_load) =
                   1495:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1496:                 }
                   1497:             }
                   1498:         }
1.1331    raeburn  1499:         unless ($caller eq 'login') {
                   1500:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1501:                 $is_balancer = 0;
                   1502:                 if ($uname ne '' && $udom ne '') {
                   1503:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1176    raeburn  1504:                     
1.1331    raeburn  1505:                         &appenv({'user.loadbalexempt'     => $lonhost,  
                   1506:                                  'user.loadbalcheck.time' => time});
                   1507:                     }
1.1176    raeburn  1508:                 }
1.1129    raeburn  1509:             }
                   1510:         }
                   1511:     }
                   1512:     return ($is_balancer,$otherserver);
                   1513: }
                   1514: 
1.1191    raeburn  1515: sub check_balancer_result {
                   1516:     my ($result,@hosts) = @_;
                   1517:     my ($is_balancer,$currtargets,$currrules);
                   1518:     if (ref($result) eq 'HASH') {
                   1519:         if ($result->{'lonhost'} ne '') {
                   1520:             my $currbalancer = $result->{'lonhost'};
                   1521:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1522:                 $is_balancer = 1;
                   1523:                 $currtargets = $result->{'targets'};
                   1524:                 $currrules = $result->{'rules'};
                   1525:             }
                   1526:         } else {
                   1527:             foreach my $key (keys(%{$result})) {
                   1528:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1529:                     (ref($result->{$key}) eq 'HASH')) {
                   1530:                     $is_balancer = 1;
                   1531:                     $currrules = $result->{$key}{'rules'};
                   1532:                     $currtargets = $result->{$key}{'targets'};
                   1533:                     last;
                   1534:                 }
                   1535:             }
                   1536:         }
                   1537:     }
                   1538:     return ($is_balancer,$currtargets,$currrules);
                   1539: }
                   1540: 
1.1129    raeburn  1541: sub get_loadbalancer_targets {
                   1542:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1543:     my $offloadto;
1.1175    raeburn  1544:     if ($rule_in_effect eq 'none') {
                   1545:         return [$perlvar{'lonHostID'}];
                   1546:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1547:         $offloadto = $currtargets;
                   1548:     } else {
                   1549:         if ($rule_in_effect eq 'homeserver') {
                   1550:             my $homeserver = &homeserver($uname,$udom);
                   1551:             if ($homeserver ne 'no_host') {
                   1552:                 $offloadto = [$homeserver];
                   1553:             }
                   1554:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1555:             my %domconfig =
                   1556:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1557:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1558:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1559:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1560:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1561:                     }
                   1562:                 }
                   1563:             } else {
1.1178    raeburn  1564:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1565:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1566:                 if (&hostname($remotebalancer) ne '') {
                   1567:                     $offloadto = [$remotebalancer];
                   1568:                 }
                   1569:             }
                   1570:         } elsif (&hostname($rule_in_effect) ne '') {
                   1571:             $offloadto = [$rule_in_effect];
                   1572:         }
                   1573:     }
                   1574:     return $offloadto;
                   1575: }
                   1576: 
1.1127    raeburn  1577: sub internet_dom_servers {
                   1578:     my ($dom) = @_;
                   1579:     my (%uniqservers,%servers);
                   1580:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1581:     my @machinedoms = &machine_domains($primaryserver);
                   1582:     foreach my $mdom (@machinedoms) {
                   1583:         my %currservers = %servers;
                   1584:         my %server = &get_servers($mdom);
                   1585:         %servers = (%currservers,%server);
                   1586:     }
                   1587:     my %by_hostname;
                   1588:     foreach my $id (keys(%servers)) {
                   1589:         push(@{$by_hostname{$servers{$id}}},$id);
                   1590:     }
                   1591:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1592:         if (@{$by_hostname{$hostname}} > 1) {
                   1593:             my $match = 0;
                   1594:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1595:                 if (&host_domain($id) eq $dom) {
                   1596:                     $uniqservers{$id} = $hostname;
                   1597:                     $match = 1;
                   1598:                 }
                   1599:             }
                   1600:             unless ($match) {
                   1601:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1602:             }
                   1603:         } else {
                   1604:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1605:         }
                   1606:     }
                   1607:     return %uniqservers;
                   1608: }
                   1609: 
1.1347    raeburn  1610: sub trusted_domains {
                   1611:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1612:     my ($trusted,$untrusted);
1.1347    raeburn  1613:     if (&domain($calldom) eq '') {
1.1349    raeburn  1614:         return ($trusted,$untrusted);
1.1347    raeburn  1615:     }
                   1616:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1617:         return ($trusted,$untrusted);
1.1347    raeburn  1618:     }
                   1619:     my $callprimary = &domain($calldom,'primary');
                   1620:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1621:     if ($intcalldom eq '') {
1.1349    raeburn  1622:         return ($trusted,$untrusted);
1.1347    raeburn  1623:     }
                   1624: 
                   1625:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1626:     unless (defined($cached)) {
                   1627:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1628:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1629:         $trustconfig = $domconfig{'trust'};
                   1630:     }
                   1631:     if (ref($trustconfig)) {
                   1632:         my (%possexc,%possinc,@allexc,@allinc); 
                   1633:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1634:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1635:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1636:             }
                   1637:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
                   1638:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1639:             }
                   1640:         }
                   1641:         if (keys(%possexc)) {
                   1642:             if (keys(%possinc)) {
                   1643:                 foreach my $key (sort(keys(%possexc))) {
                   1644:                     next if ($key eq $intcalldom);
                   1645:                     unless ($possinc{$key}) {
                   1646:                         push(@allexc,$key);
                   1647:                     }
                   1648:                 }
                   1649:             } else {
                   1650:                 @allexc = sort(keys(%possexc));
                   1651:             }
                   1652:         }
                   1653:         if (keys(%possinc)) {
                   1654:             $possinc{$intcalldom} = 1;
                   1655:             @allinc = sort(keys(%possinc));
                   1656:         }
                   1657:         if ((@allexc > 0) || (@allinc > 0)) {
                   1658:             my %doms_by_intdom;
                   1659:             my %allintdoms = &all_host_intdom();
                   1660:             my %alldoms = &all_host_domain();
                   1661:             foreach my $key (%allintdoms) {
                   1662:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1663:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1664:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1665:                     }
                   1666:                 } else {
                   1667:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1668:                 }
                   1669:             }
                   1670:             foreach my $exc (@allexc) {
                   1671:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1349    raeburn  1672:                     $untrusted = $doms_by_intdom{$exc};
1.1347    raeburn  1673:                 }
                   1674:             }
                   1675:             foreach my $inc (@allinc) {
                   1676:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1349    raeburn  1677:                     $trusted = $doms_by_intdom{$inc};
1.1347    raeburn  1678:                 }
                   1679:             }
                   1680:         }
                   1681:     }
1.1349    raeburn  1682:     return ($trusted,$untrusted);
1.1347    raeburn  1683: }
                   1684: 
                   1685: sub will_trust {
                   1686:     my ($cmdtype,$domain,$possdom) = @_;
                   1687:     return 1 if ($domain eq $possdom);
                   1688:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1689:     my $willtrust; 
                   1690:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1691:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1692:             $willtrust = 1;
                   1693:         }
                   1694:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1695:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1696:             $willtrust = 1;
                   1697:         }
                   1698:     } else {
                   1699:         $willtrust = 1;
                   1700:     }
                   1701:     return $willtrust;
                   1702: }
                   1703: 
1.1       albertel 1704: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1705: 
1.599     albertel 1706: my %homecache;
1.1       albertel 1707: sub homeserver {
1.230     stredwic 1708:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1709:     my $index="$uname:$udom";
1.426     albertel 1710: 
1.599     albertel 1711:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1712: 
                   1713:     my %servers = &get_servers($udom,'library');
                   1714:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1715:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1716: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1717: 
                   1718: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1719: 	if ($answer eq 'found') {
                   1720: 	    delete($badServerCache{$tryserver}); 
                   1721: 	    return $homecache{$index}=$tryserver;
                   1722: 	} elsif ($answer eq 'no_host') {
                   1723: 	    $badServerCache{$tryserver}=1;
                   1724: 	}
1.1       albertel 1725:     }    
                   1726:     return 'no_host';
1.70      www      1727: }
                   1728: 
1.1300    raeburn  1729: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1730: 
                   1731: sub idget {
1.1300    raeburn  1732:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1733:     my %returnhash=();
1.1300    raeburn  1734:     my @ids=(); 
                   1735:     if (ref($idsref) eq 'ARRAY') {
                   1736:         @ids = @{$idsref};
                   1737:     } else {
                   1738:         return %returnhash; 
                   1739:     }
                   1740:     if ($namespace eq '') {
                   1741:         $namespace = 'ids';
                   1742:     }
1.70      www      1743:     
1.841     albertel 1744:     my %servers = &get_servers($udom,'library');
                   1745:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1746: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1747: 	if ($namespace eq 'ids') {
                   1748: 	    $idlist=~tr/A-Z/a-z/;
                   1749: 	}
                   1750: 	my $reply;
                   1751: 	if ($namespace eq 'ids') {
                   1752: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1753: 	} else {
                   1754: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1755: 	}
1.841     albertel 1756: 	my @answer=();
                   1757: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1758: 	    @answer=split(/\&/,$reply);
                   1759: 	}                    ;
                   1760: 	my $i;
                   1761: 	for ($i=0;$i<=$#ids;$i++) {
                   1762: 	    if ($answer[$i]) {
1.1299    raeburn  1763: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1764: 	    }
1.841     albertel 1765: 	}
1.1300    raeburn  1766:     }
1.70      www      1767:     return %returnhash;
                   1768: }
                   1769: 
                   1770: # ------------------------------------- Find the IDs behind a list of usernames
                   1771: 
                   1772: sub idrget {
                   1773:     my ($udom,@unames)=@_;
                   1774:     my %returnhash=();
1.800     albertel 1775:     foreach my $uname (@unames) {
                   1776:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1777:     }
1.70      www      1778:     return %returnhash;
                   1779: }
                   1780: 
1.1300    raeburn  1781: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1782: 
                   1783: sub idput {
1.1300    raeburn  1784:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1785:     my %servers=();
1.1300    raeburn  1786:     my %ids=();
                   1787:     my %byid = ();
                   1788:     if (ref($idsref) eq 'HASH') {
                   1789:         %ids=%{$idsref};
                   1790:     }
                   1791:     if ($namespace eq '') {
                   1792:         $namespace = 'ids'; 
                   1793:     }
1.800     albertel 1794:     foreach my $uname (keys(%ids)) {
                   1795: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1796:         if ($uhom eq '') {
                   1797:             $uhom=&homeserver($uname,$udom);
                   1798:         }
1.70      www      1799:         if ($uhom ne 'no_host') {
1.800     albertel 1800:             my $esc_unam=&escape($uname);
1.1300    raeburn  1801:             if ($namespace eq 'ids') {
                   1802:                 my $id=&escape($ids{$uname});
                   1803:                 $id=~tr/A-Z/a-z/;
                   1804:                 my $esc_unam=&escape($uname);
                   1805:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1806:             } else {
1.1300    raeburn  1807:                 my @currids = split(/,/,$ids{$uname});
                   1808:                 foreach my $id (@currids) {
                   1809:                     $byid{$uhom}{$id} .= $uname.',';
                   1810:                 }
                   1811:             }
                   1812:         }
                   1813:     }
                   1814:     if ($namespace eq 'clickers') {
                   1815:         foreach my $server (keys(%byid)) {
                   1816:             if (ref($byid{$server}) eq 'HASH') {
                   1817:                 foreach my $id (keys(%{$byid{$server}})) {
                   1818:                     $byid{$server} =~ s/,$//;
                   1819:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1820:                 }
1.70      www      1821:             }
                   1822:         }
1.191     harris41 1823:     }
1.800     albertel 1824:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1825:         $servers{$server} =~ s/\&$//;
                   1826:         if ($namespace eq 'ids') {     
                   1827:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1828:         } else {
                   1829:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1830:         }
1.191     harris41 1831:     }
1.344     www      1832: }
                   1833: 
1.1300    raeburn  1834: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1835: 
                   1836: sub iddel {
1.1300    raeburn  1837:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1838:     my %result=();
1.1300    raeburn  1839:     my %ids=();
                   1840:     my %byid = ();
                   1841:     if (ref($idshashref) eq 'HASH') {
                   1842:         %ids=%{$idshashref};
                   1843:     } else {
1.1231    raeburn  1844:         return %result;
                   1845:     }
1.1300    raeburn  1846:     if ($namespace eq '') {
                   1847:         $namespace = 'ids';
                   1848:     }
1.1231    raeburn  1849:     my %servers=();
1.1300    raeburn  1850:     while (my ($id,$unamestr) = each(%ids)) {
                   1851:         if ($namespace eq 'ids') {
                   1852:             my $uhom = $uhome;
                   1853:             if ($uhom eq '') { 
                   1854:                 $uhom=&homeserver($unamestr,$udom);
                   1855:             }
                   1856:             if ($uhom ne 'no_host') {
                   1857:                 $servers{$uhom}.='&'.&escape($id);
                   1858:             }
                   1859:          } else {
                   1860:             my @curritems = split(/,/,$ids{$id});
                   1861:             foreach my $uname (@curritems) {
                   1862:                 my $uhom = $uhome;
                   1863:                 if ($uhom eq '') {
                   1864:                     $uhom=&homeserver($uname,$udom);
                   1865:                 }
                   1866:                 if ($uhom ne 'no_host') { 
                   1867:                     $byid{$uhom}{$id} .= $uname.',';
                   1868:                 }
                   1869:             }
1.1231    raeburn  1870:         }
1.1300    raeburn  1871:     }
                   1872:     if ($namespace eq 'clickers') {
                   1873:         foreach my $server (keys(%byid)) {
                   1874:             if (ref($byid{$server}) eq 'HASH') {
                   1875:                 foreach my $id (keys(%{$byid{$server}})) {
                   1876:                     $byid{$server}{$id} =~ s/,$//;
                   1877:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   1878:                 }
1.1231    raeburn  1879:             }
                   1880:         }
                   1881:     }
                   1882:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1883:         $servers{$server} =~ s/\&$//;
                   1884:         if ($namespace eq 'ids') {
                   1885:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1886:         } elsif ($namespace eq 'clickers') {
                   1887:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   1888:         }
1.1231    raeburn  1889:     }
                   1890:     return %result;
                   1891: }
                   1892: 
1.1300    raeburn  1893: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   1894: 
                   1895: sub updateclickers {
                   1896:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   1897:     my %clickers;
                   1898:     if (ref($idshashref) eq 'HASH') {
                   1899:         %clickers=%{$idshashref};
                   1900:     } else {
                   1901:         return;
                   1902:     }
                   1903:     my $items='';
                   1904:     foreach my $item (keys(%clickers)) {
                   1905:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   1906:     }
                   1907:     $items=~s/\&$//;
                   1908:     my $request = "updateclickers:$udom:$action:$items";
                   1909:     if ($critical) {
                   1910:         return &critical($request,$uhome);
                   1911:     } else {
                   1912:         return &reply($request,$uhome);
                   1913:     }
                   1914: }
                   1915: 
1.1023    raeburn  1916: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1917: sub dump_dom {
1.1165    droeschl 1918:     my ($namespace, $udom, $regexp) = @_;
                   1919: 
                   1920:     $udom ||= $env{'user.domain'};
                   1921: 
                   1922:     return () unless $udom;
                   1923: 
                   1924:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1925: }
                   1926: 
1.1023    raeburn  1927: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1928: 
                   1929: sub get_dom {
1.860     raeburn  1930:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  1931:     return if ($udom eq 'public');
1.806     raeburn  1932:     my $items='';
                   1933:     foreach my $item (@$storearr) {
                   1934:         $items.=&escape($item).'&';
                   1935:     }
                   1936:     $items=~s/\&$//;
1.860     raeburn  1937:     if (!$udom) {
                   1938:         $udom=$env{'user.domain'};
1.1267    raeburn  1939:         return if ($udom eq 'public');
1.860     raeburn  1940:         if (defined(&domain($udom,'primary'))) {
                   1941:             $uhome=&domain($udom,'primary');
                   1942:         } else {
1.874     albertel 1943:             undef($uhome);
1.860     raeburn  1944:         }
                   1945:     } else {
                   1946:         if (!$uhome) {
                   1947:             if (defined(&domain($udom,'primary'))) {
                   1948:                 $uhome=&domain($udom,'primary');
                   1949:             }
                   1950:         }
                   1951:     }
                   1952:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  1953:         my $rep;
                   1954:         if ($namespace =~ /^enc/) {
                   1955:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   1956:         } else {
                   1957:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1958:         }
1.866     raeburn  1959:         my %returnhash;
1.875     albertel 1960:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1961:             return %returnhash;
                   1962:         }
1.806     raeburn  1963:         my @pairs=split(/\&/,$rep);
                   1964:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1965:             return @pairs;
                   1966:         }
                   1967:         my $i=0;
                   1968:         foreach my $item (@$storearr) {
                   1969:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1970:             $i++;
                   1971:         }
                   1972:         return %returnhash;
                   1973:     } else {
1.880     banghart 1974:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1975:     }
                   1976: }
                   1977: 
                   1978: # -------------------------------------------- put items in domain db files 
                   1979: 
                   1980: sub put_dom {
1.860     raeburn  1981:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1982:     if (!$udom) {
                   1983:         $udom=$env{'user.domain'};
                   1984:         if (defined(&domain($udom,'primary'))) {
                   1985:             $uhome=&domain($udom,'primary');
                   1986:         } else {
1.874     albertel 1987:             undef($uhome);
1.860     raeburn  1988:         }
                   1989:     } else {
                   1990:         if (!$uhome) {
                   1991:             if (defined(&domain($udom,'primary'))) {
                   1992:                 $uhome=&domain($udom,'primary');
                   1993:             }
                   1994:         }
                   1995:     } 
                   1996:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1997:         my $items='';
                   1998:         foreach my $item (keys(%$storehash)) {
                   1999:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2000:         }
                   2001:         $items=~s/\&$//;
1.1344    raeburn  2002:         if ($namespace =~ /^enc/) {
                   2003:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2004:         } else {
                   2005:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2006:         }
1.806     raeburn  2007:     } else {
1.860     raeburn  2008:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2009:     }
                   2010: }
                   2011: 
1.1023    raeburn  2012: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2013: sub newput_dom {
1.1023    raeburn  2014:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2015:     my $result;
                   2016:     if (!$udom) {
                   2017:         $udom=$env{'user.domain'};
                   2018:     }
1.1023    raeburn  2019:     if ($udom) {
                   2020:         my $uname = &get_domainconfiguser($udom);
                   2021:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2022:     }
                   2023:     return $result;
                   2024: }
                   2025: 
1.1023    raeburn  2026: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2027: sub del_dom {
1.1023    raeburn  2028:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2029:     if (ref($storearr) eq 'ARRAY') {
                   2030:         if (!$udom) {
                   2031:             $udom=$env{'user.domain'};
                   2032:         }
1.1023    raeburn  2033:         if ($udom) {
                   2034:             my $uname = &get_domainconfiguser($udom); 
                   2035:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2036:         }
                   2037:     }
                   2038: }
                   2039: 
1.1023    raeburn  2040: # ----------------------------------construct domainconfig user for a domain 
                   2041: sub get_domainconfiguser {
                   2042:     my ($udom) = @_;
                   2043:     return $udom.'-domainconfig';
                   2044: }
                   2045: 
1.837     raeburn  2046: sub retrieve_inst_usertypes {
                   2047:     my ($udom) = @_;
                   2048:     my (%returnhash,@order);
1.989     raeburn  2049:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2050:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2051:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2052:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2053:     } else {
                   2054:         if (defined(&domain($udom,'primary'))) {
                   2055:             my $uhome=&domain($udom,'primary');
                   2056:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2057:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2058:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2059:                 return (\%returnhash,\@order);
                   2060:             }
                   2061:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2062:             my @pairs=split(/\&/,$hashitems);
                   2063:             foreach my $item (@pairs) {
                   2064:                 my ($key,$value)=split(/=/,$item,2);
                   2065:                 $key = &unescape($key);
                   2066:                 next if ($key =~ /^error: 2 /);
                   2067:                 $returnhash{$key}=&thaw_unescape($value);
                   2068:             }
                   2069:             my @esc_order = split(/\&/,$orderitems);
                   2070:             foreach my $item (@esc_order) {
                   2071:                 push(@order,&unescape($item));
                   2072:             }
                   2073:         } else {
1.1256    raeburn  2074:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2075:         }
1.1256    raeburn  2076:         return (\%returnhash,\@order);
1.837     raeburn  2077:     }
                   2078: }
                   2079: 
1.868     raeburn  2080: sub is_domainimage {
                   2081:     my ($url) = @_;
1.1306    raeburn  2082:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2083:         if (&domain($1) ne '') {
                   2084:             return '1';
                   2085:         }
                   2086:     }
                   2087:     return;
                   2088: }
                   2089: 
1.899     raeburn  2090: sub inst_directory_query {
                   2091:     my ($srch) = @_;
                   2092:     my $udom = $srch->{'srchdomain'};
                   2093:     my %results;
                   2094:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2095:     my $outcome;
1.899     raeburn  2096:     if ($homeserver ne '') {
1.1357    raeburn  2097:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2098:             if ($srch->{'srchby'} eq 'email') {
                   2099:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
                   2100:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2101:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2102:                     (($major == 2) && ($minor < 12))) {
                   2103:                     return;
                   2104:                 }
                   2105:             }
                   2106:         }
1.904     albertel 2107: 	my $queryid=&reply("querysend:instdirsearch:".
                   2108: 			   &escape($srch->{'srchby'}).':'.
                   2109: 			   &escape($srch->{'srchterm'}).':'.
                   2110: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2111: 	my $host=&hostname($homeserver);
                   2112: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2113: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2114: 	    return;
                   2115: 	}
                   2116: 	my $response = &get_query_reply($queryid);
                   2117: 	my $maxtries = 5;
                   2118: 	my $tries = 1;
                   2119: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2120: 	    $response = &get_query_reply($queryid);
                   2121: 	    $tries ++;
                   2122: 	}
                   2123: 
                   2124:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2125:             if ($response eq 'unavailable') {
                   2126:                 $outcome = $response;
                   2127:             } else {
                   2128:                 $outcome = 'ok';
                   2129:                 my @matches = split(/\n/,$response);
                   2130:                 foreach my $match (@matches) {
                   2131:                     my ($key,$value) = split(/=/,$match);
                   2132:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2133:                 }
1.899     raeburn  2134:             }
                   2135:         }
                   2136:     }
1.909     raeburn  2137:     return ($outcome,%results);
1.899     raeburn  2138: }
                   2139: 
                   2140: sub usersearch {
                   2141:     my ($srch) = @_;
                   2142:     my $dom = $srch->{'srchdomain'};
                   2143:     my %results;
                   2144:     my %libserv = &all_library();
                   2145:     my $query = 'usersearch';
                   2146:     foreach my $tryserver (keys(%libserv)) {
                   2147:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2148:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2149:                 if ($srch->{'srchby'} eq 'email') {
                   2150:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
                   2151:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2152:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2153:                              (($major == 2) && ($minor < 12)));
                   2154:                 }
                   2155:             }
1.899     raeburn  2156:             my $host=&hostname($tryserver);
                   2157:             my $queryid=
1.911     raeburn  2158:                 &reply("querysend:".&escape($query).':'.
                   2159:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2160:                        &escape($srch->{'srchtype'}).':'.
                   2161:                        &escape($srch->{'srchterm'}),$tryserver);
                   2162:             if ($queryid !~/^\Q$host\E\_/) {
                   2163:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2164:                 next;
1.899     raeburn  2165:             }
                   2166:             my $reply = &get_query_reply($queryid);
                   2167:             my $maxtries = 1;
                   2168:             my $tries = 1;
                   2169:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2170:                 $reply = &get_query_reply($queryid);
                   2171:                 $tries ++;
                   2172:             }
                   2173:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2174:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2175:             } else {
1.911     raeburn  2176:                 my @matches;
                   2177:                 if ($reply =~ /\n/) {
                   2178:                     @matches = split(/\n/,$reply);
                   2179:                 } else {
                   2180:                     @matches = split(/\&/,$reply);
                   2181:                 }
1.899     raeburn  2182:                 foreach my $match (@matches) {
                   2183:                     my ($uname,$udom,%userhash);
1.911     raeburn  2184:                     foreach my $entry (split(/:/,$match)) {
                   2185:                         my ($key,$value) =
                   2186:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2187:                         $userhash{$key} = $value;
                   2188:                         if ($key eq 'username') {
                   2189:                             $uname = $value;
                   2190:                         } elsif ($key eq 'domain') {
                   2191:                             $udom = $value;
1.911     raeburn  2192:                         }
1.899     raeburn  2193:                     }
                   2194:                     $results{$uname.':'.$udom} = \%userhash;
                   2195:                 }
                   2196:             }
                   2197:         }
                   2198:     }
                   2199:     return %results;
                   2200: }
                   2201: 
1.912     raeburn  2202: sub get_instuser {
                   2203:     my ($udom,$uname,$id) = @_;
                   2204:     my $homeserver = &domain($udom,'primary');
                   2205:     my ($outcome,%results);
                   2206:     if ($homeserver ne '') {
                   2207:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2208:                            &escape($id).':'.&escape($udom),$homeserver);
                   2209:         my $host=&hostname($homeserver);
                   2210:         if ($queryid !~/^\Q$host\E\_/) {
                   2211:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2212:             return;
                   2213:         }
                   2214:         my $response = &get_query_reply($queryid);
                   2215:         my $maxtries = 5;
                   2216:         my $tries = 1;
                   2217:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2218:             $response = &get_query_reply($queryid);
                   2219:             $tries ++;
                   2220:         }
                   2221:         if (!&error($response) && $response ne 'refused') {
                   2222:             if ($response eq 'unavailable') {
                   2223:                 $outcome = $response;
                   2224:             } else {
                   2225:                 $outcome = 'ok';
                   2226:                 my @matches = split(/\n/,$response);
                   2227:                 foreach my $match (@matches) {
                   2228:                     my ($key,$value) = split(/=/,$match);
                   2229:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2230:                 }
                   2231:             }
                   2232:         }
                   2233:     }
                   2234:     my %userinfo;
                   2235:     if (ref($results{$uname}) eq 'HASH') {
                   2236:         %userinfo = %{$results{$uname}};
                   2237:     } 
                   2238:     return ($outcome,%userinfo);
                   2239: }
                   2240: 
1.1290    raeburn  2241: sub get_multiple_instusers {
                   2242:     my ($udom,$users,$caller) = @_;
                   2243:     my ($outcome,$results);
                   2244:     if (ref($users) eq 'HASH') {
                   2245:         my $count = keys(%{$users}); 
                   2246:         my $requested = &freeze_escape($users);
                   2247:         my $homeserver = &domain($udom,'primary');
                   2248:         if ($homeserver ne '') {
                   2249:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2250:             my $host=&hostname($homeserver);
                   2251:             if ($queryid !~/^\Q$host\E\_/) {
                   2252:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2253:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2254:                 return ($outcome,$results);
                   2255:             }
                   2256:             my $response = &get_query_reply($queryid);
                   2257:             my $maxtries = 5;
                   2258:             if ($count > 100) {
                   2259:                 $maxtries = 1+int($count/20);
                   2260:             }
                   2261:             my $tries = 1;
                   2262:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2263:                 $response = &get_query_reply($queryid);
                   2264:                 $tries ++;
                   2265:             }
                   2266:             if ($response eq '') {
                   2267:                 $results = {};
                   2268:                 foreach my $key (keys(%{$users})) {
                   2269:                     my ($uname,$id);
                   2270:                     if ($caller eq 'id') {
                   2271:                         $id = $key;
                   2272:                     } else {
                   2273:                         $uname = $key;
                   2274:                     }
                   2275:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2276:                     $outcome = $resp;
1.1290    raeburn  2277:                     if ($resp eq 'ok') {
                   2278:                         %{$results} = (%{$results}, %info);
                   2279:                     } else {
                   2280:                         last;
                   2281:                     }
                   2282:                 }
                   2283:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2284:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2285:                     $outcome = $response;
                   2286:                 } else {
1.1291    raeburn  2287:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2288:                     if ($outcome eq 'ok') {
                   2289:                         $results = &thaw_unescape($userdata); 
                   2290:                     }
                   2291:                 }
                   2292:             }
                   2293:         }
                   2294:     }
                   2295:     return ($outcome,$results);
                   2296: }
                   2297: 
1.912     raeburn  2298: sub inst_rulecheck {
1.923     raeburn  2299:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2300:     my %returnhash;
                   2301:     if ($udom ne '') {
                   2302:         if (ref($rules) eq 'ARRAY') {
                   2303:             @{$rules} = map {&escape($_);} (@{$rules});
                   2304:             my $rulestr = join(':',@{$rules});
                   2305:             my $homeserver=&domain($udom,'primary');
                   2306:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2307:                 my $response;
                   2308:                 if ($item eq 'username') {                
                   2309:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2310:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2311:                                               $homeserver));
1.923     raeburn  2312:                 } elsif ($item eq 'id') {
                   2313:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2314:                                               ':'.&escape($id).':'.$rulestr,
                   2315:                                               $homeserver));
1.945     raeburn  2316:                 } elsif ($item eq 'selfcreate') {
                   2317:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2318:                                                &escape($udom).':'.&escape($uname).
                   2319:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2320:                 }
1.912     raeburn  2321:                 if ($response ne 'refused') {
                   2322:                     my @pairs=split(/\&/,$response);
                   2323:                     foreach my $item (@pairs) {
                   2324:                         my ($key,$value)=split(/=/,$item,2);
                   2325:                         $key = &unescape($key);
                   2326:                         next if ($key =~ /^error: 2 /);
                   2327:                         $returnhash{$key}=&thaw_unescape($value);
                   2328:                     }
                   2329:                 }
                   2330:             }
                   2331:         }
                   2332:     }
                   2333:     return %returnhash;
                   2334: }
                   2335: 
                   2336: sub inst_userrules {
1.923     raeburn  2337:     my ($udom,$check) = @_;
1.912     raeburn  2338:     my (%ruleshash,@ruleorder);
                   2339:     if ($udom ne '') {
                   2340:         my $homeserver=&domain($udom,'primary');
                   2341:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2342:             my $response;
                   2343:             if ($check eq 'id') {
                   2344:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2345:                                  $homeserver);
1.943     raeburn  2346:             } elsif ($check eq 'email') {
                   2347:                 $response=&reply('instemailrules:'.&escape($udom),
                   2348:                                  $homeserver);
1.923     raeburn  2349:             } else {
                   2350:                 $response=&reply('instuserrules:'.&escape($udom),
                   2351:                                  $homeserver);
                   2352:             }
1.912     raeburn  2353:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2354:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2355:                 ($response ne 'no_such_host')) {
                   2356:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2357:                 my @pairs=split(/\&/,$hashitems);
                   2358:                 foreach my $item (@pairs) {
                   2359:                     my ($key,$value)=split(/=/,$item,2);
                   2360:                     $key = &unescape($key);
                   2361:                     next if ($key =~ /^error: 2 /);
                   2362:                     $ruleshash{$key}=&thaw_unescape($value);
                   2363:                 }
                   2364:                 my @esc_order = split(/\&/,$orderitems);
                   2365:                 foreach my $item (@esc_order) {
                   2366:                     push(@ruleorder,&unescape($item));
                   2367:                 }
                   2368:             }
                   2369:         }
                   2370:     }
                   2371:     return (\%ruleshash,\@ruleorder);
                   2372: }
                   2373: 
1.976     raeburn  2374: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2375: 
                   2376: sub get_domain_defaults {
1.1240    raeburn  2377:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2378:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2379:     my $cachetime = 60*60*24;
1.1240    raeburn  2380:     unless ($ignore_cache) {
                   2381:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2382:         if (defined($cached)) {
                   2383:             if (ref($result) eq 'HASH') {
                   2384:                 return %{$result};
                   2385:             }
1.943     raeburn  2386:         }
                   2387:     }
                   2388:     my %domdefaults;
                   2389:     my %domconfig =
1.989     raeburn  2390:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2391:                                   'requestcourses','inststatus',
1.1183    raeburn  2392:                                   'coursedefaults','usersessions',
1.1258    raeburn  2393:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2394:                                   'coursecategories','ssl','autoenroll',
1.1332    raeburn  2395:                                   'trust','helpsettings'],$domain);
1.1305    raeburn  2396:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2397:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2398:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2399:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2400:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2401:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2402:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2403:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2404:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2405:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2406:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2407:     } else {
                   2408:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2409:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2410:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2411:     }
1.976     raeburn  2412:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2413:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2414:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2415:         } else {
                   2416:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2417:         }
1.1177    raeburn  2418:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2419:         foreach my $item (@usertools) {
                   2420:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2421:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2422:             }
                   2423:         }
1.1229    raeburn  2424:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2425:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2426:         }
1.976     raeburn  2427:     }
1.985     raeburn  2428:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2429:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2430:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2431:         }
                   2432:     }
1.1183    raeburn  2433:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2434:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2435:     }
1.989     raeburn  2436:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2437:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2438:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2439:         }
                   2440:     }
1.1047    raeburn  2441:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2442:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2443:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2444:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2445:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2446:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2447:         }
1.1254    raeburn  2448:         foreach my $type (@coursetypes) {
                   2449:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2450:                 unless ($type eq 'community') {
                   2451:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2452:                 }
                   2453:             }
                   2454:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2455:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2456:             }
1.1277    raeburn  2457:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2458:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2459:                     $domdefaults{$type.'postsubtimeout'} = 
                   2460:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2461:                 }
                   2462:             }
1.1230    raeburn  2463:         }
1.1286    raeburn  2464:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2465:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2466:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2467:                 if (@clonecodes) {
                   2468:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2469:                 }
                   2470:             }
                   2471:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2472:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2473:         }
1.1356    raeburn  2474:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2475:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2476:         } 
1.1047    raeburn  2477:     }
1.1073    raeburn  2478:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2479:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2480:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2481:         }
                   2482:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2483:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2484:         }
1.1279    raeburn  2485:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2486:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2487:         }
1.1073    raeburn  2488:     }
1.1254    raeburn  2489:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2490:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2491:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2492:                             'approval','limit');
                   2493:             foreach my $type (@coursetypes) {
                   2494:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2495:                     my @mgrdc = ();
                   2496:                     foreach my $item (@settings) {
                   2497:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2498:                             push(@mgrdc,$item);
                   2499:                         }
                   2500:                     }
                   2501:                     if (@mgrdc) {
                   2502:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2503:                     }
                   2504:                 }
                   2505:             }
                   2506:         }
                   2507:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2508:             foreach my $type (@coursetypes) {
                   2509:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2510:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2511:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2512:                     }
                   2513:                 }
                   2514:             }
                   2515:         }
                   2516:     }
1.1258    raeburn  2517:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2518:         $domdefaults{'catauth'} = 'std';
                   2519:         $domdefaults{'catunauth'} = 'std';
                   2520:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2521:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2522:         }
                   2523:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2524:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2525:         }
                   2526:     }
1.1315    raeburn  2527:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2528:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2529:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2530:         }
1.1338    raeburn  2531:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2532:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2533:         }
                   2534:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2535:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2536:         }
                   2537:     }
1.1320    raeburn  2538:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2539:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2540:         foreach my $prefix (@prefixes) {
                   2541:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2542:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2543:             }
                   2544:         }
                   2545:     }
1.1314    raeburn  2546:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2547:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2548:     }
1.1332    raeburn  2549:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2550:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2551:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2552:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2553:         }
                   2554:     }
1.1219    raeburn  2555:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2556:     return %domdefaults;
                   2557: }
                   2558: 
1.1311    raeburn  2559: sub course_portal_url {
                   2560:     my ($cnum,$cdom) = @_;
                   2561:     my $chome = &homeserver($cnum,$cdom);
                   2562:     my $hostname = &hostname($chome);
                   2563:     my $protocol = $protocol{$chome};
                   2564:     $protocol = 'http' if ($protocol ne 'https');
                   2565:     my %domdefaults = &get_domain_defaults($cdom);
                   2566:     my $firsturl;
                   2567:     if ($domdefaults{'portal_def'}) {
                   2568:         $firsturl = $domdefaults{'portal_def'};
                   2569:     } else {
                   2570:         $firsturl = $protocol.'://'.$hostname;
                   2571:     }
                   2572:     return $firsturl;
                   2573: }
                   2574: 
1.344     www      2575: # --------------------------------------------------- Assign a key to a student
                   2576: 
                   2577: sub assign_access_key {
1.364     www      2578: #
                   2579: # a valid key looks like uname:udom#comments
                   2580: # comments are being appended
                   2581: #
1.498     www      2582:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2583:     $kdom=
1.620     albertel 2584:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2585:     $knum=
1.620     albertel 2586:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2587:     $cdom=
1.620     albertel 2588:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2589:     $cnum=
1.620     albertel 2590:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2591:     $udom=$env{'user.name'} unless (defined($udom));
                   2592:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2593:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2594:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2595:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2596:                                                   # assigned to this person
                   2597:                                                   # - this should not happen,
1.345     www      2598:                                                   # unless something went wrong
                   2599:                                                   # the first time around
                   2600: # ready to assign
1.364     www      2601:         $logentry=$1.'; '.$logentry;
1.496     www      2602:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2603:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2604: # key now belongs to user
1.346     www      2605: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2606:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2607:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2608:                 return 'ok';
                   2609:             } else {
                   2610:                 return 
                   2611:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2612: 	    }
                   2613:         } else {
                   2614:             return 'error: Could not assign key, try again later.';
                   2615:         }
1.364     www      2616:     } elsif (!$existing{$ckey}) {
1.345     www      2617: # the key does not exist
                   2618: 	return 'error: The key does not exist';
                   2619:     } else {
                   2620: # the key is somebody else's
                   2621: 	return 'error: The key is already in use';
                   2622:     }
1.344     www      2623: }
                   2624: 
1.364     www      2625: # ------------------------------------------ put an additional comment on a key
                   2626: 
                   2627: sub comment_access_key {
                   2628: #
                   2629: # a valid key looks like uname:udom#comments
                   2630: # comments are being appended
                   2631: #
                   2632:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2633:     $cdom=
1.620     albertel 2634:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2635:     $cnum=
1.620     albertel 2636:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2637:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2638:     if ($existing{$ckey}) {
                   2639:         $existing{$ckey}.='; '.$logentry;
                   2640: # ready to assign
1.367     www      2641:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2642:                                                  $cdom,$cnum) eq 'ok') {
                   2643: 	    return 'ok';
                   2644:         } else {
                   2645: 	    return 'error: Count not store comment.';
                   2646:         }
                   2647:     } else {
                   2648: # the key does not exist
                   2649: 	return 'error: The key does not exist';
                   2650:     }
                   2651: }
                   2652: 
1.344     www      2653: # ------------------------------------------------------ Generate a set of keys
                   2654: 
                   2655: sub generate_access_keys {
1.364     www      2656:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2657:     $cdom=
1.620     albertel 2658:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2659:     $cnum=
1.620     albertel 2660:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2661:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2662:     unless (($cdom) && ($cnum)) { return 0; }
                   2663:     if ($number>10000) { return 0; }
                   2664:     sleep(2); # make sure don't get same seed twice
                   2665:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2666:     my $total=0;
                   2667:     for (my $i=1;$i<=$number;$i++) {
                   2668:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2669:                   sprintf("%lx",int(100000*rand)).'-'.
                   2670:                   sprintf("%lx",int(100000*rand));
                   2671:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2672:        $newkey=~s/0/h/g; # and also 0 and O
                   2673:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2674:        if ($existing{$newkey}) {
                   2675:            $i--;
                   2676:        } else {
1.364     www      2677: 	  if (&put('accesskeys',
                   2678:               { $newkey => '# generated '.localtime().
1.620     albertel 2679:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2680:                            '; '.$logentry },
                   2681: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2682:               $total++;
                   2683: 	  }
                   2684:        }
                   2685:     }
1.620     albertel 2686:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2687:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2688:     return $total;
                   2689: }
                   2690: 
                   2691: # ------------------------------------------------------- Validate an accesskey
                   2692: 
                   2693: sub validate_access_key {
                   2694:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2695:     $cdom=
1.620     albertel 2696:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2697:     $cnum=
1.620     albertel 2698:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2699:     $udom=$env{'user.domain'} unless (defined($udom));
                   2700:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2701:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2702:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2703: }
                   2704: 
                   2705: # ------------------------------------- Find the section of student in a course
1.652     albertel 2706: sub devalidate_getsection_cache {
                   2707:     my ($udom,$unam,$courseid)=@_;
                   2708:     my $hashid="$udom:$unam:$courseid";
                   2709:     &devalidate_cache_new('getsection',$hashid);
                   2710: }
1.298     matthew  2711: 
1.815     albertel 2712: sub courseid_to_courseurl {
                   2713:     my ($courseid) = @_;
                   2714:     #already url style courseid
                   2715:     return $courseid if ($courseid =~ m{^/});
                   2716: 
                   2717:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2718: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2719: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2720: 	return "/$cdom/$cnum";
                   2721:     }
                   2722: 
                   2723:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2724:     if (exists($courseinfo{'num'})) {
                   2725: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2726:     }
                   2727: 
                   2728:     return undef;
                   2729: }
                   2730: 
1.298     matthew  2731: sub getsection {
                   2732:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2733:     my $cachetime=1800;
1.551     albertel 2734: 
                   2735:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2736:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2737:     if (defined($cached)) { return $result; }
                   2738: 
1.298     matthew  2739:     my %Pending; 
                   2740:     my %Expired;
                   2741:     #
                   2742:     # Each role can either have not started yet (pending), be active, 
                   2743:     #    or have expired.
                   2744:     #
                   2745:     # If there is an active role, we are done.
                   2746:     #
                   2747:     # If there is more than one role which has not started yet, 
                   2748:     #     choose the one which will start sooner
                   2749:     # If there is one role which has not started yet, return it.
                   2750:     #
                   2751:     # If there is more than one expired role, choose the one which ended last.
                   2752:     # If there is a role which has expired, return it.
                   2753:     #
1.815     albertel 2754:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2755:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2756:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2757:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2758:         my $section=$1;
                   2759:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2760:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2761:         my $now=time;
1.548     albertel 2762:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2763:             $Expired{$end}=$section;
                   2764:             next;
                   2765:         }
1.548     albertel 2766:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2767:             $Pending{$start}=$section;
                   2768:             next;
                   2769:         }
1.599     albertel 2770:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2771:     }
                   2772:     #
                   2773:     # Presumedly there will be few matching roles from the above
                   2774:     # loop and the sorting time will be negligible.
                   2775:     if (scalar(keys(%Pending))) {
                   2776:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2777:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2778:     } 
                   2779:     if (scalar(keys(%Expired))) {
                   2780:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2781:         my $time = pop(@sorted);
1.599     albertel 2782:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2783:     }
1.599     albertel 2784:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2785: }
1.70      www      2786: 
1.599     albertel 2787: sub save_cache {
                   2788:     &purge_remembered();
1.722     albertel 2789:     #&Apache::loncommon::validate_page();
1.620     albertel 2790:     undef(%env);
1.780     albertel 2791:     undef($env_loaded);
1.599     albertel 2792: }
1.452     albertel 2793: 
1.599     albertel 2794: my $to_remember=-1;
                   2795: my %remembered;
                   2796: my %accessed;
                   2797: my $kicks=0;
                   2798: my $hits=0;
1.849     albertel 2799: sub make_key {
                   2800:     my ($name,$id) = @_;
1.872     albertel 2801:     if (length($id) > 65 
                   2802: 	&& length(&escape($id)) > 200) {
                   2803: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2804:     }
1.849     albertel 2805:     return &escape($name.':'.$id);
                   2806: }
                   2807: 
1.599     albertel 2808: sub devalidate_cache_new {
                   2809:     my ($name,$id,$debug) = @_;
                   2810:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  2811:     my $remembered_id=$name.':'.$id;
1.849     albertel 2812:     $id=&make_key($name,$id);
1.599     albertel 2813:     $memcache->delete($id);
1.1319    damieng  2814:     delete($remembered{$remembered_id});
                   2815:     delete($accessed{$remembered_id});
1.599     albertel 2816: }
                   2817: 
                   2818: sub is_cached_new {
                   2819:     my ($name,$id,$debug) = @_;
1.1319    damieng  2820:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   2821:     if (exists($remembered{$remembered_id})) {
                   2822: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2823: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2824: 	$hits++;
1.1319    damieng  2825: 	return ($remembered{$remembered_id},1);
1.599     albertel 2826:     }
1.1319    damieng  2827:     $id=&make_key($name,$id);
1.599     albertel 2828:     my $value = $memcache->get($id);
                   2829:     if (!(defined($value))) {
                   2830: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2831: 	return (undef,undef);
1.416     albertel 2832:     }
1.599     albertel 2833:     if ($value eq '__undef__') {
                   2834: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2835: 	$value=undef;
                   2836:     }
1.1319    damieng  2837:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2838:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2839:     return ($value,1);
                   2840: }
                   2841: 
                   2842: sub do_cache_new {
                   2843:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  2844:     my $remembered_id=$name.':'.$id;
1.849     albertel 2845:     $id=&make_key($name,$id);
1.599     albertel 2846:     my $setvalue=$value;
                   2847:     if (!defined($setvalue)) {
                   2848: 	$setvalue='__undef__';
                   2849:     }
1.623     albertel 2850:     if (!defined($time) ) {
                   2851: 	$time=600;
                   2852:     }
1.599     albertel 2853:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2854:     my $result = $memcache->set($id,$setvalue,$time);
                   2855:     if (! $result) {
1.872     albertel 2856: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2857: 	$memcache->disconnect_all();
1.872     albertel 2858:     }
1.600     albertel 2859:     # need to make a copy of $value
1.1319    damieng  2860:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2861:     return $value;
                   2862: }
                   2863: 
                   2864: sub make_room {
1.1319    damieng  2865:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2866: 
1.1319    damieng  2867:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2868:                                     : $value;
1.599     albertel 2869:     if ($to_remember<0) { return; }
1.1319    damieng  2870:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2871:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2872:     my $to_kick;
                   2873:     my $max_time=0;
                   2874:     foreach my $other (keys(%accessed)) {
                   2875: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2876: 	    $to_kick=$other;
                   2877: 	    $max_time=&tv_interval($accessed{$other});
                   2878: 	}
                   2879:     }
                   2880:     delete($remembered{$to_kick});
                   2881:     delete($accessed{$to_kick});
                   2882:     $kicks++;
                   2883:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2884:     return;
                   2885: }
                   2886: 
1.599     albertel 2887: sub purge_remembered {
1.604     albertel 2888:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2889:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2890:     undef(%remembered);
                   2891:     undef(%accessed);
1.428     albertel 2892: }
1.70      www      2893: # ------------------------------------- Read an entry from a user's environment
                   2894: 
                   2895: sub userenvironment {
                   2896:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2897:     my $items;
                   2898:     foreach my $item (@what) {
                   2899:         $items.=&escape($item).'&';
                   2900:     }
                   2901:     $items=~s/\&$//;
1.70      www      2902:     my %returnhash=();
1.1009    raeburn  2903:     my $uhome = &homeserver($unam,$udom);
                   2904:     unless ($uhome eq 'no_host') {
                   2905:         my @answer=split(/\&/, 
                   2906:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2907:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2908:             return %returnhash;
                   2909:         }
1.1009    raeburn  2910:         my $i;
                   2911:         for ($i=0;$i<=$#what;$i++) {
                   2912: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2913:         }
1.70      www      2914:     }
                   2915:     return %returnhash;
1.1       albertel 2916: }
                   2917: 
1.617     albertel 2918: # ---------------------------------------------------------- Get a studentphoto
                   2919: sub studentphoto {
                   2920:     my ($udom,$unam,$ext) = @_;
                   2921:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2922:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2923:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2924:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2925:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2926:             } else {
                   2927:                 my ($result,$perm_reqd)=
1.707     albertel 2928: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2929:                 if ($result eq 'ok') {
                   2930:                     if (!($perm_reqd eq 'yes')) {
                   2931:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2932:                     }
                   2933:                 }
                   2934:             }
                   2935:         }
                   2936:     } else {
                   2937:         my ($result,$perm_reqd) = 
1.707     albertel 2938: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2939:         if ($result eq 'ok') {
                   2940:             if (!($perm_reqd eq 'yes')) {
                   2941:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2942:             }
                   2943:         }
                   2944:     }
                   2945:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2946: }
                   2947: 
                   2948: sub retrievestudentphoto {
                   2949:     my ($udom,$unam,$ext,$type) = @_;
                   2950:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2951:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2952:     if ($ret eq 'ok') {
                   2953:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2954:         if ($type eq 'thumbnail') {
                   2955:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2956:         }
                   2957:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2958:         return $tokenurl;
                   2959:     } else {
                   2960:         if ($type eq 'thumbnail') {
                   2961:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2962:         } else { 
                   2963:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2964:         }
1.617     albertel 2965:     }
                   2966: }
                   2967: 
1.263     www      2968: # -------------------------------------------------------------------- New chat
                   2969: 
                   2970: sub chatsend {
1.724     raeburn  2971:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2972:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2973:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2974:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2975:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2976: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2977: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2978: }
                   2979: 
                   2980: # ------------------------------------------ Find current version of a resource
                   2981: 
                   2982: sub getversion {
                   2983:     my $fname=&clutter(shift);
1.1189    raeburn  2984:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2985:     return &currentversion(&filelocation('',$fname));
                   2986: }
                   2987: 
                   2988: sub currentversion {
                   2989:     my $fname=shift;
                   2990:     my $author=$fname;
                   2991:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2992:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2993:     my $home=&homeserver($uname,$udom);
1.292     www      2994:     if ($home eq 'no_host') { 
                   2995:         return -1; 
                   2996:     }
1.1112    www      2997:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2998:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2999: 	return -1;
                   3000:     }
1.1112    www      3001:     return $answer;
1.263     www      3002: }
                   3003: 
1.1111    www      3004: #
                   3005: # Return special version number of resource if set by override, empty otherwise
                   3006: #
                   3007: sub usedversion {
                   3008:     my $fname=shift;
                   3009:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3010:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3011:     if ($urlversion) { return $urlversion; }
                   3012:     return '';
                   3013: }
                   3014: 
1.1       albertel 3015: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3016: 
1.1       albertel 3017: sub subscribe {
                   3018:     my $fname=shift;
1.761     raeburn  3019:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3020:     $fname=~s/[\n\r]//g;
1.1       albertel 3021:     my $author=$fname;
                   3022:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3023:     my ($udom,$uname)=split(/\//,$author);
                   3024:     my $home=homeserver($uname,$udom);
1.335     albertel 3025:     if ($home eq 'no_host') {
                   3026:         return 'not_found';
1.1       albertel 3027:     }
                   3028:     my $answer=reply("sub:$fname",$home);
1.64      www      3029:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3030: 	$answer.=' by '.$home;
                   3031:     }
1.1       albertel 3032:     return $answer;
                   3033: }
                   3034:     
1.8       www      3035: # -------------------------------------------------------------- Replicate file
                   3036: 
                   3037: sub repcopy {
                   3038:     my $filename=shift;
1.23      www      3039:     $filename=~s/\/+/\//g;
1.1142    raeburn  3040:     my $londocroot = $perlvar{'lonDocRoot'};
                   3041:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3042:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3043:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3044: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3045: 	return &repcopy_userfile($filename);
                   3046:     }
1.532     albertel 3047:     $filename=~s/[\n\r]//g;
1.8       www      3048:     my $transname="$filename.in.transfer";
1.828     www      3049: # FIXME: this should flock
1.607     raeburn  3050:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3051:     my $remoteurl=subscribe($filename);
1.64      www      3052:     if ($remoteurl =~ /^con_lost by/) {
                   3053: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3054:            return 'unavailable';
1.8       www      3055:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3056: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3057: 	   return 'not_found';
1.64      www      3058:     } elsif ($remoteurl =~ /^rejected by/) {
                   3059: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3060:            return 'forbidden';
1.20      www      3061:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3062:            return 'ok';
1.8       www      3063:     } else {
1.290     www      3064:         my $author=$filename;
                   3065:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3066:         my ($udom,$uname)=split(/\//,$author);
                   3067:         my $home=homeserver($uname,$udom);
                   3068:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3069:            my @parts=split(/\//,$filename);
                   3070:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3071:            if ($path ne "$londocroot/res") {
1.8       www      3072:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3073: 	       return 'bad_request';
1.8       www      3074:            }
                   3075:            my $count;
                   3076:            for ($count=5;$count<$#parts;$count++) {
                   3077:                $path.="/$parts[$count]";
                   3078:                if ((-e $path)!=1) {
                   3079: 		   mkdir($path,0777);
                   3080:                }
                   3081:            }
                   3082:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3083:            my $response;
                   3084:            if ($remoteurl =~ m{/raw/}) {
                   3085:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3086:            } else {
                   3087:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3088:            }
1.8       www      3089:            if ($response->is_error()) {
                   3090: 	       unlink($transname);
                   3091:                my $message=$response->status_line;
1.672     albertel 3092:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3093:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3094:                return 'unavailable';
1.8       www      3095:            } else {
1.16      www      3096: 	       if ($remoteurl!~/\.meta$/) {
                   3097:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3098:                   my $mresponse;
                   3099:                   if ($remoteurl =~ m{/raw/}) {
                   3100:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3101:                   } else {
                   3102:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3103:                   }
1.16      www      3104:                   if ($mresponse->is_error()) {
                   3105: 		      unlink($filename.'.meta');
                   3106:                       &logthis(
1.672     albertel 3107:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3108:                   }
                   3109: 	       }
1.8       www      3110:                rename($transname,$filename);
1.607     raeburn  3111:                return 'ok';
1.8       www      3112:            }
1.290     www      3113:        }
1.8       www      3114:     }
1.330     www      3115: }
                   3116: 
                   3117: # ------------------------------------------------ Get server side include body
                   3118: sub ssi_body {
1.381     albertel 3119:     my ($filelink,%form)=@_;
1.606     matthew  3120:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3121:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3122:     }
1.953     www      3123:     my $output='';
                   3124:     my $response;
1.980     raeburn  3125:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3126:        ($output,$response)=&externalssi($filelink);
1.953     www      3127:     } else {
1.1004    droeschl 3128:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3129:        $filelink .= 'inhibitmenu=yes';
1.953     www      3130:        ($output,$response)=&ssi($filelink,%form);
                   3131:     }
1.778     albertel 3132:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3133:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3134:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3135:     if (wantarray) {
                   3136:         return ($output, $response);
                   3137:     } else {
                   3138:         return $output;
                   3139:     }
1.8       www      3140: }
                   3141: 
1.15      www      3142: # --------------------------------------------------------- Server Side Include
                   3143: 
1.782     albertel 3144: sub absolute_url {
                   3145:     my ($host_name) = @_;
                   3146:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3147:     if ($host_name eq '') {
                   3148: 	$host_name = $ENV{'SERVER_NAME'};
                   3149:     }
                   3150:     return $protocol.$host_name;
                   3151: }
                   3152: 
1.942     foxr     3153: #
                   3154: #   Server side include.
                   3155: # Parameters:
                   3156: #  fn     Possibly encrypted resource name/id.
                   3157: #  form   Hash that describes how the rendering should be done
                   3158: #         and other things.
1.944     foxr     3159: # Returns:
1.950     raeburn  3160: #   Scalar context: The content of the response.
                   3161: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3162: #     
1.15      www      3163: sub ssi {
                   3164: 
1.944     foxr     3165:     my ($fn,%form)=@_;
1.23      www      3166:     my $request;
1.711     albertel 3167: 
                   3168:     $form{'no_update_last_known'}=1;
1.895     albertel 3169:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3170:     if (%form) {
1.782     albertel 3171:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3172:       $request->content(join('&',map { 
                   3173:             my $name = escape($_);
                   3174:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3175:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3176:             : &escape($form{$_}) );    
                   3177:         } keys(%form)));
1.23      www      3178:     } else {
1.782     albertel 3179:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3180:     }
                   3181: 
1.15      www      3182:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3183:     my $lonhost = $perlvar{'lonHostID'};
                   3184:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar);
1.1182    foxr     3185: 
1.944     foxr     3186:     if (wantarray) {
1.1345    raeburn  3187: 	return ($response->content, $response);
1.944     foxr     3188:     } else {
1.1345    raeburn  3189: 	return $response->content;
1.942     foxr     3190:     }
1.324     www      3191: }
                   3192: 
                   3193: sub externalssi {
                   3194:     my ($url)=@_;
                   3195:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3196:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3197:     if (wantarray) {
                   3198:         return ($response->content, $response);
                   3199:     } else {
                   3200:         return $response->content;
                   3201:     }
1.15      www      3202: }
1.254     www      3203: 
1.1354    raeburn  3204: 
                   3205: # If the local copy of a replicated resource is outdated, trigger a  
                   3206: # connection from the homeserver to flush the delayed queue. If no update 
                   3207: # happens, remove local copies of outdated resource (and corresponding
                   3208: # metadata file).
                   3209: 
1.1352    raeburn  3210: sub remove_stale_resfile {
                   3211:     my ($url) = @_;
1.1354    raeburn  3212:     my $removed;
1.1352    raeburn  3213:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3214:         my $audom = $1;
                   3215:         my $auname = $2;
1.1353    raeburn  3216:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3217:             my $homeserver = &homeserver($auname,$audom);
                   3218:             unless (($homeserver eq 'no_host') ||
                   3219:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3220:                 my $fname = &filelocation('',$url);
                   3221:                 if (-e $fname) {
                   3222:                     my $protocol = $protocol{$homeserver};
                   3223:                     $protocol = 'http' if ($protocol ne 'https');
                   3224:                     my $hostname = &hostname($homeserver);
                   3225:                     if ($hostname) {
                   3226:                         my $uri = &declutter($url);
                   3227:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3228:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3229:                         if ($response->is_success()) {
                   3230:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3231:                             my $locmodtime = (stat($fname))[9];
                   3232:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3233:                                 my $stale;
                   3234:                                 my $answer = &reply('pong',$homeserver);
                   3235:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3236:                                     sleep(0.2);
                   3237:                                     $locmodtime = (stat($fname))[9];
                   3238:                                     if ($locmodtime < $remmodtime) {
                   3239:                                         my $posstransfer = $fname.'.in.transfer';
                   3240:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3241:                                             $removed = 1;
                   3242:                                         } else {
                   3243:                                             $stale = 1;
                   3244:                                         }
                   3245:                                     } else {
                   3246:                                         $removed = 1;
                   3247:                                     }
                   3248:                                 } else {
                   3249:                                     $stale = 1;
                   3250:                                 }
                   3251:                                 if ($stale) {
                   3252:                                     unlink($fname);
                   3253:                                     if ($uri!~/\.meta$/) {
                   3254:                                         unlink($fname.'.meta');
                   3255:                                     }
                   3256:                                     &reply("unsub:$fname",$homeserver);
                   3257:                                     $removed = 1;
1.1352    raeburn  3258:                                 }
                   3259:                             }
                   3260:                         }
                   3261:                     }
                   3262:                 }
                   3263:             }
                   3264:         }
                   3265:     }
1.1354    raeburn  3266:     return $removed;
1.1352    raeburn  3267: }
                   3268: 
1.492     albertel 3269: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3270: 
                   3271: sub allowuploaded {
                   3272:     my ($srcurl,$url)=@_;
                   3273:     $url=&clutter(&declutter($url));
                   3274:     my $dir=$url;
                   3275:     $dir=~s/\/[^\/]+$//;
                   3276:     my %httpref=();
                   3277:     my $httpurl=&hreflocation('',$url);
                   3278:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3279:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3280: }
1.477     raeburn  3281: 
1.1193    raeburn  3282: #
                   3283: # Determine if the current user should be able to edit a particular resource,
                   3284: # when viewing in course context.
                   3285: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3286: #     Functions.
                   3287: # (b) When displaying folder contents in course editor, used to determine if
                   3288: #     "Edit" link will be displayed alongside resource.
                   3289: #
1.1196    raeburn  3290: #  input: six args -- filename (decluttered), course number, course domain,
                   3291: #                   url, symb (if registered) and group (if this is a group
                   3292: #                   item -- e.g., bulletin board, group page etc.).
                   3293: #  output: array of five scalars -- 
1.1193    raeburn  3294: #          $cfile -- url for file editing if editable on current server
                   3295: #          $home -- homeserver of resource (i.e., for author if published,
                   3296: #                                           or course if uploaded.).
                   3297: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3298: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3299: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3300: #
                   3301: 
                   3302: sub can_edit_resource {
1.1194    raeburn  3303:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3304:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3305: #
                   3306: # For aboutme pages user can only edit his/her own.
                   3307: #
1.1199    raeburn  3308:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3309:         my ($sdom,$sname) = ($1,$2);
                   3310:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3311:             $home = $env{'user.home'};
                   3312:             $cfile = $resurl;
                   3313:             if ($env{'form.forceedit'}) {
                   3314:                 $forceview = 1;
                   3315:             } else {
                   3316:                 $forceedit = 1;
                   3317:             }
                   3318:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3319:         } else {
                   3320:             return;
                   3321:         }
                   3322:     }
                   3323: 
                   3324:     if ($env{'request.course.id'}) {
                   3325:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3326:         if ($group ne '') {
                   3327: # if this is a group homepage or group bulletin board, check group privs
                   3328:             my $allowed = 0;
1.1197    raeburn  3329:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3330:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3331:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3332:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3333:                     $allowed = 1;
                   3334:                 }
1.1197    raeburn  3335:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3336:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3337:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3338:                     $allowed = 1;
                   3339:                 }
                   3340:             }
                   3341:             if ($allowed) {
                   3342:                 $home=&homeserver($cnum,$cdom);
                   3343:                 if ($env{'form.forceedit'}) {
                   3344:                     $forceview = 1;
                   3345:                 } else {
                   3346:                     $forceedit = 1;
                   3347:                 }
                   3348:                 $cfile = $resurl;
                   3349:             } else {
                   3350:                 return;
                   3351:             }
                   3352:         } else {
1.1208    raeburn  3353:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3354:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3355:                     return;
                   3356:                 }
                   3357:             } elsif (!$crsedit) {
1.1194    raeburn  3358: #
                   3359: # No edit allowed where CC has switched to student role.
                   3360: #
                   3361:                 return;
                   3362:             }
                   3363:         }
                   3364:     }
                   3365: 
1.1193    raeburn  3366:     if ($file ne '') {
                   3367:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3368:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3369:                 $uploaded = 1;
                   3370:                 $incourse = 1;
1.1193    raeburn  3371:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3372:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3373:                     if ($env{'form.forceedit'}) {
                   3374:                         $forceview = 1;
                   3375:                     } else {
                   3376:                         $forceedit = 1;
                   3377:                     }
1.1194    raeburn  3378:                 }
                   3379:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3380:                 $incourse = 1;
                   3381:                 if ($env{'form.forceedit'}) {
                   3382:                     $forceview = 1;
                   3383:                 } else {
                   3384:                     $forceedit = 1;
                   3385:                 }
                   3386:                 $cfile = $resurl;
                   3387:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3388:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3389:                     $incourse = 1;
                   3390:                     if ($env{'form.forceedit'}) {
                   3391:                         $forceview = 1;
                   3392:                     } else {
                   3393:                         $forceedit = 1;
                   3394:                     }
                   3395:                     $cfile = $resurl;
1.1199    raeburn  3396:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3397:                     $incourse = 1;
                   3398:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3399:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3400:                     $incourse = 1;
1.1199    raeburn  3401:                     if ($env{'form.forceedit'}) {
                   3402:                         $forceview = 1;
                   3403:                     } else {
                   3404:                         $forceedit = 1;
                   3405:                     }
                   3406:                     $cfile = $resurl;
1.1343    raeburn  3407:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3408:                     $incourse = 1;
                   3409:                     if ($env{'form.forceedit'}) {
                   3410:                         $forceview = 1;
                   3411:                     } else {
                   3412:                         $forceedit = 1;
                   3413:                     }
                   3414:                     $cfile = $resurl;
1.1208    raeburn  3415:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3416:                     $incourse = 1;
                   3417:                     if ($env{'form.forceedit'}) {
                   3418:                         $forceview = 1;
                   3419:                     } else {
                   3420:                         $forceedit = 1;
                   3421:                     }
                   3422:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3423:                 }
                   3424:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3425:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3426:                 if (&is_on_map($template)) { 
                   3427:                     $incourse = 1;
                   3428:                     $forceview = 1;
                   3429:                     $cfile = $template;
1.1193    raeburn  3430:                 }
1.1199    raeburn  3431:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3432:                     $incourse = 1;
                   3433:                     if ($env{'form.forceedit'}) {
                   3434:                         $forceview = 1;
                   3435:                     } else {
                   3436:                         $forceedit = 1;
                   3437:                     }
                   3438:                     $cfile = $resurl;
1.1343    raeburn  3439:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3440:                 $incourse = 1;
                   3441:                 if ($env{'form.forceedit'}) {
                   3442:                     $forceview = 1;
                   3443:                 } else {
                   3444:                     $forceedit = 1;
                   3445:                 }
                   3446:                 $cfile = $resurl;
1.1199    raeburn  3447:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3448:                 $incourse = 1;
                   3449:                 $forceview = 1;
                   3450:                 if ($symb) {
                   3451:                     my ($map,$id,$res)=&decode_symb($symb);
                   3452:                     $env{'request.symb'} = $symb;
                   3453:                     $cfile = &clutter($res);
                   3454:                 } else {
                   3455:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3456:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3457:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3458:                         $cfile = '/adm/wrapper'.$escfile;
                   3459:                     } else {
                   3460:                         $escfile =~ s{^http://}{};
                   3461:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3462:                     }
1.1199    raeburn  3463:                 }
1.1234    raeburn  3464:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3465:                 if ($env{'form.forceedit'}) {
                   3466:                     $forceview = 1;
                   3467:                 } else {
                   3468:                     $forceedit = 1;
                   3469:                 }
                   3470:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3471:             }
                   3472:         }
1.1194    raeburn  3473:         if ($uploaded || $incourse) {
                   3474:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3475:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3476:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3477:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3478:             # Check that the user has permission to edit this resource
                   3479:             my $setpriv = 1;
                   3480:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3481:             if (defined($cfudom)) {
                   3482:                 $home=&homeserver($cfuname,$cfudom);
                   3483:                 $cfile=$file;
                   3484:             }
                   3485:         }
1.1194    raeburn  3486:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3487:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3488:             my @ids=&current_machine_ids();
                   3489:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3490:                 $switchserver=1;
                   3491:             }
                   3492:         }
                   3493:     }
1.1194    raeburn  3494:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3495: }
                   3496: 
                   3497: sub is_course_upload {
                   3498:     my ($file,$cnum,$cdom) = @_;
                   3499:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3500:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3501:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3502:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3503:         return 1;
                   3504:     }
                   3505:     return;
                   3506: }
                   3507: 
1.1194    raeburn  3508: sub in_course {
1.1195    raeburn  3509:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3510:     if ($hideprivileged) {
                   3511:         my $skipuser;
1.1219    raeburn  3512:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3513:         my @possdoms = ($cdom);  
                   3514:         if ($coursehash{'checkforpriv'}) { 
                   3515:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3516:         }
                   3517:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3518:             $skipuser = 1;
                   3519:             if ($coursehash{'nothideprivileged'}) {
                   3520:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3521:                     my $user;
                   3522:                     if ($item =~ /:/) {
                   3523:                         $user = $item;
                   3524:                     } else {
                   3525:                         $user = join(':',split(/[\@]/,$item));
                   3526:                     }
                   3527:                     if ($user eq $uname.':'.$udom) {
                   3528:                         undef($skipuser);
                   3529:                         last;
                   3530:                     }
                   3531:                 }
                   3532:             }
                   3533:             if ($skipuser) {
                   3534:                 return 0;
                   3535:             }
                   3536:         }
                   3537:     }
1.1194    raeburn  3538:     $type ||= 'any';
                   3539:     if (!defined($cdom) || !defined($cnum)) {
                   3540:         my $cid  = $env{'request.course.id'};
                   3541:         $cdom = $env{'course.'.$cid.'.domain'};
                   3542:         $cnum = $env{'course.'.$cid.'.num'};
                   3543:     }
                   3544:     my $typesref;
1.1195    raeburn  3545:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3546:         $typesref = ['active','previous','future'];
                   3547:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3548:         $typesref = [$type];
                   3549:     }
                   3550:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3551:                               $typesref,undef,[$cdom]);
                   3552:     my ($tmp) = keys(%roles);
                   3553:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3554:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3555:     if (@course_roles > 0) {
                   3556:         return 1;
                   3557:     }
                   3558:     return 0;
                   3559: }
                   3560: 
1.478     albertel 3561: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3562: # input: action, courseID, current domain, intended
1.637     raeburn  3563: #        path to file, source of file, instruction to parse file for objects,
                   3564: #        ref to hash for embedded objects,
                   3565: #        ref to hash for codebase of java objects.
1.1095    raeburn  3566: #        reference to scalar to accommodate mime type determined
                   3567: #          from File::MMagic if $parser = parse.
1.637     raeburn  3568: #
1.485     raeburn  3569: # output: url to file (if action was uploaddoc), 
                   3570: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3571: #
1.478     albertel 3572: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3573: # course.
1.477     raeburn  3574: #
1.478     albertel 3575: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3576: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3577: #          course's home server.
1.477     raeburn  3578: #
1.478     albertel 3579: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3580: #          be copied from $source (current location) to 
                   3581: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3582: #         and will then be copied to
                   3583: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3584: #         course's home server.
1.485     raeburn  3585: #
1.481     raeburn  3586: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3587: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3588: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3589: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3590: #         in course's home server.
1.637     raeburn  3591: #
1.477     raeburn  3592: 
                   3593: sub process_coursefile {
1.1095    raeburn  3594:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3595:         $mimetype)=@_;
1.477     raeburn  3596:     my $fetchresult;
1.638     albertel 3597:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3598:     if ($action eq 'propagate') {
1.638     albertel 3599:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3600: 			     $home);
1.481     raeburn  3601:     } else {
1.477     raeburn  3602:         my $fpath = '';
                   3603:         my $fname = $file;
1.478     albertel 3604:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3605:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3606:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3607:         if ($action eq 'copy') {
                   3608:             if ($source eq '') {
                   3609:                 $fetchresult = 'no source file';
                   3610:                 return $fetchresult;
                   3611:             } else {
                   3612:                 my $destination = $filepath.'/'.$fname;
                   3613:                 rename($source,$destination);
                   3614:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3615:                                  $home);
1.481     raeburn  3616:             }
                   3617:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  3618:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3619:             print $fh $env{'form.'.$source};
1.481     raeburn  3620:             close($fh);
1.637     raeburn  3621:             if ($parser eq 'parse') {
1.1024    raeburn  3622:                 my $mm = new File::MMagic;
1.1095    raeburn  3623:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3624:                 if ($type eq 'text/html') {
1.1024    raeburn  3625:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3626:                     unless ($parse_result eq 'ok') {
                   3627:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3628:                     }
1.637     raeburn  3629:                 }
1.1095    raeburn  3630:                 if (ref($mimetype)) {
                   3631:                     $$mimetype = $type;
                   3632:                 } 
1.637     raeburn  3633:             }
1.477     raeburn  3634:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3635:                                  $home);
1.481     raeburn  3636:             if ($fetchresult eq 'ok') {
                   3637:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3638:             } else {
                   3639:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3640:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3641:                 return '/adm/notfound.html';
                   3642:             }
1.477     raeburn  3643:         }
                   3644:     }
1.485     raeburn  3645:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3646:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3647:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3648:     }
                   3649:     return $fetchresult;
                   3650: }
                   3651: 
1.637     raeburn  3652: sub build_filepath {
                   3653:     my ($fpath) = @_;
                   3654:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3655:     unless ($fpath eq '') {
                   3656:         my @parts=split('/',$fpath);
                   3657:         foreach my $part (@parts) {
                   3658:             $filepath.= '/'.$part;
                   3659:             if ((-e $filepath)!=1) {
                   3660:                 mkdir($filepath,0777);
                   3661:             }
                   3662:         }
                   3663:     }
                   3664:     return $filepath;
                   3665: }
                   3666: 
                   3667: sub store_edited_file {
1.638     albertel 3668:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3669:     my $file = $primary_url;
                   3670:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3671:     my $fpath = '';
                   3672:     my $fname = $file;
                   3673:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3674:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3675:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  3676:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3677:     print $fh $content;
                   3678:     close($fh);
1.638     albertel 3679:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3680:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3681: 			  $home);
1.637     raeburn  3682:     if ($$fetchresult eq 'ok') {
                   3683:         return '/uploaded/'.$fpath.'/'.$fname;
                   3684:     } else {
1.638     albertel 3685:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3686: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3687:         return '/adm/notfound.html';
                   3688:     }
                   3689: }
                   3690: 
1.531     albertel 3691: sub clean_filename {
1.831     albertel 3692:     my ($fname,$args)=@_;
1.315     www      3693: # Replace Windows backslashes by forward slashes
1.257     www      3694:     $fname=~s/\\/\//g;
1.831     albertel 3695:     if (!$args->{'keep_path'}) {
                   3696:         # Get rid of everything but the actual filename
                   3697: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3698:     }
1.315     www      3699: # Replace spaces by underscores
                   3700:     $fname=~s/\s+/\_/g;
                   3701: # Replace all other weird characters by nothing
1.831     albertel 3702:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3703: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3704: # numbers
                   3705:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3706:     return $fname;
                   3707: }
1.1051    raeburn  3708: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3709: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3710: # image with the same aspect ratio as the original, but with dimensions which do 
                   3711: # not exceed $resizewidth and $resizeheight.
                   3712:  
1.984     neumanie 3713: sub resizeImage {
1.1051    raeburn  3714:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3715:     my $ima = Image::Magick->new;
                   3716:     my $resized;
                   3717:     if (-e $img_path) {
                   3718:         $ima->Read($img_path);
                   3719:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3720:             my $width = $ima->Get('width');
                   3721:             my $height = $ima->Get('height');
                   3722:             if ($width > $resizewidth) {
                   3723: 	        my $factor = $width/$resizewidth;
                   3724:                 my $newheight = $height/$factor;
                   3725:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3726:                 $resized = 1;
                   3727:             }
                   3728:         }
                   3729:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3730:             my $width = $ima->Get('width');
                   3731:             my $height = $ima->Get('height');
                   3732:             if ($height > $resizeheight) {
                   3733:                 my $factor = $height/$resizeheight;
                   3734:                 my $newwidth = $width/$factor;
                   3735:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3736:                 $resized = 1;
                   3737:             }
                   3738:         }
                   3739:         if ($resized) {
                   3740:             $ima->Write($img_path);
                   3741:         }
                   3742:     }
                   3743:     return;
1.977     amueller 3744: }
                   3745: 
1.608     albertel 3746: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3747: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3748: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3749: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3750: #                                    canceloverwrite, or ''. 
                   3751: #                   if 'coursedoc': upload to the current course
                   3752: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3753: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3754: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3755: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3756: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3757: #        $allfiles - reference to hash for embedded objects
                   3758: #        $codebase - reference to hash for codebase of java objects
                   3759: #        $desuname - username for permanent storage of uploaded file
                   3760: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3761: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3762: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3763: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3764: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3765: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3766: #                    from File::MMagic.
1.858     raeburn  3767: # 
1.686     albertel 3768: # output: url of file in userspace, or error: <message> 
                   3769: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3770: 
1.531     albertel 3771: sub userfileupload {
1.1090    raeburn  3772:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3773:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3774:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3775:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3776:     $fname=&clean_filename($fname);
1.1090    raeburn  3777:     # See if there is anything left
1.257     www      3778:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3779:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3780:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3781:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3782:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3783:         my $now = time;
1.1090    raeburn  3784:         my $filepath;
1.1095    raeburn  3785:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3786:              $filepath = 'tmp/helprequests/'.$now;
                   3787:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3788:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3789:                          '_'.$env{'user.domain'}.'/pending';
                   3790:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3791:             my ($docuname,$docudom);
1.1350    raeburn  3792:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3793:                 $docudom = $destudom;
                   3794:             } else {
                   3795:                 $docudom = $env{'user.domain'};
                   3796:             }
1.1350    raeburn  3797:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  3798:                 $docuname = $destuname;
                   3799:             } else {
                   3800:                 $docuname = $env{'user.name'};
                   3801:             }
                   3802:             if (exists($env{'form.group'})) {
                   3803:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3804:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3805:             }
                   3806:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3807:             if ($context eq 'canceloverwrite') {
                   3808:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3809:                 if (-e  $tempfile) {
                   3810:                     my @info = stat($tempfile);
                   3811:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3812:                         unlink($tempfile);
                   3813:                     }
                   3814:                 }
                   3815:                 return;
1.523     raeburn  3816:             }
                   3817:         }
1.1090    raeburn  3818:         # Create the directory if not present
1.741     raeburn  3819:         my @parts=split(/\//,$filepath);
                   3820:         my $fullpath = $perlvar{'lonDaemons'};
                   3821:         for (my $i=0;$i<@parts;$i++) {
                   3822:             $fullpath .= '/'.$parts[$i];
                   3823:             if ((-e $fullpath)!=1) {
                   3824:                 mkdir($fullpath,0777);
                   3825:             }
                   3826:         }
1.1359    raeburn  3827:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3828:         print $fh $env{'form.'.$formname};
                   3829:         close($fh);
1.1090    raeburn  3830:         if ($context eq 'existingfile') {
                   3831:             my @info = stat($fullpath.'/'.$fname);
                   3832:             return ($fullpath.'/'.$fname,$info[9]);
                   3833:         } else {
                   3834:             return $fullpath.'/'.$fname;
                   3835:         }
1.523     raeburn  3836:     }
1.995     raeburn  3837:     if ($subdir eq 'scantron') {
                   3838:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3839:     } else {
1.995     raeburn  3840:         $fname="$subdir/$fname";
                   3841:     }
1.1090    raeburn  3842:     if ($context eq 'coursedoc') {
1.638     albertel 3843: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3844: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3845:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3846:             return &finishuserfileupload($docuname,$docudom,
                   3847: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3848: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3849:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3850:         } else {
1.1218    raeburn  3851:             if ($env{'form.folder'}) {
                   3852:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3853:             }
1.638     albertel 3854:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3855: 				       $fname,$formname,$parser,
1.1095    raeburn  3856: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3857:         }
1.719     banghart 3858:     } elsif (defined($destuname)) {
                   3859:         my $docuname=$destuname;
                   3860:         my $docudom=$destudom;
1.860     raeburn  3861: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3862: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3863:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3864:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3865:     } else {
1.638     albertel 3866:         my $docuname=$env{'user.name'};
                   3867:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3868:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3869:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3870:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3871:         }
1.860     raeburn  3872: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3873: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3874:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3875:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3876:     }
1.271     www      3877: }
                   3878: 
                   3879: sub finishuserfileupload {
1.860     raeburn  3880:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3881:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3882:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3883:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3884:   
1.860     raeburn  3885:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3886:     $file=$fname;
                   3887:     if ($fname=~m|/|) {
                   3888:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3889: 	$path.=$fnamepath.'/';
                   3890:     }
1.259     www      3891:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3892:     my $count;
                   3893:     for ($count=4;$count<=$#parts;$count++) {
                   3894:         $filepath.="/$parts[$count]";
                   3895:         if ((-e $filepath)!=1) {
                   3896: 	    mkdir($filepath,0777);
                   3897:         }
                   3898:     }
1.984     neumanie 3899: 
1.258     www      3900: # Save the file
                   3901:     {
1.1359    raeburn  3902: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3903: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3904: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3905: 	    return '/adm/notfound.html';
                   3906: 	}
1.1090    raeburn  3907:         if ($context eq 'overwrite') {
1.1117    foxr     3908:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3909:             my $target = $filepath.'/'.$file;
                   3910:             if (-e $source) {
                   3911:                 my @info = stat($source);
                   3912:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3913:                     unless (&File::Copy::move($source,$target)) {
                   3914:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3915:                         return "Moving from $source failed";
                   3916:                     }
                   3917:                 } else {
                   3918:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3919:                 }
                   3920:             } else {
                   3921:                 return "Temporary file: $source missing";
                   3922:             }
                   3923:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3924: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3925: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3926: 	    return '/adm/notfound.html';
                   3927: 	}
1.570     albertel 3928: 	close(FH);
1.1051    raeburn  3929:         if ($resizewidth && $resizeheight) {
                   3930:             my $mm = new File::MMagic;
                   3931:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3932:             if ($mime_type =~ m{^image/}) {
                   3933: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3934:             }  
1.977     amueller 3935: 	}
1.258     www      3936:     }
1.1152    raeburn  3937:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3938:         if (ref($mimetype)) {
                   3939:             if ($$mimetype eq '') {
                   3940:                 my $mm = new File::MMagic;
                   3941:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3942:                 $$mimetype = $type;
                   3943:             }
                   3944:         }
                   3945:     }
1.637     raeburn  3946:     if ($parser eq 'parse') {
1.1152    raeburn  3947:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3948:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3949:                                                        $allfiles,$codebase);
                   3950:             unless ($parse_result eq 'ok') {
                   3951:                 &logthis('Failed to parse '.$filepath.$file.
                   3952: 	   	         ' for embedded media: '.$parse_result); 
                   3953:             }
1.637     raeburn  3954:         }
                   3955:     }
1.860     raeburn  3956:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3957:         my $input = $filepath.'/'.$file;
                   3958:         my $output = $filepath.'/'.'tn-'.$file;
                   3959:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  3960:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3961:         system({$args[0]} @args);
1.860     raeburn  3962:         if (-e $filepath.'/'.'tn-'.$file) {
                   3963:             $fetchthumb  = 1; 
                   3964:         }
                   3965:     }
1.858     raeburn  3966:  
1.259     www      3967: # Notify homeserver to grep it
                   3968: #
1.984     neumanie 3969:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3970:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3971:     if ($fetchresult eq 'ok') {
1.860     raeburn  3972:         if ($fetchthumb) {
                   3973:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3974:             if ($thumbresult ne 'ok') {
                   3975:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3976:                          $docuhome.': '.$thumbresult);
                   3977:             }
                   3978:         }
1.259     www      3979: #
1.258     www      3980: # Return the URL to it
1.494     albertel 3981:         return '/uploaded/'.$path.$file;
1.263     www      3982:     } else {
1.494     albertel 3983:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3984: 		 ': '.$fetchresult);
1.263     www      3985:         return '/adm/notfound.html';
1.858     raeburn  3986:     }
1.493     albertel 3987: }
                   3988: 
1.637     raeburn  3989: sub extract_embedded_items {
1.961     raeburn  3990:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3991:     my @state = ();
1.1164    raeburn  3992:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3993:     my %javafiles = (
                   3994:                       codebase => '',
                   3995:                       code => '',
                   3996:                       archive => ''
                   3997:                     );
                   3998:     my %mediafiles = (
                   3999:                       src => '',
                   4000:                       movie => '',
                   4001:                      );
1.648     raeburn  4002:     my $p;
                   4003:     if ($content) {
                   4004:         $p = HTML::LCParser->new($content);
                   4005:     } else {
1.961     raeburn  4006:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4007:     }
1.641     albertel 4008:     while (my $t=$p->get_token()) {
1.640     albertel 4009: 	if ($t->[0] eq 'S') {
                   4010: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4011: 	    push(@state, $tagname);
1.648     raeburn  4012:             if (lc($tagname) eq 'allow') {
                   4013:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4014:             }
1.640     albertel 4015: 	    if (lc($tagname) eq 'img') {
                   4016: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4017: 	    }
1.886     albertel 4018: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4019:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4020:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4021:                 }
1.886     albertel 4022: 	    }
1.645     raeburn  4023:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4024:                 my $src;
1.645     raeburn  4025:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4026:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4027:                 } else {
1.1164    raeburn  4028:                     if ($attr->{'src'} ne '') {
                   4029:                         $src = $attr->{'src'};
                   4030:                         &add_filetype($allfiles,$src,'src');
                   4031:                     }
                   4032:                 }
                   4033:                 my $text = $p->get_trimmed_text();
                   4034:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4035:                     my @swfargs = split(/,/,$1);
                   4036:                     foreach my $item (@swfargs) {
                   4037:                         $item =~ s/["']//g;
                   4038:                         $item =~ s/^\s+//;
                   4039:                         $item =~ s/\s+$//;
                   4040:                     }
                   4041:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4042:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4043:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4044:                         } else {
                   4045:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4046:                         }
                   4047:                     }
1.645     raeburn  4048:                 }
                   4049:             }
                   4050:             if (lc($tagname) eq 'link') {
                   4051:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4052:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4053:                 }
                   4054:             }
1.640     albertel 4055: 	    if (lc($tagname) eq 'object' ||
                   4056: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4057: 		foreach my $item (keys(%javafiles)) {
                   4058: 		    $javafiles{$item} = '';
                   4059: 		}
1.1164    raeburn  4060:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4061:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4062:                 }
1.640     albertel 4063: 	    }
                   4064: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4065: 		my $name = lc($attr->{'name'});
                   4066: 		foreach my $item (keys(%javafiles)) {
                   4067: 		    if ($name eq $item) {
                   4068: 			$javafiles{$item} = $attr->{'value'};
                   4069: 			last;
                   4070: 		    }
                   4071: 		}
1.1164    raeburn  4072:                 my $pathfrom;
1.640     albertel 4073: 		foreach my $item (keys(%mediafiles)) {
                   4074: 		    if ($name eq $item) {
1.1164    raeburn  4075:                         $pathfrom = $attr->{'value'};
                   4076:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4077: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4078: 			last;
                   4079: 		    }
                   4080: 		}
1.1164    raeburn  4081:                 if ($name eq 'flashvars') {
                   4082:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4083:                 }
                   4084:                 if ($pathfrom ne '') {
                   4085:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4086:                                          $pathfrom);
                   4087:                 }
1.640     albertel 4088: 	    }
                   4089: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4090: 		foreach my $item (keys(%javafiles)) {
                   4091: 		    if ($attr->{$item}) {
                   4092: 			$javafiles{$item} = $attr->{$item};
                   4093: 			last;
                   4094: 		    }
                   4095: 		}
                   4096: 		foreach my $item (keys(%mediafiles)) {
                   4097: 		    if ($attr->{$item}) {
                   4098: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4099: 			last;
                   4100: 		    }
                   4101: 		}
1.1164    raeburn  4102:                 if (lc($tagname) eq 'embed') {
                   4103:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4104:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4105:                                              $attr->{'src'});
                   4106:                     }
                   4107:                 }
1.640     albertel 4108: 	    }
1.1243    raeburn  4109:             if (lc($tagname) eq 'iframe') {
                   4110:                 my $src = $attr->{'src'} ;
                   4111:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4112:                     &add_filetype($allfiles,$src,'src');
                   4113:                 } elsif ($src =~ m{^/}) {
                   4114:                     if ($env{'request.course.id'}) {
                   4115:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4116:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4117:                         my $url = &hreflocation('',$fullpath);
                   4118:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4119:                             my $relpath = $1;
                   4120:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4121:                                 &add_filetype($allfiles,$1,'src');
                   4122:                             }
                   4123:                         }
                   4124:                     }
                   4125:                 }
                   4126:             }
1.1164    raeburn  4127:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4128:                 pop(@state);
1.1164    raeburn  4129:             }
1.640     albertel 4130: 	} elsif ($t->[0] eq 'E') {
                   4131: 	    my ($tagname) = ($t->[1]);
                   4132: 	    if ($javafiles{'codebase'} ne '') {
                   4133: 		$javafiles{'codebase'} .= '/';
                   4134: 	    }  
                   4135: 	    if (lc($tagname) eq 'applet' ||
                   4136: 		lc($tagname) eq 'object' ||
                   4137: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4138: 		) {
                   4139: 		foreach my $item (keys(%javafiles)) {
                   4140: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4141: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4142: 			&add_filetype($allfiles,$file,$item);
                   4143: 		    }
                   4144: 		}
                   4145: 	    } 
                   4146: 	    pop @state;
                   4147: 	}
                   4148:     }
1.1164    raeburn  4149:     foreach my $id (sort(keys(%flashvars))) {
                   4150:         if ($shockwave{$id} ne '') {
                   4151:             my @pairs = split(/\&/,$flashvars{$id});
                   4152:             foreach my $pair (@pairs) {
                   4153:                 my ($key,$value) = split(/\=/,$pair);
                   4154:                 if ($key eq 'thumb') {
                   4155:                     &add_filetype($allfiles,$value,$key);
                   4156:                 } elsif ($key eq 'content') {
                   4157:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4158:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4159:                     if ($ext ne '') {
                   4160:                         &add_filetype($allfiles,$path.$value,$ext);
                   4161:                     }
                   4162:                 }
                   4163:             }
                   4164:         }
                   4165:     }
1.637     raeburn  4166:     return 'ok';
                   4167: }
                   4168: 
1.639     albertel 4169: sub add_filetype {
                   4170:     my ($allfiles,$file,$type)=@_;
                   4171:     if (exists($allfiles->{$file})) {
                   4172: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4173: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4174: 	}
                   4175:     } else {
                   4176: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4177:     }
                   4178: }
                   4179: 
1.1164    raeburn  4180: sub embedded_dependency {
                   4181:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4182:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4183:         if (($identifier ne '') &&
                   4184:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4185:             ($pathfrom ne '')) {
                   4186:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4187:             foreach my $dep (@{$related->{$identifier}}) {
                   4188:                 &add_filetype($allfiles,$path.$dep,'object');
                   4189:             }
                   4190:         }
                   4191:     }
                   4192:     return;
                   4193: }
                   4194: 
1.493     albertel 4195: sub removeuploadedurl {
1.984     neumanie 4196:     my ($url)=@_;	
                   4197:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4198:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4199: }
                   4200: 
                   4201: sub removeuserfile {
                   4202:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4203:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4204:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4205:     if ($result eq 'ok') {	
1.798     raeburn  4206:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4207:             my $metafile = $fname.'.meta';
                   4208:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4209: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4210:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4211:             my $sqlresult = 
1.823     albertel 4212:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4213:                                         'portfolio_metadata',$group,
                   4214:                                         'delete');
1.798     raeburn  4215:         }
                   4216:     }
                   4217:     return $result;
1.257     www      4218: }
1.15      www      4219: 
1.530     albertel 4220: sub mkdiruserfile {
                   4221:     my ($docuname,$docudom,$dir)=@_;
                   4222:     my $home=&homeserver($docuname,$docudom);
                   4223:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4224: }
                   4225: 
1.531     albertel 4226: sub renameuserfile {
                   4227:     my ($docuname,$docudom,$old,$new)=@_;
                   4228:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4229:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4230:                         &escape("$old").':'.&escape("$new"),$home);
                   4231:     if ($result eq 'ok') {
                   4232:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4233:             my $oldmeta = $old.'.meta';
                   4234:             my $newmeta = $new.'.meta';
                   4235:             my $metaresult = 
                   4236:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4237: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4238:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4239:             my $sqlresult = 
1.823     albertel 4240:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4241:                                         'portfolio_metadata',$group,
                   4242:                                         'delete');
1.798     raeburn  4243:         }
                   4244:     }
                   4245:     return $result;
1.531     albertel 4246: }
                   4247: 
1.14      www      4248: # ------------------------------------------------------------------------- Log
                   4249: 
                   4250: sub log {
                   4251:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4252:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4253: }
                   4254: 
                   4255: # ------------------------------------------------------------------ Course Log
1.352     www      4256: #
                   4257: # This routine flushes several buffers of non-mission-critical nature
                   4258: #
1.157     www      4259: 
                   4260: sub flushcourselogs {
1.352     www      4261:     &logthis('Flushing log buffers');
                   4262: #
                   4263: # course logs
                   4264: # This is a log of all transactions in a course, which can be used
                   4265: # for data mining purposes
                   4266: #
                   4267: # It also collects the courseid database, which lists last transaction
                   4268: # times and course titles for all courseids
                   4269: #
                   4270:     my %courseidbuffer=();
1.921     raeburn  4271:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4272:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4273: 		          &escape($courselogs{$crsid}),
                   4274: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4275: 	    delete $courselogs{$crsid};
                   4276:         } else {
                   4277:             &logthis('Failed to flush log buffer for '.$crsid);
                   4278:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4279:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4280:                         " exceeded maximum size, deleting.</font>");
                   4281:                delete $courselogs{$crsid};
                   4282:             }
1.352     www      4283:         }
1.920     raeburn  4284:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4285:             'description' => $coursedescrbuf{$crsid},
                   4286:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4287:             'type'        => $coursetypebuf{$crsid},
                   4288:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4289:         };
1.191     harris41 4290:     }
1.352     www      4291: #
                   4292: # Write course id database (reverse lookup) to homeserver of courses 
                   4293: # Is used in pickcourse
                   4294: #
1.840     albertel 4295:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4296:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4297:                                     $courseidbuffer{$crs_home},
                   4298:                                     $crs_home,'timeonly');
1.352     www      4299:     }
                   4300: #
                   4301: # File accesses
                   4302: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4303: #
1.449     matthew  4304:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4305:         if ($entry =~ /___count$/) {
                   4306:             my ($dom,$name);
1.807     albertel 4307:             ($dom,$name,undef)=
1.811     albertel 4308: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4309:             if (! defined($dom) || $dom eq '' || 
                   4310:                 ! defined($name) || $name eq '') {
1.620     albertel 4311:                 my $cid = $env{'request.course.id'};
                   4312:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4313:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4314:             }
1.450     matthew  4315:             my $value = $accesshash{$entry};
                   4316:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4317:             my %temphash=($url => $value);
1.449     matthew  4318:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4319:             if ($result eq 'ok') {
                   4320:                 delete $accesshash{$entry};
                   4321:             }
                   4322:         } else {
1.811     albertel 4323:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4324:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4325:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4326:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4327:                 delete $accesshash{$entry};
                   4328:             }
1.185     www      4329:         }
1.191     harris41 4330:     }
1.352     www      4331: #
                   4332: # Roles
                   4333: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4334: #
1.800     albertel 4335:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4336:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4337: 	    split(/\:/,$entry);
                   4338:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4339:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4340:                 $rudom,$runame) eq 'ok') {
                   4341: 	    delete $userrolehash{$entry};
                   4342:         }
                   4343:     }
1.662     raeburn  4344: #
1.1334    raeburn  4345: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4346: #
                   4347:     my %domrolebuffer = ();
1.1000    raeburn  4348:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4349:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4350:         if ($domrolebuffer{$rudom}) {
                   4351:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4352:                       '='.&escape($domainrolehash{$entry});
                   4353:         } else {
                   4354:             $domrolebuffer{$rudom}.=&escape($entry).
                   4355:                       '='.&escape($domainrolehash{$entry});
                   4356:         }
                   4357:         delete $domainrolehash{$entry};
                   4358:     }
                   4359:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4360: 	my %servers;
                   4361: 	if (defined(&domain($dom,'primary'))) {
                   4362: 	    my $primary=&domain($dom,'primary');
                   4363: 	    my $hostname=&hostname($primary);
                   4364: 	    $servers{$primary} = $hostname;
                   4365: 	} else { 
                   4366: 	    %servers = &get_servers($dom,'library');
                   4367: 	}
1.841     albertel 4368: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4369: 	    if (&reply('domroleput:'.$dom.':'.
                   4370: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4371: 		last;
                   4372: 	    } else {  
1.841     albertel 4373: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4374: 	    }
1.662     raeburn  4375:         }
                   4376:     }
1.186     www      4377:     $dumpcount++;
1.157     www      4378: }
                   4379: 
                   4380: sub courselog {
                   4381:     my $what=shift;
1.158     www      4382:     $what=time.':'.$what;
1.620     albertel 4383:     unless ($env{'request.course.id'}) { return ''; }
                   4384:     $coursedombuf{$env{'request.course.id'}}=
                   4385:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4386:     $coursenumbuf{$env{'request.course.id'}}=
                   4387:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4388:     $coursehombuf{$env{'request.course.id'}}=
                   4389:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4390:     $coursedescrbuf{$env{'request.course.id'}}=
                   4391:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4392:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4393:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4394:     $courseownerbuf{$env{'request.course.id'}}=
                   4395:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4396:     $coursetypebuf{$env{'request.course.id'}}=
                   4397:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4398:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4399: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4400:     } else {
1.620     albertel 4401: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4402:     }
1.620     albertel 4403:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4404: 	&flushcourselogs();
                   4405:     }
1.158     www      4406: }
                   4407: 
                   4408: sub courseacclog {
                   4409:     my $fnsymb=shift;
1.620     albertel 4410:     unless ($env{'request.course.id'}) { return ''; }
                   4411:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4412:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4413:         $what.=':POST';
1.583     matthew  4414:         # FIXME: Probably ought to escape things....
1.800     albertel 4415: 	foreach my $key (keys(%env)) {
                   4416:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4417:                 my $formitem = $1;
                   4418:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4419:                     $what.=':'.$formitem.'='.$env{$key};
                   4420:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4421:                     $what.=':'.$formitem.'='.$env{$key};
                   4422:                 }
1.158     www      4423:             }
1.191     harris41 4424:         }
1.583     matthew  4425:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4426:         # FIXME: We should not be depending on a form parameter that someone
                   4427:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4428:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4429:             $what.= ':POST';
                   4430:             # FIXME: Probably ought to escape things....
                   4431:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4432:                                  'crsdiscuss') {
1.620     albertel 4433:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4434:             }
                   4435:         }
1.158     www      4436:     }
                   4437:     &courselog($what);
1.149     www      4438: }
                   4439: 
1.185     www      4440: sub countacc {
                   4441:     my $url=&declutter(shift);
1.458     matthew  4442:     return if (! defined($url) || $url eq '');
1.620     albertel 4443:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4444: #
                   4445: # Mark that this url was used in this course
                   4446: #
1.620     albertel 4447:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4448: #
                   4449: # Increase the access count for this resource in this child process
                   4450: #
1.281     www      4451:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4452:     $accesshash{$key}++;
1.185     www      4453: }
1.349     www      4454: 
1.361     www      4455: sub linklog {
                   4456:     my ($from,$to)=@_;
                   4457:     $from=&declutter($from);
                   4458:     $to=&declutter($to);
                   4459:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4460:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4461: }
1.1160    www      4462: 
                   4463: sub statslog {
                   4464:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4465:     if ($users<2) { return; }
                   4466:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4467:             'course'       => $env{'request.course.id'},
                   4468:             'sections'     => '"all"',
                   4469:             'num_students' => $users,
                   4470:             'part'         => $part,
                   4471:             'symb'         => $symb,
                   4472:             'mean_tries'   => $av_attempts,
                   4473:             'deg_of_diff'  => $degdiff});
                   4474:     foreach my $key (keys(%dynstore)) {
                   4475:         $accesshash{$key}=$dynstore{$key};
                   4476:     }
                   4477: }
1.361     www      4478:   
1.349     www      4479: sub userrolelog {
                   4480:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4481:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4482:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4483:        $userrolehash
                   4484:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4485:                     =$tend.':'.$tstart;
1.662     raeburn  4486:     }
1.1169    droeschl 4487:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4488:        $userrolehash
                   4489:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4490:                     =$tend.':'.$tstart;
                   4491:     }
1.1334    raeburn  4492:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4493:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4494:        $domainrolehash
                   4495:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4496:                     = $tend.':'.$tstart;
                   4497:     }
1.351     www      4498: }
                   4499: 
1.957     raeburn  4500: sub courserolelog {
                   4501:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4502:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4503:         my $cdom = $1;
                   4504:         my $cnum = $2;
                   4505:         my $sec = $3;
                   4506:         my $namespace = 'rolelog';
                   4507:         my %storehash = (
                   4508:                            role    => $trole,
                   4509:                            start   => $tstart,
                   4510:                            end     => $tend,
                   4511:                            selfenroll => $selfenroll,
                   4512:                            context    => $context,
                   4513:                         );
                   4514:         if ($trole eq 'gr') {
                   4515:             $namespace = 'groupslog';
                   4516:             $storehash{'group'} = $sec;
                   4517:         } else {
                   4518:             $storehash{'section'} = $sec;
                   4519:         }
1.1188    raeburn  4520:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4521:                    $domain,$cnum,$cdom);
1.1184    raeburn  4522:         if (($trole ne 'st') || ($sec ne '')) {
                   4523:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4524:         }
                   4525:     }
                   4526:     return;
                   4527: }
                   4528: 
1.1184    raeburn  4529: sub domainrolelog {
                   4530:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4531:     if ($area =~ m{^/($match_domain)/$}) {
                   4532:         my $cdom = $1;
                   4533:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4534:         my $namespace = 'rolelog';
                   4535:         my %storehash = (
                   4536:                            role    => $trole,
                   4537:                            start   => $tstart,
                   4538:                            end     => $tend,
                   4539:                            context => $context,
                   4540:                         );
1.1188    raeburn  4541:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4542:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4543:     }
                   4544:     return;
                   4545: 
                   4546: }
                   4547: 
                   4548: sub coauthorrolelog {
                   4549:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4550:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4551:         my $audom = $1;
                   4552:         my $auname = $2;
                   4553:         my $namespace = 'rolelog';
                   4554:         my %storehash = (
                   4555:                            role    => $trole,
                   4556:                            start   => $tstart,
                   4557:                            end     => $tend,
                   4558:                            context => $context,
                   4559:                         );
1.1188    raeburn  4560:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4561:                    $domain,$auname,$audom);
1.1184    raeburn  4562:     }
                   4563:     return;
                   4564: }
                   4565: 
1.351     www      4566: sub get_course_adv_roles {
1.948     raeburn  4567:     my ($cid,$codes) = @_;
1.620     albertel 4568:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4569:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4570:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4571:     my %nothide=();
1.800     albertel 4572:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4573:         if ($user !~ /:/) {
                   4574: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4575:         } else {
                   4576:             $nothide{$user}=1;
                   4577:         }
1.470     www      4578:     }
1.1219    raeburn  4579:     my @possdoms = ($coursehash{'domain'});
                   4580:     if ($coursehash{'checkforpriv'}) {
                   4581:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4582:     }
1.351     www      4583:     my %returnhash=();
                   4584:     my %dumphash=
                   4585:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4586:     my $now=time;
1.997     raeburn  4587:     my %privileged;
1.1000    raeburn  4588:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4589: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4590:         if (($tstart) && ($tstart<0)) { next; }
                   4591:         if (($tend) && ($tend<$now)) { next; }
                   4592:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4593:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4594: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4595:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4596:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4597: 	if ($role eq 'cr') { next; }
1.948     raeburn  4598:         if ($codes) {
                   4599:             if ($section) { $role .= ':'.$section; }
                   4600:             if ($returnhash{$role}) {
                   4601:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4602:             } else {
                   4603:                 $returnhash{$role}=$username.':'.$domain;
                   4604:             }
1.351     www      4605:         } else {
1.988     raeburn  4606:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4607:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4608:             if ($returnhash{$key}) {
                   4609: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4610:             } else {
                   4611:                 $returnhash{$key}=$username.':'.$domain;
                   4612:             }
1.351     www      4613:         }
1.948     raeburn  4614:     }
1.400     www      4615:     return %returnhash;
                   4616: }
                   4617: 
                   4618: sub get_my_roles {
1.937     raeburn  4619:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4620:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4621:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4622:     my (%dumphash,%nothide);
1.1086    raeburn  4623:     if ($context eq 'userroles') {
1.1166    raeburn  4624:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4625:     } else {
1.1219    raeburn  4626:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4627:         if ($hidepriv) {
                   4628:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4629:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4630:                 if ($user !~ /:/) {
                   4631:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4632:                 } else {
                   4633:                     $nothide{$user} = 1;
                   4634:                 }
                   4635:             }
                   4636:         }
1.858     raeburn  4637:     }
1.400     www      4638:     my %returnhash=();
                   4639:     my $now=time;
1.999     raeburn  4640:     my %privileged;
1.800     albertel 4641:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4642:         my ($role,$tend,$tstart);
                   4643:         if ($context eq 'userroles') {
1.1149    raeburn  4644:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4645: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4646:         } else {
                   4647:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4648:         }
1.400     www      4649:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4650:         my $status = 'active';
1.939     raeburn  4651:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4652:             $status = 'previous';
                   4653:         } 
                   4654:         if (($tstart) && ($now<$tstart)) {
                   4655:             $status = 'future';
                   4656:         }
                   4657:         if (ref($types) eq 'ARRAY') {
                   4658:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4659:                 next;
                   4660:             } 
                   4661:         } else {
                   4662:             if ($status ne 'active') {
                   4663:                 next;
                   4664:             }
                   4665:         }
1.867     raeburn  4666:         my ($rolecode,$username,$domain,$section,$area);
                   4667:         if ($context eq 'userroles') {
1.1186    raeburn  4668:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4669:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4670:         } else {
                   4671:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4672:         }
1.832     raeburn  4673:         if (ref($roledoms) eq 'ARRAY') {
                   4674:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4675:                 next;
                   4676:             }
                   4677:         }
                   4678:         if (ref($roles) eq 'ARRAY') {
                   4679:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4680:                 if ($role =~ /^cr\//) {
                   4681:                     if (!grep(/^cr$/,@{$roles})) {
                   4682:                         next;
                   4683:                     }
1.1104    raeburn  4684:                 } elsif ($role =~ /^gr\//) {
                   4685:                     if (!grep(/^gr$/,@{$roles})) {
                   4686:                         next;
                   4687:                     }
1.922     raeburn  4688:                 } else {
                   4689:                     next;
                   4690:                 }
1.832     raeburn  4691:             }
1.867     raeburn  4692:         }
1.937     raeburn  4693:         if ($hidepriv) {
1.1219    raeburn  4694:             my @privroles = ('dc','su');
1.999     raeburn  4695:             if ($context eq 'userroles') {
1.1219    raeburn  4696:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4697:             } else {
1.1219    raeburn  4698:                 my $possdoms = [$domain];
                   4699:                 if (ref($roledoms) eq 'ARRAY') {
                   4700:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4701:                 }
1.1219    raeburn  4702:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4703:                     if (!$nothide{$username.':'.$domain}) {
                   4704:                         next;
                   4705:                     }
                   4706:                 }
1.937     raeburn  4707:             }
                   4708:         }
1.933     raeburn  4709:         if ($withsec) {
                   4710:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4711:                 $tstart.':'.$tend;
                   4712:         } else {
                   4713:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4714:         }
1.832     raeburn  4715:     }
1.373     www      4716:     return %returnhash;
1.399     www      4717: }
                   4718: 
1.1333    raeburn  4719: sub get_all_adhocroles {
                   4720:     my ($dom) = @_;
                   4721:     my @roles_by_num = ();
                   4722:     my %domdefaults = &get_domain_defaults($dom);
                   4723:     my (%description,%access_in_dom,%access_info);
                   4724:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4725:         my $count = 0;
                   4726:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4727:         my %ordered;
                   4728:         foreach my $role (sort(keys(%domcurrent))) {
                   4729:             my ($order,$desc,$access_in_dom);
                   4730:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4731:                 $order = $domcurrent{$role}{'order'};
                   4732:                 $desc = $domcurrent{$role}{'desc'};
                   4733:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4734:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4735:             }
                   4736:             if ($order eq '') {
                   4737:                 $order = $count;
                   4738:             }
                   4739:             $ordered{$order} = $role;
                   4740:             if ($desc ne '') {
                   4741:                 $description{$role} = $desc;
                   4742:             } else {
                   4743:                 $description{$role}= $role;
                   4744:             }
                   4745:             $count++;
                   4746:         }
                   4747:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4748:             push(@roles_by_num,$ordered{$item});
                   4749:         }
                   4750:     }
                   4751:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4752: }
                   4753: 
1.1332    raeburn  4754: sub get_my_adhocroles {
1.1333    raeburn  4755:     my ($cid,$checkreg) = @_;
                   4756:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4757:     if ($env{'request.course.id'} eq $cid) {
                   4758:         $cdom = $env{'course.'.$cid.'.domain'};
                   4759:         $cnum = $env{'course.'.$cid.'.num'};
                   4760:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4761:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4762:         $cdom = $1;
                   4763:         $cnum = $2;
                   4764:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4765:                                      $cdom,$cnum);
                   4766:     }
                   4767:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4768:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4769:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4770:         if ($rosterhash{$user} ne '') {
                   4771:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4772:             return ([],{}) if ($type eq 'auto');
                   4773:         }
                   4774:     }
                   4775:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  4776:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  4777:             my $then=$env{'user.login.time'};
                   4778:             my $update=$env{'user.update.time'};
1.1335    raeburn  4779:             if (!$update) {
                   4780:                 $update = $then;
                   4781:             }
                   4782:             my @liveroles;
1.1334    raeburn  4783:             foreach my $role ('dh','da') {
                   4784:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  4785:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  4786:                     my $limit = $update;
                   4787:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4788:                         $limit = $then;
                   4789:                     }
1.1335    raeburn  4790:                     my $activerole = 1;
                   4791:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4792:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4793:                     if ($activerole) {
                   4794:                         push(@liveroles,$role);
                   4795:                     }
1.1334    raeburn  4796:                 }
1.1332    raeburn  4797:             }
1.1335    raeburn  4798:             if (@liveroles) {
1.1332    raeburn  4799:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  4800:                     my ($accessref,$accessinfo,%access_in_dom);
                   4801:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4802:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4803:                         if (@{$roles_by_num}) {
1.1332    raeburn  4804:                             my %settings;
                   4805:                             if ($env{'request.course.id'} eq $cid) {
                   4806:                                 foreach my $envkey (keys(%env)) {
                   4807:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4808:                                         $settings{$1} = $env{$envkey};
                   4809:                                     }
                   4810:                                 }
                   4811:                             } else {
                   4812:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4813:                             }
                   4814:                             my %setincrs;
                   4815:                             if ($settings{'internal.adhocaccess'}) {
                   4816:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4817:                             }
                   4818:                             my @statuses;
                   4819:                             if ($env{'environment.inststatus'}) {
                   4820:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4821:                             }
                   4822:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  4823:                             if (ref($accessref) eq 'HASH') {
                   4824:                                 %access_in_dom = %{$accessref};
                   4825:                             }
                   4826:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  4827:                                 my ($curraccess,@okstatus,@personnel);
                   4828:                                 if ($setincrs{$role}) {
                   4829:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4830:                                     if ($curraccess eq 'status') {
                   4831:                                         @okstatus = split(/\&/,$rest);
                   4832:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4833:                                         @personnel = split(/\&/,$rest);
                   4834:                                     }
                   4835:                                 } else {
                   4836:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  4837:                                     if (ref($accessinfo) eq 'HASH') {
                   4838:                                         if ($curraccess eq 'status') {
                   4839:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4840:                                                 @okstatus = @{$accessinfo->{$role}};
                   4841:                                             }
                   4842:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4843:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4844:                                                 @personnel = @{$accessinfo->{$role}};
                   4845:                                             }
1.1332    raeburn  4846:                                         }
                   4847:                                     }
                   4848:                                 }
                   4849:                                 if ($curraccess eq 'none') {
                   4850:                                     next;
                   4851:                                 } elsif ($curraccess eq 'all') {
                   4852:                                     push(@possroles,$role);
1.1336    raeburn  4853:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  4854:                                     if (grep(/^dh$/,@liveroles)) {
                   4855:                                         push(@possroles,$role);
                   4856:                                     } else {
                   4857:                                         next;
                   4858:                                     }
1.1336    raeburn  4859:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  4860:                                     if (grep(/^da$/,@liveroles)) {
                   4861:                                         push(@possroles,$role);
                   4862:                                     } else {
                   4863:                                         next;
                   4864:                                     }
1.1332    raeburn  4865:                                 } elsif ($curraccess eq 'status') {
                   4866:                                     if (@okstatus) {
                   4867:                                         if (!@statuses) {
                   4868:                                             if (grep(/^default$/,@okstatus)) {
                   4869:                                                 push(@possroles,$role);
                   4870:                                             }
                   4871:                                         } else {
                   4872:                                             foreach my $status (@okstatus) {
                   4873:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4874:                                                     push(@possroles,$role);
                   4875:                                                     last;
                   4876:                                                 }
                   4877:                                             }
                   4878:                                         }
                   4879:                                     }
                   4880:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4881:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4882:                                         if ($curraccess eq 'exc') {
                   4883:                                             push(@possroles,$role);
                   4884:                                         }
                   4885:                                     } elsif ($curraccess eq 'inc') {
                   4886:                                         push(@possroles,$role);
                   4887:                                     }
                   4888:                                 }
                   4889:                             }
                   4890:                         }
                   4891:                     }
                   4892:                 }
                   4893:             }
                   4894:         }
                   4895:     }
1.1333    raeburn  4896:     unless (ref($description) eq 'HASH') {
                   4897:         if (ref($roles_by_num) eq 'ARRAY') {
                   4898:             my %desc;
                   4899:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   4900:             $description = \%desc;
                   4901:         } else {
                   4902:             $description = {};
                   4903:         }
                   4904:     }
                   4905:     return (\@possroles,$description);
1.1332    raeburn  4906: }
                   4907: 
1.399     www      4908: # ----------------------------------------------------- Frontpage Announcements
                   4909: #
                   4910: #
                   4911: 
                   4912: sub postannounce {
                   4913:     my ($server,$text)=@_;
1.844     albertel 4914:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4915:     unless ($text=~/\w/) { $text=''; }
                   4916:     return &reply('setannounce:'.&escape($text),$server);
                   4917: }
                   4918: 
                   4919: sub getannounce {
1.448     albertel 4920: 
1.1359    raeburn  4921:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4922: 	my $announcement='';
1.800     albertel 4923: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4924: 	close($fh);
1.399     www      4925: 	if ($announcement=~/\w/) { 
                   4926: 	    return 
                   4927:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4928:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4929: 	} else {
                   4930: 	    return '';
                   4931: 	}
                   4932:     } else {
                   4933: 	return '';
                   4934:     }
1.351     www      4935: }
1.353     www      4936: 
                   4937: # ---------------------------------------------------------- Course ID routines
                   4938: # Deal with domain's nohist_courseid.db files
                   4939: #
                   4940: 
                   4941: sub courseidput {
1.921     raeburn  4942:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4943:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4944:     my $outcome;
                   4945:     if ($caller eq 'timeonly') {
                   4946:         my $cids = '';
                   4947:         foreach my $item (keys(%$storehash)) {
                   4948:             $cids.=&escape($item).'&';
                   4949:         }
                   4950:         $cids=~s/\&$//;
                   4951:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4952:                           $coursehome);       
                   4953:     } else {
                   4954:         my $items = '';
                   4955:         foreach my $item (keys(%$storehash)) {
                   4956:             $items.= &escape($item).'='.
                   4957:                      &freeze_escape($$storehash{$item}).'&';
                   4958:         }
                   4959:         $items=~s/\&$//;
                   4960:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4961:                           $coursehome);
1.918     raeburn  4962:     }
                   4963:     if ($outcome eq 'unknown_cmd') {
                   4964:         my $what;
                   4965:         foreach my $cid (keys(%$storehash)) {
                   4966:             $what .= &escape($cid).'=';
1.921     raeburn  4967:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4968:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4969:             }
                   4970:             $what =~ s/\:$/&/;
                   4971:         }
                   4972:         $what =~ s/\&$//;  
                   4973:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4974:     } else {
                   4975:         return $outcome;
                   4976:     }
1.353     www      4977: }
                   4978: 
                   4979: sub courseiddump {
1.921     raeburn  4980:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4981:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4982:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4983:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  4984:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4985:     my $as_hash = 1;
                   4986:     my %returnhash;
                   4987:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4988:     my %libserv = &all_library();
                   4989:     foreach my $tryserver (keys(%libserv)) {
                   4990:         if ( (  $hostidflag == 1 
                   4991: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4992: 	     || (!defined($hostidflag)) ) {
                   4993: 
1.918     raeburn  4994: 	    if (($domfilter eq '') ||
                   4995: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4996:                 my $rep;
                   4997:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4998:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4999:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5000:                                 &escape($descfilter), &escape($instcodefilter), 
                   5001:                                 &escape($ownerfilter), &escape($coursefilter),
                   5002:                                 &escape($typefilter), &escape($regexp_ok), 
                   5003:                                 $as_hash, &escape($selfenrollonly), 
                   5004:                                 &escape($catfilter), $showhidden, $caller, 
                   5005:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5006:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5007:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5008:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5009:                 } else {
                   5010:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5011:                              $sincefilter.':'.&escape($descfilter).':'.
                   5012:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5013:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5014:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5015:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5016:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5017:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5018:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5019:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5020:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5021:                 }
                   5022:                      
1.918     raeburn  5023:                 my @pairs=split(/\&/,$rep);
                   5024:                 foreach my $item (@pairs) {
                   5025:                     my ($key,$value)=split(/\=/,$item,2);
                   5026:                     $key = &unescape($key);
                   5027:                     next if ($key =~ /^error: 2 /);
                   5028:                     my $result = &thaw_unescape($value);
                   5029:                     if (ref($result) eq 'HASH') {
                   5030:                         $returnhash{$key}=$result;
                   5031:                     } else {
1.921     raeburn  5032:                         my @responses = split(/:/,$value);
                   5033:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5034:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5035:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5036:                         }
1.1008    raeburn  5037:                     }
1.353     www      5038:                 }
                   5039:             }
                   5040:         }
                   5041:     }
                   5042:     return %returnhash;
                   5043: }
                   5044: 
1.1055    raeburn  5045: sub courselastaccess {
                   5046:     my ($cdom,$cnum,$hostidref) = @_;
                   5047:     my %returnhash;
                   5048:     if ($cdom && $cnum) {
                   5049:         my $chome = &homeserver($cnum,$cdom);
                   5050:         if ($chome ne 'no_host') {
                   5051:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5052:             &extract_lastaccess(\%returnhash,$rep);
                   5053:         }
                   5054:     } else {
                   5055:         if (!$cdom) { $cdom=''; }
                   5056:         my %libserv = &all_library();
                   5057:         foreach my $tryserver (keys(%libserv)) {
                   5058:             if (ref($hostidref) eq 'ARRAY') {
                   5059:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5060:             } 
                   5061:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5062:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5063:                 &extract_lastaccess(\%returnhash,$rep);
                   5064:             }
                   5065:         }
                   5066:     }
                   5067:     return %returnhash;
                   5068: }
                   5069: 
                   5070: sub extract_lastaccess {
                   5071:     my ($returnhash,$rep) = @_;
                   5072:     if (ref($returnhash) eq 'HASH') {
                   5073:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5074:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5075:                  $rep eq '') {
                   5076:             my @pairs=split(/\&/,$rep);
                   5077:             foreach my $item (@pairs) {
                   5078:                 my ($key,$value)=split(/\=/,$item,2);
                   5079:                 $key = &unescape($key);
                   5080:                 next if ($key =~ /^error: 2 /);
                   5081:                 $returnhash->{$key} = &thaw_unescape($value);
                   5082:             }
                   5083:         }
                   5084:     }
                   5085:     return;
                   5086: }
                   5087: 
1.658     raeburn  5088: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5089: 
                   5090: sub dcmailput {
1.685     raeburn  5091:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5092:     my $status = &Apache::lonnet::critical(
1.740     www      5093:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5094:        &escape($message),$server);
1.662     raeburn  5095:     return $status;
                   5096: }
                   5097: 
1.658     raeburn  5098: sub dcmaildump {
                   5099:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5100:     my %returnhash=();
1.846     albertel 5101: 
                   5102:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5103:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5104:                                                          &escape($enddate).':';
                   5105: 	my @esc_senders=map { &escape($_)} @$senders;
                   5106: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5107: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5108:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5109:             if (($key) && ($value)) {
                   5110:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5111:             }
                   5112:         }
                   5113:     }
                   5114:     return %returnhash;
                   5115: }
1.662     raeburn  5116: # ---------------------------------------------------------- Domain roles
                   5117: 
                   5118: sub get_domain_roles {
                   5119:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5120:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5121:         $startdate = '.';
                   5122:     }
1.1018    raeburn  5123:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5124:         $enddate = '.';
                   5125:     }
1.922     raeburn  5126:     my $rolelist;
                   5127:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5128:         $rolelist = join('&',@{$roles});
1.922     raeburn  5129:     }
1.662     raeburn  5130:     my %personnel = ();
1.841     albertel 5131: 
                   5132:     my %servers = &get_servers($dom,'library');
                   5133:     foreach my $tryserver (keys(%servers)) {
                   5134: 	%{$personnel{$tryserver}}=();
                   5135: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5136: 					    &escape($startdate).':'.
                   5137: 					    &escape($enddate).':'.
                   5138: 					    &escape($rolelist), $tryserver))) {
                   5139: 	    my ($key,$value) = split(/\=/,$line,2);
                   5140: 	    if (($key) && ($value)) {
                   5141: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5142: 	    }
                   5143: 	}
1.662     raeburn  5144:     }
                   5145:     return %personnel;
                   5146: }
1.658     raeburn  5147: 
1.1332    raeburn  5148: sub get_active_domroles {
                   5149:     my ($dom,$roles) = @_;
                   5150:     return () unless (ref($roles) eq 'ARRAY');
                   5151:     my $now = time;
                   5152:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5153:     my %domroles;
                   5154:     foreach my $server (keys(%dompersonnel)) {
                   5155:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5156:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5157:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5158:         }
                   5159:     }
                   5160:     return %domroles;
                   5161: }
                   5162: 
1.1057    www      5163: # ----------------------------------------------------------- Interval timing 
1.149     www      5164: 
1.1153    www      5165: {
                   5166: # Caches needed for speedup of navmaps
                   5167: # We don't want to cache this for very long at all (5 seconds at most)
                   5168: # 
                   5169: # The user for whom we cache
                   5170: my $cachedkey='';
                   5171: # The cached times for this user
                   5172: my %cachedtimes=();
                   5173: # When this was last done
1.1282    raeburn  5174: my $cachedtime='';
1.1153    www      5175: 
                   5176: sub load_all_first_access {
1.1308    raeburn  5177:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5178:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5179:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5180:         (!$ignorecache)) {
1.1154    raeburn  5181:         return;
                   5182:     }
                   5183:     $cachedtime=time;
                   5184:     $cachedkey=$uname.':'.$udom;
                   5185:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5186: }
                   5187: 
1.504     albertel 5188: sub get_first_access {
1.1308    raeburn  5189:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5190:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5191:     if ($argsymb) { $symb=$argsymb; }
                   5192:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5193:     if ($argmap) { $map = $argmap; }
1.926     albertel 5194:     if ($type eq 'course') {
                   5195: 	$res='course';
                   5196:     } elsif ($type eq 'map') {
1.588     albertel 5197: 	$res=&symbread($map);
                   5198:     } else {
                   5199: 	$res=$symb;
                   5200:     }
1.1308    raeburn  5201:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5202:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5203: }
                   5204: 
                   5205: sub set_first_access {
1.1162    raeburn  5206:     my ($type,$interval)=@_;
1.790     albertel 5207:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5208:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5209:     if ($type eq 'course') {
                   5210: 	$res='course';
                   5211:     } elsif ($type eq 'map') {
1.588     albertel 5212: 	$res=&symbread($map);
                   5213:     } else {
                   5214: 	$res=$symb;
                   5215:     }
1.1153    www      5216:     $cachedkey='';
1.1162    raeburn  5217:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 5218:     if (!$firstaccess) {
1.1162    raeburn  5219:         my $start = time;
                   5220: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5221:                           $udom,$uname);
                   5222:         if ($putres eq 'ok') {
                   5223:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5224:                  $udom,$uname); 
                   5225:             &appenv(
                   5226:                      {
                   5227:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5228:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5229:                      }
                   5230:                   );
                   5231:         }
                   5232:         return $putres;
1.505     albertel 5233:     }
                   5234:     return 'already_set';
1.504     albertel 5235: }
1.1153    www      5236: }
1.1282    raeburn  5237: 
1.110     www      5238: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5239: 
                   5240: sub expirespread {
                   5241:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5242:     my $cid=$env{'request.course.id'}; 
1.110     www      5243:     if ($cid) {
                   5244:        my $now=time;
                   5245:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5246:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5247:                             $env{'course.'.$cid.'.num'}.
1.110     www      5248: 	        	    ':nohist_expirationdates:'.
                   5249:                             &escape($key).'='.$now,
1.620     albertel 5250:                             $env{'course.'.$cid.'.home'})
1.110     www      5251:     }
                   5252:     return 'ok';
1.14      www      5253: }
                   5254: 
1.109     www      5255: # ----------------------------------------------------- Devalidate Spreadsheets
                   5256: 
                   5257: sub devalidate {
1.325     www      5258:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5259:     my $cid=$env{'request.course.id'}; 
1.109     www      5260:     if ($cid) {
1.391     matthew  5261:         # delete the stored spreadsheets for
                   5262:         # - the student level sheet of this user in course's homespace
                   5263:         # - the assessment level sheet for this resource 
                   5264:         #   for this user in user's homespace
1.553     albertel 5265: 	# - current conditional state info
1.325     www      5266: 	my $key=$uname.':'.$udom.':';
1.109     www      5267:         my $status=
1.299     matthew  5268: 	    &del('nohist_calculatedsheets',
1.391     matthew  5269: 		 [$key.'studentcalc:'],
1.620     albertel 5270: 		 $env{'course.'.$cid.'.domain'},
                   5271: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5272: 		.' '.
                   5273: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5274: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5275:         unless ($status eq 'ok ok') {
                   5276:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5277:                     $uname.' at '.$udom.' for '.
1.109     www      5278: 		    $symb.': '.$status);
1.133     albertel 5279:         }
1.553     albertel 5280: 	&delenv('user.state.'.$cid);
1.109     www      5281:     }
                   5282: }
                   5283: 
1.265     albertel 5284: sub get_scalar {
                   5285:     my ($string,$end) = @_;
                   5286:     my $value;
                   5287:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5288: 	$value = $1;
                   5289:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5290: 	$value = $1;
                   5291:     }
                   5292:     return &unescape($value);
                   5293: }
                   5294: 
                   5295: sub array2str {
                   5296:   my (@array) = @_;
                   5297:   my $result=&arrayref2str(\@array);
                   5298:   $result=~s/^__ARRAY_REF__//;
                   5299:   $result=~s/__END_ARRAY_REF__$//;
                   5300:   return $result;
                   5301: }
                   5302: 
1.204     albertel 5303: sub arrayref2str {
                   5304:   my ($arrayref) = @_;
1.265     albertel 5305:   my $result='__ARRAY_REF__';
1.204     albertel 5306:   foreach my $elem (@$arrayref) {
1.265     albertel 5307:     if(ref($elem) eq 'ARRAY') {
                   5308:       $result.=&arrayref2str($elem).'&';
                   5309:     } elsif(ref($elem) eq 'HASH') {
                   5310:       $result.=&hashref2str($elem).'&';
                   5311:     } elsif(ref($elem)) {
                   5312:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5313:     } else {
                   5314:       $result.=&escape($elem).'&';
                   5315:     }
                   5316:   }
                   5317:   $result=~s/\&$//;
1.265     albertel 5318:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5319:   return $result;
                   5320: }
                   5321: 
1.168     albertel 5322: sub hash2str {
1.204     albertel 5323:   my (%hash) = @_;
                   5324:   my $result=&hashref2str(\%hash);
1.265     albertel 5325:   $result=~s/^__HASH_REF__//;
                   5326:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5327:   return $result;
                   5328: }
                   5329: 
                   5330: sub hashref2str {
                   5331:   my ($hashref)=@_;
1.265     albertel 5332:   my $result='__HASH_REF__';
1.800     albertel 5333:   foreach my $key (sort(keys(%$hashref))) {
                   5334:     if (ref($key) eq 'ARRAY') {
                   5335:       $result.=&arrayref2str($key).'=';
                   5336:     } elsif (ref($key) eq 'HASH') {
                   5337:       $result.=&hashref2str($key).'=';
                   5338:     } elsif (ref($key)) {
1.265     albertel 5339:       $result.='=';
1.800     albertel 5340:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5341:     } else {
1.1132    raeburn  5342: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5343:     }
                   5344: 
1.800     albertel 5345:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5346:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5347:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5348:       $result.=&hashref2str($hashref->{$key}).'&';
                   5349:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5350:        $result.='&';
1.800     albertel 5351:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5352:     } else {
1.800     albertel 5353:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5354:     }
                   5355:   }
1.168     albertel 5356:   $result=~s/\&$//;
1.265     albertel 5357:   $result .= '__END_HASH_REF__';
1.168     albertel 5358:   return $result;
                   5359: }
                   5360: 
                   5361: sub str2hash {
1.265     albertel 5362:     my ($string)=@_;
                   5363:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5364:     return %$hash;
                   5365: }
                   5366: 
                   5367: sub str2hashref {
1.168     albertel 5368:   my ($string) = @_;
1.265     albertel 5369: 
                   5370:   my %hash;
                   5371: 
                   5372:   if($string !~ /^__HASH_REF__/) {
                   5373:       if (! ($string eq '' || !defined($string))) {
                   5374: 	  $hash{'error'}='Not hash reference';
                   5375:       }
                   5376:       return (\%hash, $string);
                   5377:   }
                   5378: 
                   5379:   $string =~ s/^__HASH_REF__//;
                   5380: 
                   5381:   while($string !~ /^__END_HASH_REF__/) {
                   5382:       #key
                   5383:       my $key='';
                   5384:       if($string =~ /^__HASH_REF__/) {
                   5385:           ($key, $string)=&str2hashref($string);
                   5386:           if(defined($key->{'error'})) {
                   5387:               $hash{'error'}='Bad data';
                   5388:               return (\%hash, $string);
                   5389:           }
                   5390:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5391:           ($key, $string)=&str2arrayref($string);
                   5392:           if($key->[0] eq 'Array reference error') {
                   5393:               $hash{'error'}='Bad data';
                   5394:               return (\%hash, $string);
                   5395:           }
                   5396:       } else {
                   5397:           $string =~ s/^(.*?)=//;
1.267     albertel 5398: 	  $key=&unescape($1);
1.265     albertel 5399:       }
                   5400:       $string =~ s/^=//;
                   5401: 
                   5402:       #value
                   5403:       my $value='';
                   5404:       if($string =~ /^__HASH_REF__/) {
                   5405:           ($value, $string)=&str2hashref($string);
                   5406:           if(defined($value->{'error'})) {
                   5407:               $hash{'error'}='Bad data';
                   5408:               return (\%hash, $string);
                   5409:           }
                   5410:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5411:           ($value, $string)=&str2arrayref($string);
                   5412:           if($value->[0] eq 'Array reference error') {
                   5413:               $hash{'error'}='Bad data';
                   5414:               return (\%hash, $string);
                   5415:           }
                   5416:       } else {
                   5417: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5418:       }
                   5419:       $string =~ s/^&//;
                   5420: 
                   5421:       $hash{$key}=$value;
1.204     albertel 5422:   }
1.265     albertel 5423: 
                   5424:   $string =~ s/^__END_HASH_REF__//;
                   5425: 
                   5426:   return (\%hash, $string);
1.204     albertel 5427: }
                   5428: 
                   5429: sub str2array {
1.265     albertel 5430:     my ($string)=@_;
                   5431:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5432:     return @$array;
                   5433: }
                   5434: 
                   5435: sub str2arrayref {
1.204     albertel 5436:   my ($string) = @_;
1.265     albertel 5437:   my @array;
                   5438: 
                   5439:   if($string !~ /^__ARRAY_REF__/) {
                   5440:       if (! ($string eq '' || !defined($string))) {
                   5441: 	  $array[0]='Array reference error';
                   5442:       }
                   5443:       return (\@array, $string);
                   5444:   }
                   5445: 
                   5446:   $string =~ s/^__ARRAY_REF__//;
                   5447: 
                   5448:   while($string !~ /^__END_ARRAY_REF__/) {
                   5449:       my $value='';
                   5450:       if($string =~ /^__HASH_REF__/) {
                   5451:           ($value, $string)=&str2hashref($string);
                   5452:           if(defined($value->{'error'})) {
                   5453:               $array[0] ='Array reference error';
                   5454:               return (\@array, $string);
                   5455:           }
                   5456:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5457:           ($value, $string)=&str2arrayref($string);
                   5458:           if($value->[0] eq 'Array reference error') {
                   5459:               $array[0] ='Array reference error';
                   5460:               return (\@array, $string);
                   5461:           }
                   5462:       } else {
                   5463: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5464:       }
                   5465:       $string =~ s/^&//;
                   5466: 
                   5467:       push(@array, $value);
1.191     harris41 5468:   }
1.265     albertel 5469: 
                   5470:   $string =~ s/^__END_ARRAY_REF__//;
                   5471: 
                   5472:   return (\@array, $string);
1.168     albertel 5473: }
                   5474: 
1.167     albertel 5475: # -------------------------------------------------------------------Temp Store
                   5476: 
1.168     albertel 5477: sub tmpreset {
                   5478:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5479:   if (!$symb) {
                   5480:     $symb=&symbread();
1.620     albertel 5481:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5482:   }
                   5483:   $symb=escape($symb);
                   5484: 
1.620     albertel 5485:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5486:   $namespace=~s/\//\_/g;
                   5487:   $namespace=~s/\W//g;
                   5488: 
1.620     albertel 5489:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5490:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5491:   if ($domain eq 'public' && $stuname eq 'public') {
                   5492:       $stuname=$ENV{'REMOTE_ADDR'};
                   5493:   }
1.1117    foxr     5494:   my $path=LONCAPA::tempdir();
1.168     albertel 5495:   my %hash;
                   5496:   if (tie(%hash,'GDBM_File',
                   5497: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5498: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5499:     foreach my $key (keys(%hash)) {
1.180     albertel 5500:       if ($key=~ /:$symb/) {
1.168     albertel 5501: 	delete($hash{$key});
                   5502:       }
                   5503:     }
                   5504:   }
                   5505: }
                   5506: 
1.167     albertel 5507: sub tmpstore {
1.168     albertel 5508:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5509: 
                   5510:   if (!$symb) {
                   5511:     $symb=&symbread();
1.620     albertel 5512:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5513:   }
                   5514:   $symb=escape($symb);
                   5515: 
                   5516:   if (!$namespace) {
                   5517:     # I don't think we would ever want to store this for a course.
                   5518:     # it seems this will only be used if we don't have a course.
1.620     albertel 5519:     #$namespace=$env{'request.course.id'};
1.168     albertel 5520:     #if (!$namespace) {
1.620     albertel 5521:       $namespace=$env{'request.state'};
1.168     albertel 5522:     #}
                   5523:   }
                   5524:   $namespace=~s/\//\_/g;
                   5525:   $namespace=~s/\W//g;
1.620     albertel 5526:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5527:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5528:   if ($domain eq 'public' && $stuname eq 'public') {
                   5529:       $stuname=$ENV{'REMOTE_ADDR'};
                   5530:   }
1.168     albertel 5531:   my $now=time;
                   5532:   my %hash;
1.1117    foxr     5533:   my $path=LONCAPA::tempdir();
1.168     albertel 5534:   if (tie(%hash,'GDBM_File',
                   5535: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5536: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5537:     $hash{"version:$symb"}++;
                   5538:     my $version=$hash{"version:$symb"};
                   5539:     my $allkeys=''; 
                   5540:     foreach my $key (keys(%$storehash)) {
                   5541:       $allkeys.=$key.':';
1.591     albertel 5542:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5543:     }
                   5544:     $hash{"$version:$symb:timestamp"}=$now;
                   5545:     $allkeys.='timestamp';
                   5546:     $hash{"$version:keys:$symb"}=$allkeys;
                   5547:     if (untie(%hash)) {
                   5548:       return 'ok';
                   5549:     } else {
                   5550:       return "error:$!";
                   5551:     }
                   5552:   } else {
                   5553:     return "error:$!";
                   5554:   }
                   5555: }
1.167     albertel 5556: 
1.168     albertel 5557: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5558: 
1.168     albertel 5559: sub tmprestore {
                   5560:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5561: 
1.168     albertel 5562:   if (!$symb) {
                   5563:     $symb=&symbread();
1.620     albertel 5564:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5565:   }
                   5566:   $symb=escape($symb);
                   5567: 
1.620     albertel 5568:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5569: 
1.620     albertel 5570:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5571:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5572:   if ($domain eq 'public' && $stuname eq 'public') {
                   5573:       $stuname=$ENV{'REMOTE_ADDR'};
                   5574:   }
1.168     albertel 5575:   my %returnhash;
                   5576:   $namespace=~s/\//\_/g;
                   5577:   $namespace=~s/\W//g;
                   5578:   my %hash;
1.1117    foxr     5579:   my $path=LONCAPA::tempdir();
1.168     albertel 5580:   if (tie(%hash,'GDBM_File',
                   5581: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5582: 	  &GDBM_READER(),0640)) {
1.168     albertel 5583:     my $version=$hash{"version:$symb"};
                   5584:     $returnhash{'version'}=$version;
                   5585:     my $scope;
                   5586:     for ($scope=1;$scope<=$version;$scope++) {
                   5587:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5588:       my @keys=split(/:/,$vkeys);
                   5589:       my $key;
                   5590:       $returnhash{"$scope:keys"}=$vkeys;
                   5591:       foreach $key (@keys) {
1.591     albertel 5592: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5593: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5594:       }
                   5595:     }
1.168     albertel 5596:     if (!(untie(%hash))) {
                   5597:       return "error:$!";
                   5598:     }
                   5599:   } else {
                   5600:     return "error:$!";
                   5601:   }
                   5602:   return %returnhash;
1.167     albertel 5603: }
                   5604: 
1.9       www      5605: # ----------------------------------------------------------------------- Store
                   5606: 
                   5607: sub store {
1.1269    raeburn  5608:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5609:     my $home='';
                   5610: 
1.168     albertel 5611:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5612: 
1.213     www      5613:     $symb=&symbclean($symb);
1.122     albertel 5614:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5615: 
1.620     albertel 5616:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5617:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5618: 
                   5619:     &devalidate($symb,$stuname,$domain);
1.109     www      5620: 
                   5621:     $symb=escape($symb);
1.187     www      5622:     if (!$namespace) { 
1.620     albertel 5623:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5624:           return ''; 
                   5625:        } 
                   5626:     }
1.620     albertel 5627:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5628: 
                   5629:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5630:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5631: 
1.12      www      5632:     my $namevalue='';
1.800     albertel 5633:     foreach my $key (keys(%$storehash)) {
                   5634:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5635:     }
1.12      www      5636:     $namevalue=~s/\&$//;
1.187     www      5637:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5638:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5639: }
                   5640: 
1.47      www      5641: # -------------------------------------------------------------- Critical Store
                   5642: 
                   5643: sub cstore {
1.1269    raeburn  5644:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5645:     my $home='';
                   5646: 
1.168     albertel 5647:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5648: 
1.213     www      5649:     $symb=&symbclean($symb);
1.122     albertel 5650:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5651: 
1.620     albertel 5652:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5653:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5654: 
                   5655:     &devalidate($symb,$stuname,$domain);
1.109     www      5656: 
                   5657:     $symb=escape($symb);
1.187     www      5658:     if (!$namespace) { 
1.620     albertel 5659:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5660:           return ''; 
                   5661:        } 
                   5662:     }
1.620     albertel 5663:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5664: 
                   5665:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5666:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5667: 
1.47      www      5668:     my $namevalue='';
1.800     albertel 5669:     foreach my $key (keys(%$storehash)) {
                   5670:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5671:     }
1.47      www      5672:     $namevalue=~s/\&$//;
1.187     www      5673:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5674:     return critical
1.1269    raeburn  5675:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5676: }
                   5677: 
1.9       www      5678: # --------------------------------------------------------------------- Restore
                   5679: 
                   5680: sub restore {
1.124     www      5681:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5682:     my $home='';
                   5683: 
1.168     albertel 5684:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5685: 
1.122     albertel 5686:     if (!$symb) {
1.1224    raeburn  5687:         return if ($namespace eq 'courserequests');
                   5688:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5689:     } else {
1.1224    raeburn  5690:         unless ($namespace eq 'courserequests') {
                   5691:             $symb=&escape(&symbclean($symb));
                   5692:         }
1.122     albertel 5693:     }
1.188     www      5694:     if (!$namespace) { 
1.620     albertel 5695:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5696:           return ''; 
                   5697:        } 
                   5698:     }
1.620     albertel 5699:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5700:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5701:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5702:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5703: 
1.12      www      5704:     my %returnhash=();
1.800     albertel 5705:     foreach my $line (split(/\&/,$answer)) {
                   5706: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5707:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5708:     }
1.75      www      5709:     my $version;
                   5710:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5711:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5712:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5713:        }
1.75      www      5714:     }
1.13      www      5715:     return %returnhash;
1.34      www      5716: }
                   5717: 
                   5718: # ---------------------------------------------------------- Course Description
1.1118    foxr     5719: #
                   5720: #  
1.34      www      5721: 
                   5722: sub coursedescription {
1.731     albertel 5723:     my ($courseid,$args)=@_;
1.34      www      5724:     $courseid=~s/^\///;
1.49      www      5725:     $courseid=~s/\_/\//g;
1.34      www      5726:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5727:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5728:     my $normalid=$cdomain.'_'.$cnum;
                   5729:     # need to always cache even if we get errors otherwise we keep 
                   5730:     # trying and trying and trying to get the course description.
                   5731:     my %envhash=();
                   5732:     my %returnhash=();
1.731     albertel 5733:     
                   5734:     my $expiretime=600;
                   5735:     if ($env{'request.course.id'} eq $normalid) {
                   5736: 	$expiretime=120;
                   5737:     }
                   5738: 
                   5739:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5740:     if (!$args->{'freshen_cache'}
                   5741: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5742: 	foreach my $key (keys(%env)) {
                   5743: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5744: 	    my ($setting) = $1;
                   5745: 	    $returnhash{$setting} = $env{$key};
                   5746: 	}
                   5747: 	return %returnhash;
                   5748:     }
                   5749: 
1.1118    foxr     5750:     # get the data again
                   5751: 
1.731     albertel 5752:     if (!$args->{'one_time'}) {
                   5753: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5754:     }
1.811     albertel 5755: 
1.34      www      5756:     if ($chome ne 'no_host') {
1.302     albertel 5757:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5758:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5759: 	   my $username = $env{'user.name'}; # Defult username
                   5760: 	   if(defined $args->{'user'}) {
                   5761: 	       $username = $args->{'user'};
                   5762: 	   }
1.129     albertel 5763:            $returnhash{'home'}= $chome;
                   5764: 	   $returnhash{'domain'} = $cdomain;
                   5765: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5766:            if (!defined($returnhash{'type'})) {
                   5767:                $returnhash{'type'} = 'Course';
                   5768:            }
1.130     albertel 5769:            while (my ($name,$value) = each %returnhash) {
1.53      www      5770:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5771:            }
1.270     www      5772:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5773:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5774: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5775:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5776:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5777:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5778:        }
                   5779:     }
1.731     albertel 5780:     if (!$args->{'one_time'}) {
1.949     raeburn  5781: 	&appenv(\%envhash);
1.731     albertel 5782:     }
1.302     albertel 5783:     return %returnhash;
1.461     www      5784: }
                   5785: 
1.1080    raeburn  5786: sub update_released_required {
                   5787:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5788:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5789:         $cid = $env{'request.course.id'};
                   5790:         $cdom = $env{'course.'.$cid.'.domain'};
                   5791:         $cnum = $env{'course.'.$cid.'.num'};
                   5792:         $chome = $env{'course.'.$cid.'.home'};
                   5793:     }
                   5794:     if ($needsrelease) {
                   5795:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5796:         my $needsupdate;
                   5797:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5798:             $needsupdate = 1;
                   5799:         } else {
                   5800:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5801:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5802:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5803:                 $needsupdate = 1;
                   5804:             }
                   5805:         }
                   5806:         if ($needsupdate) {
                   5807:             my %needshash = (
                   5808:                              'internal.releaserequired' => $needsrelease,
                   5809:                             );
                   5810:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5811:             if ($putresult eq 'ok') {
                   5812:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5813:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5814:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5815:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5816:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5817:                 }
                   5818:             }
                   5819:         }
                   5820:     }
                   5821:     return;
                   5822: }
                   5823: 
1.461     www      5824: # -------------------------------------------------See if a user is privileged
                   5825: 
                   5826: sub privileged {
1.1219    raeburn  5827:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5828:     my $now = time;
1.1219    raeburn  5829:     my $roles;
                   5830:     if (ref($possroles) eq 'ARRAY') {
                   5831:         $roles = $possroles; 
                   5832:     } else {
                   5833:         $roles = ['dc','su'];
                   5834:     }
                   5835:     if (ref($possdomains) eq 'ARRAY') {
                   5836:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5837:         foreach my $dom (@{$possdomains}) {
                   5838:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5839:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5840:                 foreach my $role (@{$roles}) {
                   5841:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5842:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5843:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5844:                             return 1 unless (($end && $end < $now) ||
                   5845:                                              ($start && $start > $now));
                   5846:                         }
                   5847:                     }
                   5848:                 }
                   5849:             }
                   5850:         }
                   5851:     } else {
                   5852:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5853:         my $now = time;
1.1170    droeschl 5854: 
1.1275    musolffc 5855:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5856:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5857:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5858:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5859:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5860:             }
1.1219    raeburn  5861:         }
                   5862:     }
                   5863:     return 0;
                   5864: }
1.1170    droeschl 5865: 
1.1219    raeburn  5866: sub privileged_by_domain {
                   5867:     my ($domains,$roles) = @_;
                   5868:     my %privileged = ();
                   5869:     my $cachetime = 60*60*24;
                   5870:     my $now = time;
                   5871:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5872:         return %privileged;
                   5873:     }
                   5874:     foreach my $dom (@{$domains}) {
                   5875:         next if (ref($privileged{$dom}) eq 'HASH');
                   5876:         my $needroles;
                   5877:         foreach my $role (@{$roles}) {
                   5878:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5879:             if (defined($cached)) {
                   5880:                 if (ref($result) eq 'HASH') {
                   5881:                     $privileged{$dom}{$role} = $result;
                   5882:                 }
                   5883:             } else {
                   5884:                 $needroles = 1;
                   5885:             }
                   5886:         }
                   5887:         if ($needroles) {
                   5888:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5889:             $privileged{$dom} = {};
                   5890:             foreach my $server (keys(%dompersonnel)) {
                   5891:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5892:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5893:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5894:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5895:                         next if ($end && $end < $now);
                   5896:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5897:                             $dompersonnel{$server}{$item};
                   5898:                     }
                   5899:                 }
                   5900:             }
                   5901:             if (ref($privileged{$dom}) eq 'HASH') {
                   5902:                 foreach my $role (@{$roles}) {
                   5903:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5904:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5905:                     } else {
                   5906:                         my %hash = ();
                   5907:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5908:                     }
                   5909:                 }
                   5910:             }
                   5911:         }
                   5912:     }
                   5913:     return %privileged;
1.9       www      5914: }
1.1       albertel 5915: 
1.103     harris41 5916: # -------------------------------------------------------- Get user privileges
1.11      www      5917: 
                   5918: sub rolesinit {
1.1169    droeschl 5919:     my ($domain, $username) = @_;
                   5920:     my %userroles = ('user.login.time' => time);
                   5921:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5922: 
                   5923:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5924:     # also, blocking can be triggered by an activating timer
                   5925:     # it's saved in the user's %env.
                   5926:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5927:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5928:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5929:         %timerintchk, %timerintenv);
                   5930: 
1.1162    raeburn  5931:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5932:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5933:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5934:     }
1.1169    droeschl 5935: 
1.1162    raeburn  5936:     foreach my $key (keys(%timerinterval)) {
                   5937:         my ($cid,$rest) = split(/\0/,$key);
                   5938:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5939:     }
1.1169    droeschl 5940: 
1.11      www      5941:     my %allroles=();
1.1162    raeburn  5942:     my %allgroups=();
1.11      www      5943: 
1.1274    raeburn  5944:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5945:         my $role = $rolesdump{$area};
                   5946:         $area =~ s/\_\w\w$//;
                   5947: 
                   5948:         my ($trole, $tend, $tstart, $group_privs);
                   5949: 
                   5950:         if ($role =~ /^cr/) {
                   5951:         # Custom role, defined by a user 
                   5952:         # e.g., user.role.cr/msu/smith/mynewrole
                   5953:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5954:                 $trole = $1;
                   5955:                 ($tend, $tstart) = split('_', $2);
                   5956:             } else {
                   5957:                 $trole = $role;
                   5958:             }
                   5959:         } elsif ($role =~ m|^gr/|) {
                   5960:         # Role of member in a group, defined within a course/community
                   5961:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5962:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5963:             next if $tstart eq '-1';
                   5964:             ($trole, $group_privs) = split(/\//, $trole);
                   5965:             $group_privs = &unescape($group_privs);
                   5966:         } else {
                   5967:         # Just a normal role, defined in roles.tab
                   5968:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5969:         }
                   5970: 
                   5971:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5972:                  $username);
                   5973:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5974: 
                   5975:         # role expired or not available yet?
                   5976:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5977:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5978: 
                   5979:         next if $area eq '' or $trole eq '';
                   5980: 
                   5981:         my $spec = "$trole.$area";
                   5982:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5983: 
                   5984:         if ($trole =~ /^cr\//) {
                   5985:         # Custom role, defined by a user
                   5986:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5987:         } elsif ($trole eq 'gr') {
                   5988:         # Role of a member in a group, defined within a course/community
                   5989:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5990:             next;
                   5991:         } else {
                   5992:         # Normal role, defined in roles.tab
                   5993:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5994:         }
                   5995: 
                   5996:         my $cid = $tdomain.'_'.$trest;
                   5997:         unless ($firstaccchk{$cid}) {
                   5998:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5999:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6000:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6001:                         $coursetimerstarts{$cid}{$item}; 
                   6002:                 }
                   6003:             }
                   6004:             $firstaccchk{$cid} = 1;
                   6005:         }
                   6006:         unless ($timerintchk{$cid}) {
                   6007:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6008:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6009:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6010:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6011:                 }
1.12      www      6012:             }
1.1169    droeschl 6013:             $timerintchk{$cid} = 1;
1.191     harris41 6014:         }
1.11      www      6015:     }
1.1169    droeschl 6016: 
1.1341    raeburn  6017:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6018:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6019:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6020:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6021: 
1.1162    raeburn  6022:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6023: }
                   6024: 
1.567     raeburn  6025: sub set_arearole {
1.1215    raeburn  6026:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6027:     unless ($nolog) {
1.567     raeburn  6028: # log the associated role with the area
1.1215    raeburn  6029:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6030:     }
1.743     albertel 6031:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6032: }
                   6033: 
                   6034: sub custom_roleprivs {
                   6035:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6036:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6037:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6038:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6039:         my ($rdummy,$roledef)=
                   6040:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6041:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6042:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6043:             if (defined($syspriv)) {
1.1043    raeburn  6044:                 if ($trest =~ /^$match_community$/) {
                   6045:                     $syspriv =~ s/bre\&S//; 
                   6046:                 }
1.567     raeburn  6047:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6048:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6049:             }
                   6050:             if ($tdomain ne '') {
                   6051:                 if (defined($dompriv)) {
                   6052:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6053:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6054:                 }
                   6055:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6056:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6057:                         my $rolename = $1;
                   6058:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6059:                     }
1.567     raeburn  6060:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6061:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6062:                 }
                   6063:             }
                   6064:         }
                   6065:     }
                   6066: }
                   6067: 
1.1332    raeburn  6068: sub course_adhocrole_privs {
                   6069:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6070:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6071:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6072:         my (%currprivs,%storeprivs);
                   6073:         foreach my $item (split(/:/,$coursepriv)) {
                   6074:             my ($priv,$restrict) = split(/\&/,$item);
                   6075:             $currprivs{$priv} = $restrict;
                   6076:         }
                   6077:         my (%possadd,%possremove,%full);
                   6078:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6079:             my ($priv,$restrict)=split(/\&/,$item);
                   6080:             $full{$priv} = $restrict;
                   6081:         }
                   6082:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6083:              next if ($item eq '');
                   6084:              my ($rule,$rest) = split(/=/,$item);
                   6085:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6086:              foreach my $priv (split(/:/,$rest)) {
                   6087:                  if ($priv ne '') {
                   6088:                      if ($rule eq 'off') {
                   6089:                          $possremove{$priv} = 1;
                   6090:                      } else {
                   6091:                          $possadd{$priv} = 1;
                   6092:                      }
                   6093:                  }
                   6094:              }
                   6095:          }
                   6096:          foreach my $priv (sort(keys(%full))) {
                   6097:              if (exists($currprivs{$priv})) {
                   6098:                  unless (exists($possremove{$priv})) {
                   6099:                      $storeprivs{$priv} = $currprivs{$priv};
                   6100:                  }
                   6101:              } elsif (exists($possadd{$priv})) {
                   6102:                  $storeprivs{$priv} = $full{$priv};
                   6103:              }
                   6104:          }
                   6105:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6106:      }
                   6107:      return $coursepriv;
                   6108: }
                   6109: 
1.678     raeburn  6110: sub group_roleprivs {
                   6111:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6112:     my $access = 1;
                   6113:     my $now = time;
                   6114:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6115:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6116:     if ($access) {
1.811     albertel 6117:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6118:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6119:     }
                   6120: }
1.567     raeburn  6121: 
                   6122: sub standard_roleprivs {
                   6123:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6124:     if (defined($pr{$trole.':s'})) {
                   6125:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6126:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6127:     }
                   6128:     if ($tdomain ne '') {
                   6129:         if (defined($pr{$trole.':d'})) {
                   6130:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6131:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6132:         }
                   6133:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6134:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6135:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6136:         }
                   6137:     }
                   6138: }
                   6139: 
                   6140: sub set_userprivs {
1.1064    raeburn  6141:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6142:     my $author=0;
                   6143:     my $adv=0;
1.1341    raeburn  6144:     my $rar=0;
1.678     raeburn  6145:     my %grouproles = ();
                   6146:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6147:         my @groupkeys; 
1.1000    raeburn  6148:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6149:             push(@groupkeys,$role);
                   6150:         }
                   6151:         if (ref($groups_roles) eq 'HASH') {
                   6152:             foreach my $key (keys(%{$groups_roles})) {
                   6153:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6154:                     push(@groupkeys,$key);
                   6155:                 }
                   6156:             }
                   6157:         }
                   6158:         if (@groupkeys > 0) {
                   6159:             foreach my $role (@groupkeys) {
                   6160:                 my ($trole,$area,$sec,$extendedarea);
                   6161:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6162:                     $trole = $1;
                   6163:                     $area = $2;
                   6164:                     $sec = $3;
                   6165:                     $extendedarea = $area.$sec;
                   6166:                     if (exists($$allgroups{$area})) {
                   6167:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6168:                             my $spec = $trole.'.'.$extendedarea;
                   6169:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6170:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6171:                         }
1.678     raeburn  6172:                     }
                   6173:                 }
                   6174:             }
                   6175:         }
                   6176:     }
1.800     albertel 6177:     foreach my $group (keys(%grouproles)) {
                   6178:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6179:     }
1.800     albertel 6180:     foreach my $role (keys(%{$allroles})) {
                   6181:         my %thesepriv;
1.941     raeburn  6182:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6183:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6184:             if ($item ne '') {
                   6185:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6186:                 if ($restrictions eq '') {
                   6187:                     $thesepriv{$privilege}='F';
                   6188:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6189:                     $thesepriv{$privilege}.=$restrictions;
                   6190:                 }
                   6191:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6192:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6193:             }
                   6194:         }
                   6195:         my $thesestr='';
1.1104    raeburn  6196:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6197: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6198: 	}
                   6199:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6200:     }
1.1341    raeburn  6201:     return ($author,$adv,$rar);
1.567     raeburn  6202: }
                   6203: 
1.994     raeburn  6204: sub role_status {
1.1104    raeburn  6205:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6206:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6207:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6208:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6209:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6210:             $$where = '/'.$two;
1.994     raeburn  6211:             $$trolecode=$$role.'.'.$$where;
                   6212:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6213:             $$tstatus='is';
1.1104    raeburn  6214:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6215:                 $$tstatus='future';
1.1034    raeburn  6216:                 if ($$tstart<$now) {
                   6217:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6218:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6219:                             my (%allroles,%allgroups,$group_privs,
                   6220:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6221:                             my %userroles = (
                   6222:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6223:                             );
1.1064    raeburn  6224:                             @rolecodes = ('cm'); 
1.1002    raeburn  6225:                             my $spec=$$role.'.'.$$where;
                   6226:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6227:                             if ($$role =~ /^cr\//) {
                   6228:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6229:                                 push(@rolecodes,'cr');
1.1002    raeburn  6230:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6231:                                 push(@rolecodes,$$role);
1.1002    raeburn  6232:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6233:                                                     $env{'user.name'});
1.1064    raeburn  6234:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6235:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6236:                                 $group_privs = &unescape($group_privs);
                   6237:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6238:                                 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  6239:                                 &get_groups_roles($tdomain,$trest,
                   6240:                                                   \%course_roles,\@rolecodes,
                   6241:                                                   \%groups_roles);
1.1002    raeburn  6242:                             } else {
1.1064    raeburn  6243:                                 push(@rolecodes,$$role);
1.1002    raeburn  6244:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6245:                             }
1.1341    raeburn  6246:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6247:                                                                    \%groups_roles);
1.1064    raeburn  6248:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6249:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6250:                         }
                   6251:                     }
1.1034    raeburn  6252:                     $$tstatus = 'is';
1.1002    raeburn  6253:                 }
1.994     raeburn  6254:             }
                   6255:             if ($$tend) {
1.1104    raeburn  6256:                 if ($$tend<$update) {
1.994     raeburn  6257:                     $$tstatus='expired';
                   6258:                 } elsif ($$tend<$now) {
                   6259:                     $$tstatus='will_not';
                   6260:                 }
                   6261:             }
                   6262:         }
                   6263:     }
                   6264: }
                   6265: 
1.1104    raeburn  6266: sub get_groups_roles {
                   6267:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6268:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6269:                   (ref($rolecodes) eq 'ARRAY') && 
                   6270:                   (ref($groups_roles) eq 'HASH')); 
                   6271:     if (keys(%{$cdom_courseroles}) > 0) {
                   6272:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6273:         if ($cdom ne '' && $cnum ne '') {
                   6274:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6275:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6276:                     my $crsrole = $1;
                   6277:                     my $crssec = $2;
                   6278:                     if ($crsrole =~ /^cr/) {
                   6279:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6280:                             push(@{$rolecodes},'cr');
                   6281:                         }
                   6282:                     } else {
                   6283:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6284:                             push(@{$rolecodes},$crsrole);
                   6285:                         }
                   6286:                     }
                   6287:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6288:                     if ($crssec ne '') {
                   6289:                         $rolekey .= "/$crssec";
                   6290:                     }
                   6291:                     $rolekey .= './';
                   6292:                     $groups_roles->{$rolekey} = $rolecodes;
                   6293:                 }
                   6294:             }
                   6295:         }
                   6296:     }
                   6297:     return;
                   6298: }
                   6299: 
                   6300: sub delete_env_groupprivs {
                   6301:     my ($where,$courseroles,$possroles) = @_;
                   6302:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6303:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6304:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6305:         %{$courseroles->{$udom}} =
                   6306:             &get_my_roles('','','userroles',['active'],
                   6307:                           $possroles,[$udom],1);
                   6308:     }
                   6309:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6310:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6311:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6312:             my $area = '/'.$cdom.'/'.$cnum;
                   6313:             my $privkey = "user.priv.$crsrole.$area";
                   6314:             if ($crssec ne '') {
                   6315:                 $privkey .= '/'.$crssec;
                   6316:             }
                   6317:             $privkey .= ".$area/$group";
                   6318:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6319:         }
                   6320:     }
                   6321:     return;
                   6322: }
                   6323: 
1.994     raeburn  6324: sub check_adhoc_privs {
1.1329    raeburn  6325:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6326:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6327:     if ($sec) {
                   6328:         $cckey .= '/'.$sec;
                   6329:     } 
1.1185    raeburn  6330:     my $setprivs;
1.994     raeburn  6331:     if ($env{$cckey}) {
                   6332:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6333:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6334:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6335:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6336:             $setprivs = 1;
1.994     raeburn  6337:         }
                   6338:     } else {
1.1330    raeburn  6339:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6340:         $setprivs = 1;
1.994     raeburn  6341:     }
1.1185    raeburn  6342:     return $setprivs;
1.994     raeburn  6343: }
                   6344: 
                   6345: sub set_adhoc_privileges {
1.1326    raeburn  6346: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6347:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6348:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6349:     if ($sec ne '') {
                   6350:         $area .= '/'.$sec;
                   6351:     }
1.994     raeburn  6352:     my $spec = $role.'.'.$area;
                   6353:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6354:                                   $env{'user.name'},1);
1.1326    raeburn  6355:     my %rolehash = ();
1.1332    raeburn  6356:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6357:         my $rolename = $1;
1.1326    raeburn  6358:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6359:         my %domdef = &get_domain_defaults($dcdom);
                   6360:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6361:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6362:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6363:             }
                   6364:         }
1.1326    raeburn  6365:     } else {
                   6366:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6367:     }
1.1341    raeburn  6368:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6369:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  6370:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6371:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6372:         &appenv( {'request.role'        => $spec,
                   6373:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6374:                   'request.course.sec'  => $sec,
1.1088    raeburn  6375:                  }
                   6376:                );
                   6377:         my $tadv=0;
                   6378:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6379:         &appenv({'request.role.adv'    => $tadv});
                   6380:     }
1.994     raeburn  6381: }
                   6382: 
1.12      www      6383: # --------------------------------------------------------------- get interface
                   6384: 
                   6385: sub get {
1.131     albertel 6386:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6387:    my $items='';
1.800     albertel 6388:    foreach my $item (@$storearr) {
                   6389:        $items.=&escape($item).'&';
1.191     harris41 6390:    }
1.12      www      6391:    $items=~s/\&$//;
1.620     albertel 6392:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6393:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6394:    my $uhome=&homeserver($uname,$udomain);
                   6395: 
1.133     albertel 6396:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6397:    my @pairs=split(/\&/,$rep);
1.273     albertel 6398:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6399:      return @pairs;
                   6400:    }
1.15      www      6401:    my %returnhash=();
1.42      www      6402:    my $i=0;
1.800     albertel 6403:    foreach my $item (@$storearr) {
                   6404:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6405:       $i++;
1.191     harris41 6406:    }
1.15      www      6407:    return %returnhash;
1.27      www      6408: }
                   6409: 
                   6410: # --------------------------------------------------------------- del interface
                   6411: 
                   6412: sub del {
1.133     albertel 6413:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6414:    my $items='';
1.800     albertel 6415:    foreach my $item (@$storearr) {
                   6416:        $items.=&escape($item).'&';
1.191     harris41 6417:    }
1.984     neumanie 6418: 
1.27      www      6419:    $items=~s/\&$//;
1.620     albertel 6420:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6421:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6422:    my $uhome=&homeserver($uname,$udomain);
                   6423:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6424: }
                   6425: 
                   6426: # -------------------------------------------------------------- dump interface
                   6427: 
1.1180    droeschl 6428: sub unserialize {
                   6429:     my ($rep, $escapedkeys) = @_;
                   6430: 
                   6431:     return {} if $rep =~ /^error/;
                   6432: 
                   6433:     my %returnhash=();
1.1252    raeburn  6434: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6435: 	    my ($key, $value) = split(/=/, $item, 2);
                   6436: 	    $key = unescape($key) unless $escapedkeys;
                   6437: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  6438: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 6439: 	}
                   6440:     #return %returnhash;
                   6441:     return \%returnhash;
                   6442: }        
                   6443: 
                   6444: # see Lond::dump_with_regexp
                   6445: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6446: sub dump {
1.1180    droeschl 6447:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6448:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6449:     if (!$uname) { $uname=$env{'user.name'}; }
                   6450:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6451: 
1.1266    raeburn  6452:     if ($regexp) {
                   6453:         $regexp=&escape($regexp);
                   6454:     } else {
                   6455:         $regexp='.';
                   6456:     }
1.1180    droeschl 6457:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   6458:         # user is hosted on this machine
1.1266    raeburn  6459:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  6460:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 6461:         return %{unserialize($reply, $escapedkeys)};
                   6462:     }
1.1166    raeburn  6463:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6464:     my @pairs=split(/\&/,$rep);
                   6465:     my %returnhash=();
1.1098    foxr     6466:     if (!($rep =~ /^error/ )) {
                   6467: 	foreach my $item (@pairs) {
                   6468: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 6469:         $key = unescape($key) unless $escapedkeys;
                   6470:         #$key = &unescape($key);
1.1098    foxr     6471: 	    next if ($key =~ /^error: 2 /);
                   6472: 	    $returnhash{$key}=&thaw_unescape($value);
                   6473: 	}
1.755     albertel 6474:     }
                   6475:     return %returnhash;
1.407     www      6476: }
                   6477: 
1.1098    foxr     6478: 
1.717     albertel 6479: # --------------------------------------------------------- dumpstore interface
                   6480: 
                   6481: sub dumpstore {
                   6482:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 6483:    # same as dump but keys must be escaped. They may contain colon separated
                   6484:    # lists of values that may themself contain colons (e.g. symbs).
                   6485:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6486: }
                   6487: 
1.407     www      6488: # -------------------------------------------------------------- keys interface
                   6489: 
                   6490: sub getkeys {
                   6491:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6492:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6493:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6494:    my $uhome=&homeserver($uname,$udomain);
                   6495:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6496:    my @keyarray=();
1.800     albertel 6497:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6498:       next if ($key =~ /^error: 2 /);
1.800     albertel 6499:       push(@keyarray,&unescape($key));
1.407     www      6500:    }
                   6501:    return @keyarray;
1.318     matthew  6502: }
                   6503: 
1.319     matthew  6504: # --------------------------------------------------------------- currentdump
                   6505: sub currentdump {
1.328     matthew  6506:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6507:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6508:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6509:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6510:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 6511:    my $rep;
                   6512: 
                   6513:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6514:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6515:                    $courseid)));
                   6516:    } else {
                   6517:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6518:    }
                   6519: 
1.318     matthew  6520:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6521:    #
1.318     matthew  6522:    my %returnhash=();
1.319     matthew  6523:    #
1.1343    raeburn  6524:    if ($rep eq 'unknown_cmd') {
1.319     matthew  6525:        # an old lond will not know currentdump
                   6526:        # Do a dump and make it look like a currentdump
1.822     albertel 6527:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6528:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6529:        my %hash = @tmp;
                   6530:        @tmp=();
1.424     matthew  6531:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6532:    } else {
                   6533:        my @pairs=split(/\&/,$rep);
1.800     albertel 6534:        foreach my $pair (@pairs) {
                   6535:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6536:            my ($symb,$param) = split(/:/,$key);
                   6537:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6538:                                                         &thaw_unescape($value);
1.319     matthew  6539:        }
1.191     harris41 6540:    }
1.12      www      6541:    return %returnhash;
1.424     matthew  6542: }
                   6543: 
                   6544: sub convert_dump_to_currentdump{
                   6545:     my %hash = %{shift()};
                   6546:     my %returnhash;
                   6547:     # Code ripped from lond, essentially.  The only difference
                   6548:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6549:     # we might run in to problems with parameter names =~ /^v\./
                   6550:     while (my ($key,$value) = each(%hash)) {
                   6551:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6552: 	$symb  = &unescape($symb);
                   6553: 	$param = &unescape($param);
1.424     matthew  6554:         next if ($v eq 'version' || $symb eq 'keys');
                   6555:         next if (exists($returnhash{$symb}) &&
                   6556:                  exists($returnhash{$symb}->{$param}) &&
                   6557:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6558:         $returnhash{$symb}->{$param}=$value;
                   6559:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6560:     }
                   6561:     #
                   6562:     # Remove all of the keys in the hashes which keep track of
                   6563:     # the version of the parameter.
                   6564:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6565:         # use a foreach because we are going to delete from the hash.
                   6566:         foreach my $key (keys(%$param_hash)) {
                   6567:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6568:         }
                   6569:     }
                   6570:     return \%returnhash;
1.12      www      6571: }
                   6572: 
1.627     albertel 6573: # ------------------------------------------------------ critical inc interface
                   6574: 
                   6575: sub cinc {
                   6576:     return &inc(@_,'critical');
                   6577: }
                   6578: 
1.449     matthew  6579: # --------------------------------------------------------------- inc interface
                   6580: 
                   6581: sub inc {
1.627     albertel 6582:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6583:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6584:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6585:     my $uhome=&homeserver($uname,$udomain);
                   6586:     my $items='';
                   6587:     if (! ref($store)) {
                   6588:         # got a single value, so use that instead
                   6589:         $items = &escape($store).'=&';
                   6590:     } elsif (ref($store) eq 'SCALAR') {
                   6591:         $items = &escape($$store).'=&';        
                   6592:     } elsif (ref($store) eq 'ARRAY') {
                   6593:         $items = join('=&',map {&escape($_);} @{$store});
                   6594:     } elsif (ref($store) eq 'HASH') {
                   6595:         while (my($key,$value) = each(%{$store})) {
                   6596:             $items.= &escape($key).'='.&escape($value).'&';
                   6597:         }
                   6598:     }
                   6599:     $items=~s/\&$//;
1.627     albertel 6600:     if ($critical) {
                   6601: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6602:     } else {
                   6603: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6604:     }
1.449     matthew  6605: }
                   6606: 
1.12      www      6607: # --------------------------------------------------------------- put interface
                   6608: 
                   6609: sub put {
1.134     albertel 6610:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6611:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6612:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6613:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6614:    my $items='';
1.800     albertel 6615:    foreach my $item (keys(%$storehash)) {
                   6616:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6617:    }
1.12      www      6618:    $items=~s/\&$//;
1.134     albertel 6619:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6620: }
                   6621: 
1.631     albertel 6622: # ------------------------------------------------------------ newput interface
                   6623: 
                   6624: sub newput {
                   6625:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6626:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6627:    if (!$uname) { $uname=$env{'user.name'}; }
                   6628:    my $uhome=&homeserver($uname,$udomain);
                   6629:    my $items='';
                   6630:    foreach my $key (keys(%$storehash)) {
                   6631:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6632:    }
                   6633:    $items=~s/\&$//;
                   6634:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6635: }
                   6636: 
                   6637: # ---------------------------------------------------------  putstore interface
                   6638: 
1.524     raeburn  6639: sub putstore {
1.1269    raeburn  6640:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6641:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6642:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6643:    my $uhome=&homeserver($uname,$udomain);
                   6644:    my $items='';
1.715     albertel 6645:    foreach my $key (keys(%$storehash)) {
                   6646:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6647:    }
1.715     albertel 6648:    $items=~s/\&$//;
1.716     albertel 6649:    my $esc_symb=&escape($symb);
                   6650:    my $esc_v=&escape($version);
1.715     albertel 6651:    my $reply =
1.716     albertel 6652:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6653: 	      $uhome);
1.1269    raeburn  6654:    if (($tolog) && ($reply eq 'ok')) {
                   6655:        my $namevalue='';
                   6656:        foreach my $key (keys(%{$storehash})) {
                   6657:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6658:        }
                   6659:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6660:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6661:                      '&version='.$esc_v.
                   6662:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6663:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6664:    }
1.715     albertel 6665:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6666:        # gfall back to way things use to be done
1.715     albertel 6667:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6668: 			    $uname);
1.524     raeburn  6669:    }
1.715     albertel 6670:    return $reply;
                   6671: }
                   6672: 
                   6673: sub old_putstore {
1.716     albertel 6674:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6675:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6676:     if (!$uname) { $uname=$env{'user.name'}; }
                   6677:     my $uhome=&homeserver($uname,$udomain);
                   6678:     my %newstorehash;
1.800     albertel 6679:     foreach my $item (keys(%$storehash)) {
                   6680: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6681: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6682:     }
                   6683:     my $items='';
                   6684:     my %allitems = ();
1.800     albertel 6685:     foreach my $item (keys(%newstorehash)) {
                   6686: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6687: 	    my $key = $1.':keys:'.$2;
                   6688: 	    $allitems{$key} .= $3.':';
                   6689: 	}
1.800     albertel 6690: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6691:     }
1.800     albertel 6692:     foreach my $item (keys(%allitems)) {
                   6693: 	$allitems{$item} =~ s/\:$//;
                   6694: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6695:     }
                   6696:     $items=~s/\&$//;
                   6697:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6698: }
                   6699: 
1.47      www      6700: # ------------------------------------------------------ critical put interface
                   6701: 
                   6702: sub cput {
1.134     albertel 6703:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6704:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6705:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6706:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6707:    my $items='';
1.800     albertel 6708:    foreach my $item (keys(%$storehash)) {
                   6709:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6710:    }
1.47      www      6711:    $items=~s/\&$//;
1.134     albertel 6712:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6713: }
                   6714: 
                   6715: # -------------------------------------------------------------- eget interface
                   6716: 
                   6717: sub eget {
1.133     albertel 6718:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6719:    my $items='';
1.800     albertel 6720:    foreach my $item (@$storearr) {
                   6721:        $items.=&escape($item).'&';
1.191     harris41 6722:    }
1.12      www      6723:    $items=~s/\&$//;
1.620     albertel 6724:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6725:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6726:    my $uhome=&homeserver($uname,$udomain);
                   6727:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6728:    my @pairs=split(/\&/,$rep);
                   6729:    my %returnhash=();
1.42      www      6730:    my $i=0;
1.800     albertel 6731:    foreach my $item (@$storearr) {
                   6732:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6733:       $i++;
1.191     harris41 6734:    }
1.12      www      6735:    return %returnhash;
                   6736: }
                   6737: 
1.667     albertel 6738: # ------------------------------------------------------------ tmpput interface
                   6739: sub tmpput {
1.802     raeburn  6740:     my ($storehash,$server,$context)=@_;
1.667     albertel 6741:     my $items='';
1.800     albertel 6742:     foreach my $item (keys(%$storehash)) {
                   6743: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6744:     }
                   6745:     $items=~s/\&$//;
1.802     raeburn  6746:     if (defined($context)) {
                   6747:         $items .= ':'.&escape($context);
                   6748:     }
1.667     albertel 6749:     return &reply("tmpput:$items",$server);
                   6750: }
                   6751: 
                   6752: # ------------------------------------------------------------ tmpget interface
                   6753: sub tmpget {
1.688     albertel 6754:     my ($token,$server)=@_;
                   6755:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6756:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6757:     my %returnhash;
1.1328    raeburn  6758:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6759:         return %returnhash;
                   6760:     }
1.667     albertel 6761:     foreach my $item (split(/\&/,$rep)) {
                   6762: 	my ($key,$value)=split(/=/,$item);
                   6763: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6764:     }
                   6765:     return %returnhash;
                   6766: }
                   6767: 
1.1113    raeburn  6768: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6769: sub tmpdel {
                   6770:     my ($token,$server)=@_;
                   6771:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6772:     return &reply("tmpdel:$token",$server);
                   6773: }
                   6774: 
1.1198    raeburn  6775: # ------------------------------------------------------------ get_timebased_id 
                   6776: 
                   6777: sub get_timebased_id {
                   6778:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6779:         $maxtries) = @_;
                   6780:     my ($newid,$error,$dellock);
                   6781:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6782:         return ('','ok','invalid call to get suffix');
                   6783:     }
                   6784: 
                   6785: # set defaults for any optional args for which values were not supplied
                   6786:     if ($who eq '') {
                   6787:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6788:     }
                   6789:     if (!$locktries) {
                   6790:         $locktries = 3;
                   6791:     }
                   6792:     if (!$maxtries) {
                   6793:         $maxtries = 10;
                   6794:     }
                   6795:     
                   6796:     if (($cdom eq '') || ($cnum eq '')) {
                   6797:         if ($env{'request.course.id'}) {
                   6798:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6799:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6800:         }
                   6801:         if (($cdom eq '') || ($cnum eq '')) {
                   6802:             return ('','ok','call to get suffix not in course context');
                   6803:         }
                   6804:     }
                   6805: 
                   6806: # construct locking item
                   6807:     my $lockhash = {
                   6808:                       $prefix."\0".'locked_'.$keyid => $who,
                   6809:                    };
                   6810:     my $tries = 0;
                   6811: 
                   6812: # attempt to get lock on nohist_$namespace file
                   6813:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6814:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6815:         $tries ++;
                   6816:         sleep 1;
                   6817:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6818:     }
                   6819: 
                   6820: # attempt to get unique identifier, based on current timestamp
                   6821:     if ($gotlock eq 'ok') {
                   6822:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6823:         my $id = time;
                   6824:         $newid = $id;
1.1268    raeburn  6825:         if ($idtype eq 'addcode') {
                   6826:             $newid .= &sixnum_code();
                   6827:         }
1.1198    raeburn  6828:         my $idtries = 0;
                   6829:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6830:             if ($idtype eq 'concat') {
                   6831:                 $newid = $id.$idtries;
1.1268    raeburn  6832:             } elsif ($idtype eq 'addcode') {
                   6833:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6834:             } else {
                   6835:                 $newid ++;
                   6836:             }
                   6837:             $idtries ++;
                   6838:         }
                   6839:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6840:             my %new_item =  (
                   6841:                               $prefix."\0".$newid => $who,
                   6842:                             );
                   6843:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6844:                                                  $cdom,$cnum);
                   6845:             if ($putresult ne 'ok') {
                   6846:                 undef($newid);
                   6847:                 $error = 'error saving new item: '.$putresult;
                   6848:             }
                   6849:         } else {
1.1268    raeburn  6850:              undef($newid);
1.1198    raeburn  6851:              $error = ('error: no unique suffix available for the new item ');
                   6852:         }
                   6853: #  remove lock
                   6854:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6855:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6856:     } else {
                   6857:         $error = "error: could not obtain lockfile\n";
                   6858:         $dellock = 'ok';
1.1276    raeburn  6859:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6860:             $dellock = 'nolock';
                   6861:         }
1.1198    raeburn  6862:     }
                   6863:     return ($newid,$dellock,$error);
                   6864: }
                   6865: 
1.1268    raeburn  6866: sub sixnum_code {
                   6867:     my $code;
                   6868:     for (0..6) {
                   6869:         $code .= int( rand(9) );
                   6870:     }
                   6871:     return $code;
                   6872: }
                   6873: 
1.765     albertel 6874: # -------------------------------------------------- portfolio access checking
                   6875: 
                   6876: sub portfolio_access {
1.1270    raeburn  6877:     my ($requrl,$clientip) = @_;
1.765     albertel 6878:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6879:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6880:     if ($result) {
                   6881:         my %setters;
                   6882:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6883:             my ($startblock,$endblock) =
                   6884:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6885:             if ($startblock && $endblock) {
                   6886:                 return 'B';
                   6887:             }
                   6888:         } else {
                   6889:             my ($startblock,$endblock) =
                   6890:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6891:             if ($startblock && $endblock) {
                   6892:                 return 'B';
                   6893:             }
                   6894:         }
                   6895:     }
1.765     albertel 6896:     if ($result eq 'ok') {
1.766     albertel 6897:        return 'F';
1.765     albertel 6898:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6899:        return 'A';
1.765     albertel 6900:     }
1.766     albertel 6901:     return '';
1.765     albertel 6902: }
                   6903: 
                   6904: sub get_portfolio_access {
1.1270    raeburn  6905:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6906: 
                   6907:     if (!ref($access_hash)) {
                   6908: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6909: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6910: 						   $file_name);
                   6911: 	$access_hash = $access_controls{$file_name};
                   6912:     }
                   6913: 
1.1270    raeburn  6914:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6915:     my $now = time;
                   6916:     if (ref($access_hash) eq 'HASH') {
                   6917:         foreach my $key (keys(%{$access_hash})) {
                   6918:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6919:             if ($start > $now) {
                   6920:                 next;
                   6921:             }
                   6922:             if ($end && $end<$now) {
                   6923:                 next;
                   6924:             }
                   6925:             if ($scope eq 'public') {
                   6926:                 $public = $key;
                   6927:                 last;
                   6928:             } elsif ($scope eq 'guest') {
                   6929:                 $guest = $key;
                   6930:             } elsif ($scope eq 'domains') {
                   6931:                 push(@domains,$key);
                   6932:             } elsif ($scope eq 'users') {
                   6933:                 push(@users,$key);
                   6934:             } elsif ($scope eq 'course') {
                   6935:                 push(@courses,$key);
                   6936:             } elsif ($scope eq 'group') {
                   6937:                 push(@groups,$key);
1.1270    raeburn  6938:             } elsif ($scope eq 'ip') {
                   6939:                 push(@ips,$key);
1.765     albertel 6940:             }
                   6941:         }
                   6942:         if ($public) {
                   6943:             return 'ok';
1.1270    raeburn  6944:         } elsif (@ips > 0) {
                   6945:             my $allowed;
                   6946:             foreach my $ipkey (@ips) {
                   6947:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6948:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6949:                         $allowed = 1;
                   6950:                         last; 
                   6951:                     }
                   6952:                 }
                   6953:             }
                   6954:             if ($allowed) {
                   6955:                 return 'ok';
                   6956:             }
1.765     albertel 6957:         }
                   6958:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6959:             if ($guest) {
                   6960:                 return $guest;
                   6961:             }
                   6962:         } else {
                   6963:             if (@domains > 0) {
                   6964:                 foreach my $domkey (@domains) {
                   6965:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6966:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6967:                             return 'ok';
                   6968:                         }
                   6969:                     }
                   6970:                 }
                   6971:             }
                   6972:             if (@users > 0) {
                   6973:                 foreach my $userkey (@users) {
1.865     raeburn  6974:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6975:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6976:                             if (ref($item) eq 'HASH') {
                   6977:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6978:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6979:                                     return 'ok';
                   6980:                                 }
                   6981:                             }
                   6982:                         }
                   6983:                     } 
1.765     albertel 6984:                 }
                   6985:             }
                   6986:             my %roleshash;
                   6987:             my @courses_and_groups = @courses;
                   6988:             push(@courses_and_groups,@groups); 
                   6989:             if (@courses_and_groups > 0) {
                   6990:                 my (%allgroups,%allroles); 
                   6991:                 my ($start,$end,$role,$sec,$group);
                   6992:                 foreach my $envkey (%env) {
1.1060    raeburn  6993:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6994:                         my $cid = $2.'_'.$3; 
                   6995:                         if ($1 eq 'gr') {
                   6996:                             $group = $4;
                   6997:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6998:                         } else {
                   6999:                             if ($4 eq '') {
                   7000:                                 $sec = 'none';
                   7001:                             } else {
                   7002:                                 $sec = $4;
                   7003:                             }
                   7004:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7005:                         }
1.811     albertel 7006:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7007:                         my $cid = $2.'_'.$3;
                   7008:                         if ($4 eq '') {
                   7009:                             $sec = 'none';
                   7010:                         } else {
                   7011:                             $sec = $4;
                   7012:                         }
                   7013:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7014:                     }
                   7015:                 }
                   7016:                 if (keys(%allroles) == 0) {
                   7017:                     return;
                   7018:                 }
                   7019:                 foreach my $key (@courses_and_groups) {
                   7020:                     my %content = %{$$access_hash{$key}};
                   7021:                     my $cnum = $content{'number'};
                   7022:                     my $cdom = $content{'domain'};
                   7023:                     my $cid = $cdom.'_'.$cnum;
                   7024:                     if (!exists($allroles{$cid})) {
                   7025:                         next;
                   7026:                     }    
                   7027:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7028:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7029:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7030:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7031:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7032:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7033:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7034:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7035:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7036:                                         if (grep/^all$/,@sections) {
                   7037:                                             return 'ok';
                   7038:                                         } else {
                   7039:                                             if (grep/^$sec$/,@sections) {
                   7040:                                                 return 'ok';
                   7041:                                             }
                   7042:                                         }
                   7043:                                     }
                   7044:                                 }
                   7045:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7046:                                     if (grep/^none$/,@groups) {
                   7047:                                         return 'ok';
                   7048:                                     }
                   7049:                                 } else {
                   7050:                                     if (grep/^all$/,@groups) {
                   7051:                                         return 'ok';
                   7052:                                     } 
                   7053:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7054:                                         if (grep/^$group$/,@groups) {
                   7055:                                             return 'ok';
                   7056:                                         }
                   7057:                                     }
                   7058:                                 } 
                   7059:                             }
                   7060:                         }
                   7061:                     }
                   7062:                 }
                   7063:             }
                   7064:             if ($guest) {
                   7065:                 return $guest;
                   7066:             }
                   7067:         }
                   7068:     }
                   7069:     return;
                   7070: }
                   7071: 
                   7072: sub course_group_datechecker {
                   7073:     my ($dates,$now,$status) = @_;
                   7074:     my ($start,$end) = split(/\./,$dates);
                   7075:     if (!$start && !$end) {
                   7076:         return 'ok';
                   7077:     }
                   7078:     if (grep/^active$/,@{$status}) {
                   7079:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7080:             return 'ok';
                   7081:         }
                   7082:     }
                   7083:     if (grep/^previous$/,@{$status}) {
                   7084:         if ($end > $now ) {
                   7085:             return 'ok';
                   7086:         }
                   7087:     }
                   7088:     if (grep/^future$/,@{$status}) {
                   7089:         if ($start > $now) {
                   7090:             return 'ok';
                   7091:         }
                   7092:     }
                   7093:     return; 
                   7094: }
                   7095: 
                   7096: sub parse_portfolio_url {
                   7097:     my ($url) = @_;
                   7098: 
                   7099:     my ($type,$udom,$unum,$group,$file_name);
                   7100:     
1.823     albertel 7101:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7102: 	$type = 1;
                   7103:         $udom = $1;
                   7104:         $unum = $2;
                   7105:         $file_name = $3;
1.823     albertel 7106:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7107: 	$type = 2;
                   7108:         $udom = $1;
                   7109:         $unum = $2;
                   7110:         $group = $3;
                   7111:         $file_name = $3.'/'.$4;
                   7112:     }
                   7113:     if (wantarray) {
                   7114: 	return ($type,$udom,$unum,$file_name,$group);
                   7115:     }
                   7116:     return $type;
                   7117: }
                   7118: 
                   7119: sub is_portfolio_url {
                   7120:     my ($url) = @_;
                   7121:     return scalar(&parse_portfolio_url($url));
                   7122: }
                   7123: 
1.798     raeburn  7124: sub is_portfolio_file {
                   7125:     my ($file) = @_;
1.820     raeburn  7126:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7127:         return 1;
                   7128:     }
                   7129:     return;
                   7130: }
                   7131: 
1.976     raeburn  7132: sub usertools_access {
1.1084    raeburn  7133:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7134:     my ($access,%tools);
                   7135:     if ($context eq '') {
                   7136:         $context = 'tools';
                   7137:     }
                   7138:     if ($context eq 'requestcourses') {
                   7139:         %tools = (
                   7140:                       official   => 1,
                   7141:                       unofficial => 1,
1.1006    raeburn  7142:                       community  => 1,
1.1246    raeburn  7143:                       textbook   => 1,
1.1305    raeburn  7144:                       placement  => 1,
1.985     raeburn  7145:                  );
1.1183    raeburn  7146:     } elsif ($context eq 'requestauthor') {
                   7147:         %tools = (
                   7148:                       requestauthor => 1,
                   7149:                  );
1.985     raeburn  7150:     } else {
                   7151:         %tools = (
                   7152:                       aboutme   => 1,
                   7153:                       blog      => 1,
1.1177    raeburn  7154:                       webdav    => 1,
1.985     raeburn  7155:                       portfolio => 1,
                   7156:                  );
                   7157:     }
1.976     raeburn  7158:     return if (!defined($tools{$tool}));
                   7159: 
1.1242    raeburn  7160:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7161:         $udom = $env{'user.domain'};
                   7162:         $uname = $env{'user.name'};
                   7163:     }
                   7164: 
1.978     raeburn  7165:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7166:         if ($action ne 'reload') {
1.985     raeburn  7167:             if ($context eq 'requestcourses') {
                   7168:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7169:             } elsif ($context eq 'requestauthor') {
                   7170:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7171:             } else {
                   7172:                 return $env{'environment.availabletools.'.$tool};
                   7173:             }
                   7174:         }
1.976     raeburn  7175:     }
                   7176: 
1.1183    raeburn  7177:     my ($toolstatus,$inststatus,$envkey);
                   7178:     if ($context eq 'requestauthor') {
                   7179:         $envkey = $context; 
                   7180:     } else {
                   7181:         $envkey = $context.'.'.$tool;
                   7182:     }
1.976     raeburn  7183: 
1.985     raeburn  7184:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7185:          ($action ne 'reload')) {
1.1183    raeburn  7186:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7187:         $inststatus = $env{'environment.inststatus'};
                   7188:     } else {
1.1084    raeburn  7189:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7190:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7191:             $inststatus = $userenvref->{'inststatus'};
                   7192:         } else {
1.1183    raeburn  7193:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7194:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7195:             $inststatus = $userenv{'inststatus'};
                   7196:         }
1.976     raeburn  7197:     }
                   7198: 
                   7199:     if ($toolstatus ne '') {
                   7200:         if ($toolstatus) {
                   7201:             $access = 1;
                   7202:         } else {
                   7203:             $access = 0;
                   7204:         }
                   7205:         return $access;
                   7206:     }
                   7207: 
1.1084    raeburn  7208:     my ($is_adv,%domdef);
                   7209:     if (ref($is_advref) eq 'HASH') {
                   7210:         $is_adv = $is_advref->{'is_adv'};
                   7211:     } else {
                   7212:         $is_adv = &is_advanced_user($udom,$uname);
                   7213:     }
                   7214:     if (ref($domdefref) eq 'HASH') {
                   7215:         %domdef = %{$domdefref};
                   7216:     } else {
                   7217:         %domdef = &get_domain_defaults($udom);
                   7218:     }
1.976     raeburn  7219:     if (ref($domdef{$tool}) eq 'HASH') {
                   7220:         if ($is_adv) {
                   7221:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7222:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7223:                     $access = 1;
                   7224:                 } else {
                   7225:                     $access = 0;
                   7226:                 }
                   7227:                 return $access;
                   7228:             }
                   7229:         }
                   7230:         if ($inststatus ne '') {
                   7231:             my ($hasaccess,$hasnoaccess);
                   7232:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7233:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7234:                     if ($domdef{$tool}{$affiliation}) {
                   7235:                         $hasaccess = 1;
                   7236:                     } else {
                   7237:                         $hasnoaccess = 1;
                   7238:                     }
                   7239:                 }
                   7240:             }
                   7241:             if ($hasaccess || $hasnoaccess) {
                   7242:                 if ($hasaccess) {
                   7243:                     $access = 1;
                   7244:                 } elsif ($hasnoaccess) {
                   7245:                     $access = 0; 
                   7246:                 }
                   7247:                 return $access;
                   7248:             }
                   7249:         } else {
                   7250:             if ($domdef{$tool}{'default'} ne '') {
                   7251:                 if ($domdef{$tool}{'default'}) {
                   7252:                     $access = 1;
                   7253:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7254:                     $access = 0;
                   7255:                 }
                   7256:                 return $access;
                   7257:             }
                   7258:         }
                   7259:     } else {
1.1177    raeburn  7260:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7261:             $access = 1;
                   7262:         } else {
                   7263:             $access = 0;
                   7264:         }
1.976     raeburn  7265:         return $access;
                   7266:     }
                   7267: }
                   7268: 
1.1050    raeburn  7269: sub is_course_owner {
                   7270:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7271:     if (($udom eq '') || ($uname eq '')) {
                   7272:         $udom = $env{'user.domain'};
                   7273:         $uname = $env{'user.name'};
                   7274:     }
                   7275:     unless (($udom eq '') || ($uname eq '')) {
                   7276:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7277:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7278:                 return 1;
                   7279:             } else {
                   7280:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7281:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7282:                     return 1;
                   7283:                 }
                   7284:             }
                   7285:         }
                   7286:     }
                   7287:     return;
                   7288: }
                   7289: 
1.976     raeburn  7290: sub is_advanced_user {
                   7291:     my ($udom,$uname) = @_;
1.1085    raeburn  7292:     if ($udom ne '' && $uname ne '') {
                   7293:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7294:             if (wantarray) {
                   7295:                 return ($env{'user.adv'},$env{'user.author'});
                   7296:             } else {
                   7297:                 return $env{'user.adv'};
                   7298:             }
1.1085    raeburn  7299:         }
                   7300:     }
1.976     raeburn  7301:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7302:     my %allroles;
1.1128    raeburn  7303:     my ($is_adv,$is_author);
1.976     raeburn  7304:     foreach my $role (keys(%roleshash)) {
                   7305:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7306:         my $area = '/'.$tdomain.'/'.$trest;
                   7307:         if ($sec ne '') {
                   7308:             $area .= '/'.$sec;
                   7309:         }
                   7310:         if (($area ne '') && ($trole ne '')) {
                   7311:             my $spec=$trole.'.'.$area;
                   7312:             if ($trole =~ /^cr\//) {
                   7313:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7314:             } elsif ($trole ne 'gr') {
                   7315:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7316:             }
1.1128    raeburn  7317:             if ($trole eq 'au') {
                   7318:                 $is_author = 1;
                   7319:             }
1.976     raeburn  7320:         }
                   7321:     }
                   7322:     foreach my $role (keys(%allroles)) {
                   7323:         last if ($is_adv);
                   7324:         foreach my $item (split(/:/,$allroles{$role})) {
                   7325:             if ($item ne '') {
                   7326:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7327:                 if ($privilege eq 'adv') {
                   7328:                     $is_adv = 1;
                   7329:                     last;
                   7330:                 }
                   7331:             }
                   7332:         }
                   7333:     }
1.1128    raeburn  7334:     if (wantarray) {
                   7335:         return ($is_adv,$is_author);
                   7336:     }
1.976     raeburn  7337:     return $is_adv;
                   7338: }
1.798     raeburn  7339: 
1.1035    raeburn  7340: sub check_can_request {
1.1036    raeburn  7341:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7342:     my $canreq = 0;
                   7343:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7344:     my @options = ('approval','validate','autolimit');
                   7345:     my $optregex = join('|',@options);
                   7346:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7347:         foreach my $type (@{$types}) {
                   7348:             if (&usertools_access($env{'user.name'},
                   7349:                                   $env{'user.domain'},
                   7350:                                   $type,undef,'requestcourses')) {
                   7351:                 $canreq ++;
1.1036    raeburn  7352:                 if (ref($request_domains) eq 'HASH') {
                   7353:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7354:                 }
1.1035    raeburn  7355:                 if ($dom eq $env{'user.domain'}) {
                   7356:                     $can_request->{$type} = 1;
                   7357:                 }
                   7358:             }
                   7359:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7360:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7361:                 if (@curr > 0) {
1.1036    raeburn  7362:                     foreach my $item (@curr) {
                   7363:                         if (ref($request_domains) eq 'HASH') {
                   7364:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7365:                             if ($otherdom ne '') {
                   7366:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7367:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7368:                                         push(@{$request_domains->{$type}},$otherdom);
                   7369:                                     }
                   7370:                                 } else {
                   7371:                                     push(@{$request_domains->{$type}},$otherdom);
                   7372:                                 }
                   7373:                             }
                   7374:                         }
                   7375:                     }
                   7376:                     unless($dom eq $env{'user.domain'}) {
                   7377:                         $canreq ++;
1.1035    raeburn  7378:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7379:                             $can_request->{$type} = 1;
                   7380:                         }
                   7381:                     }
                   7382:                 }
                   7383:             }
                   7384:         }
                   7385:     }
                   7386:     return $canreq;
                   7387: }
                   7388: 
1.341     www      7389: # ---------------------------------------------- Custom access rule evaluation
                   7390: 
                   7391: sub customaccess {
                   7392:     my ($priv,$uri)=@_;
1.807     albertel 7393:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7394:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7395:     $udom = &LONCAPA::clean_domain($udom);
                   7396:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7397:     my $access=0;
1.800     albertel 7398:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7399: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7400: 	if ($type eq 'user') {
                   7401: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7402: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7403: 		if ($tdom) {
                   7404: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7405: 		}
1.896     albertel 7406: 		if ($tuname) {
                   7407: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7408: 		}
                   7409: 		$access=($effect eq 'allow');
                   7410: 		last;
                   7411: 	    }
                   7412: 	} else {
                   7413: 	    if ($role) {
                   7414: 		if ($role ne $urole) { next; }
                   7415: 	    }
                   7416: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7417: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7418: 		if ($tdom) {
                   7419: 		    if ($tdom ne $udom) { next; }
                   7420: 		}
                   7421: 		if ($tcrs) {
                   7422: 		    if ($tcrs ne $ucrs) { next; }
                   7423: 		}
                   7424: 		if ($tsec) {
                   7425: 		    if ($tsec ne $usec) { next; }
                   7426: 		}
                   7427: 		$access=($effect eq 'allow');
                   7428: 		last;
                   7429: 	    }
                   7430: 	    if ($realm eq '' && $role eq '') {
                   7431: 		$access=($effect eq 'allow');
                   7432: 	    }
1.402     bowersj2 7433: 	}
1.341     www      7434:     }
                   7435:     return $access;
                   7436: }
                   7437: 
1.103     harris41 7438: # ------------------------------------------------- Check for a user privilege
1.12      www      7439: 
                   7440: sub allowed {
1.1281    raeburn  7441:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7442:     my $ver_orguri=$uri;
1.439     www      7443:     $uri=&deversion($uri);
1.152     www      7444:     my $orguri=$uri;
1.52      www      7445:     $uri=&declutter($uri);
1.809     raeburn  7446: 
1.810     raeburn  7447:     if ($priv eq 'evb') {
                   7448: # Evade communication block restrictions for specified role in a course
                   7449:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7450:             return $1;
                   7451:         } else {
                   7452:             return;
                   7453:         }
                   7454:     }
                   7455: 
1.620     albertel 7456:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7457: # Free bre access to adm and meta resources
1.1343    raeburn  7458:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7459: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7460: 	&& ($priv eq 'bre')) {
1.14      www      7461: 	return 'F';
1.159     www      7462:     }
                   7463: 
1.545     banghart 7464: # Free bre access to user's own portfolio contents
1.714     raeburn  7465:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7466:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7467: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7468:         my %setters;
                   7469:         my ($startblock,$endblock) = 
                   7470:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7471:         if ($startblock && $endblock) {
                   7472:             return 'B';
                   7473:         } else {
                   7474:             return 'F';
                   7475:         }
1.545     banghart 7476:     }
                   7477: 
1.762     raeburn  7478: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7479:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7480:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7481:         if (exists($env{'request.course.id'})) {
                   7482:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7483:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7484:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7485:                 my $courseprivid=$env{'request.course.id'};
                   7486:                 $courseprivid=~s/\_/\//;
                   7487:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7488:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7489:                     return $1; 
1.762     raeburn  7490:                 } else {
                   7491:                     if ($env{'request.course.sec'}) {
                   7492:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7493:                     }
                   7494:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7495:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7496:                         return $2;
                   7497:                     }
1.714     raeburn  7498:                 }
                   7499:             }
                   7500:         }
                   7501:     }
                   7502: 
1.159     www      7503: # Free bre to public access
                   7504: 
                   7505:     if ($priv eq 'bre') {
1.238     www      7506:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7507: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7508:            return 'F'; 
                   7509:         }
1.238     www      7510:         if ($copyright eq 'priv') {
                   7511:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7512: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7513: 		return '';
                   7514:             }
                   7515:         }
                   7516:         if ($copyright eq 'domain') {
                   7517:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7518: 	    unless (($env{'user.domain'} eq $1) ||
                   7519:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7520: 		return '';
                   7521:             }
1.262     matthew  7522:         }
1.620     albertel 7523:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7524:             # Library role, so allow browsing of resources in this domain.
                   7525:             return 'F';
1.238     www      7526:         }
1.341     www      7527:         if ($copyright eq 'custom') {
                   7528: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7529:         }
1.14      www      7530:     }
1.264     matthew  7531:     # Domain coordinator is trying to create a course
1.620     albertel 7532:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7533:         # uri is the requested domain in this case.
                   7534:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7535:         # a role of dc for the domain in question.
1.620     albertel 7536:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7537:     }
1.29      www      7538: 
1.52      www      7539:     my $thisallowed='';
                   7540:     my $statecond=0;
                   7541:     my $courseprivid='';
                   7542: 
1.1039    raeburn  7543:     my $ownaccess;
1.1043    raeburn  7544:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7545:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7546:         if ($uri eq '') {
                   7547:             $ownaccess = 1;
                   7548:         } else {
                   7549:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7550:                 my $udom = $env{'user.domain'};
                   7551:                 my $uname = $env{'user.name'};
                   7552:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7553:                     $ownaccess = 1;
1.1040    raeburn  7554:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7555:                     unless ($uri =~ m{\.\./}) {
                   7556:                         $ownaccess = 1;
                   7557:                     }
                   7558:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7559:                     my $now = time;
                   7560:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7561:                         my $adom = $1;
                   7562:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7563:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7564:                                 my ($start,$end) = split('.',$env{$key});
                   7565:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7566:                                     $ownaccess = 1;
                   7567:                                     last;
                   7568:                                 }
                   7569:                             }
                   7570:                         }
                   7571:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7572:                         my $adom = $1;
                   7573:                         my $aname = $2;
1.1042    raeburn  7574:                         foreach my $role ('ca','aa') { 
                   7575:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7576:                                 my ($start,$end) =
                   7577:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7578:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7579:                                     $ownaccess = 1;
                   7580:                                     last;
                   7581:                                 }
1.1039    raeburn  7582:                             }
                   7583:                         }
                   7584:                     }
                   7585:                 }
                   7586:             }
                   7587:         }
                   7588:     }
                   7589: 
1.52      www      7590: # Course
                   7591: 
1.620     albertel 7592:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7593:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7594:             $thisallowed.=$1;
                   7595:         }
1.52      www      7596:     }
1.29      www      7597: 
1.52      www      7598: # Domain
                   7599: 
1.620     albertel 7600:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7601:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7602:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7603:             $thisallowed.=$1;
                   7604:         }
1.12      www      7605:     }
1.52      www      7606: 
1.1141    raeburn  7607: # User who is not author or co-author might still be able to edit
                   7608: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7609:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7610:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7611:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7612:             $thisallowed.=$1;
                   7613:         }
                   7614:     }
                   7615: 
1.52      www      7616: # Course: uri itself is a course
1.66      www      7617:     my $courseuri=$uri;
                   7618:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7619:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7620: 
1.620     albertel 7621:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7622:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7623:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7624:             $thisallowed.=$1;
                   7625:         }
1.12      www      7626:     }
1.29      www      7627: 
1.665     albertel 7628: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7629: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7630:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7631: 	$thisallowed='';
1.671     raeburn  7632:         my ($match)=&is_on_map($uri);
                   7633:         if ($match) {
                   7634:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7635:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7636:                 my $value = $1;
                   7637:                 if ($noblockcheck) {
                   7638:                     $thisallowed.=$value;
1.1162    raeburn  7639:                 } else {
1.1281    raeburn  7640:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7641:                     if (@blockers > 0) {
                   7642:                         $thisallowed = 'B';
                   7643:                     } else {
                   7644:                         $thisallowed.=$value;
                   7645:                     }
1.1162    raeburn  7646:                 }
1.671     raeburn  7647:             }
                   7648:         } else {
1.705     albertel 7649:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7650:             if ($refuri) {
                   7651:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7652:                     $thisallowed='F';
1.671     raeburn  7653:                 } else {
                   7654:                     $refuri=&declutter($refuri);
                   7655:                     my ($match) = &is_on_map($refuri);
                   7656:                     if ($match) {
1.1281    raeburn  7657:                         if ($noblockcheck) {
                   7658:                             $thisallowed='F';
1.1162    raeburn  7659:                         } else {
1.1281    raeburn  7660:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7661:                             if (@blockers > 0) {
                   7662:                                 $thisallowed = 'B';
                   7663:                             } else {
                   7664:                                 $thisallowed='F';
                   7665:                             }
1.1162    raeburn  7666:                         }
1.671     raeburn  7667:                     }
1.669     raeburn  7668:                 }
1.671     raeburn  7669:             }
                   7670:         }
1.314     www      7671:     }
1.492     albertel 7672: 
1.766     albertel 7673:     if ($priv eq 'bre'
                   7674: 	&& $thisallowed ne 'F' 
                   7675: 	&& $thisallowed ne '2'
                   7676: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7677: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7678:     }
1.1250    raeburn  7679: 
1.52      www      7680: # Full access at system, domain or course-wide level? Exit.
1.29      www      7681:     if ($thisallowed=~/F/) {
                   7682: 	return 'F';
                   7683:     }
                   7684: 
1.52      www      7685: # If this is generating or modifying users, exit with special codes
1.29      www      7686: 
1.643     www      7687:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7688: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7689: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7690: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7691: 	    unless ($auname) { return $thisallowed; }
                   7692: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7693: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7694: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7695: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7696: 	}
1.52      www      7697: 	return $thisallowed;
                   7698:     }
                   7699: #
1.103     harris41 7700: # Gathered so far: system, domain and course wide privileges
1.52      www      7701: #
                   7702: # Course: See if uri or referer is an individual resource that is part of 
                   7703: # the course
                   7704: 
1.620     albertel 7705:     if ($env{'request.course.id'}) {
1.232     www      7706: 
1.620     albertel 7707:        $courseprivid=$env{'request.course.id'};
                   7708:        if ($env{'request.course.sec'}) {
                   7709:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7710:        }
                   7711:        $courseprivid=~s/\_/\//;
                   7712:        my $checkreferer=1;
1.232     www      7713:        my ($match,$cond)=&is_on_map($uri);
                   7714:        if ($match) {
                   7715:            $statecond=$cond;
1.620     albertel 7716:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7717:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7718:                my $value = $1;
                   7719:                if ($priv eq 'bre') {
1.1281    raeburn  7720:                    if ($noblockcheck) {
                   7721:                        $thisallowed.=$value;
1.1162    raeburn  7722:                    } else {
1.1281    raeburn  7723:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7724:                        if (@blockers > 0) {
                   7725:                            $thisallowed = 'B';
                   7726:                        } else {
                   7727:                            $thisallowed.=$value;
                   7728:                        }
1.1162    raeburn  7729:                    }
                   7730:                } else {
                   7731:                    $thisallowed.=$value;
                   7732:                }
1.52      www      7733:                $checkreferer=0;
                   7734:            }
1.29      www      7735:        }
1.83      www      7736:        
1.148     www      7737:        if ($checkreferer) {
1.620     albertel 7738: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7739:             unless ($refuri) {
1.800     albertel 7740:                 foreach my $key (keys(%env)) {
                   7741: 		    if ($key=~/^httpref\..*\*/) {
                   7742: 			my $pattern=$key;
1.156     www      7743:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7744:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7745:                         $pattern=~s/\//\\\//g;
1.152     www      7746:                         if ($orguri=~/$pattern/) {
1.800     albertel 7747: 			    $refuri=$env{$key};
1.148     www      7748:                         }
                   7749:                     }
1.191     harris41 7750:                 }
1.148     www      7751:             }
1.232     www      7752: 
1.148     www      7753:          if ($refuri) { 
1.152     www      7754: 	  $refuri=&declutter($refuri);
1.232     www      7755:           my ($match,$cond)=&is_on_map($refuri);
                   7756:             if ($match) {
                   7757:               my $refstatecond=$cond;
1.620     albertel 7758:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7759:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7760:                   my $value = $1;
                   7761:                   if ($priv eq 'bre') {
1.1281    raeburn  7762:                       if ($noblockcheck) {
                   7763:                           $thisallowed.=$value;
1.1162    raeburn  7764:                       } else {
1.1281    raeburn  7765:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7766:                           if (@blockers > 0) {
                   7767:                               $thisallowed = 'B';
                   7768:                           } else {
                   7769:                               $thisallowed.=$value;
                   7770:                           }
1.1162    raeburn  7771:                       }
                   7772:                   } else {
                   7773:                       $thisallowed.=$value;
                   7774:                   }
1.53      www      7775:                   $uri=$refuri;
                   7776:                   $statecond=$refstatecond;
1.52      www      7777:               }
                   7778:           }
1.148     www      7779:         }
1.29      www      7780:        }
1.52      www      7781:    }
1.29      www      7782: 
1.52      www      7783: #
1.103     harris41 7784: # Gathered now: all privileges that could apply, and condition number
1.52      www      7785: # 
                   7786: #
                   7787: # Full or no access?
                   7788: #
1.29      www      7789: 
1.52      www      7790:     if ($thisallowed=~/F/) {
                   7791: 	return 'F';
                   7792:     }
1.29      www      7793: 
1.52      www      7794:     unless ($thisallowed) {
                   7795:         return '';
                   7796:     }
1.29      www      7797: 
1.52      www      7798: # Restrictions exist, deal with them
                   7799: #
                   7800: #   C:according to course preferences
                   7801: #   R:according to resource settings
                   7802: #   L:unless locked
                   7803: #   X:according to user session state
                   7804: #
                   7805: 
                   7806: # Possibly locked functionality, check all courses
1.54      www      7807: # Locks might take effect only after 10 minutes cache expiration for other
                   7808: # courses, and 2 minutes for current course
1.52      www      7809: 
                   7810:     my $envkey;
                   7811:     if ($thisallowed=~/L/) {
1.1000    raeburn  7812:         foreach $envkey (keys(%env)) {
1.54      www      7813:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7814:                my $courseid=$2;
                   7815:                my $roleid=$1.'.'.$2;
1.92      www      7816:                $courseid=~s/^\///;
1.54      www      7817:                my $expiretime=600;
1.620     albertel 7818:                if ($env{'request.role'} eq $roleid) {
1.54      www      7819: 		  $expiretime=120;
                   7820:                }
                   7821: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7822:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7823:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7824: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7825:                }
1.620     albertel 7826:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7827:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7828: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7829:                        &log($env{'user.domain'},$env{'user.name'},
                   7830:                             $env{'user.home'},
1.57      www      7831:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7832:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7833:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7834: 		       return '';
                   7835:                    }
                   7836:                }
1.620     albertel 7837:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7838:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7839: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7840:                        &log($env{'user.domain'},$env{'user.name'},
                   7841:                             $env{'user.home'},
1.57      www      7842:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7843:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7844:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7845: 		       return '';
                   7846:                    }
                   7847:                }
                   7848: 	   }
1.29      www      7849:        }
1.52      www      7850:     }
                   7851:    
                   7852: #
                   7853: # Rest of the restrictions depend on selected course
                   7854: #
                   7855: 
1.620     albertel 7856:     unless ($env{'request.course.id'}) {
1.766     albertel 7857: 	if ($thisallowed eq 'A') {
                   7858: 	    return 'A';
1.814     raeburn  7859:         } elsif ($thisallowed eq 'B') {
                   7860:             return 'B';
1.766     albertel 7861: 	} else {
                   7862: 	    return '1';
                   7863: 	}
1.52      www      7864:     }
1.29      www      7865: 
1.52      www      7866: #
                   7867: # Now user is definitely in a course
                   7868: #
1.53      www      7869: 
                   7870: 
                   7871: # Course preferences
                   7872: 
                   7873:    if ($thisallowed=~/C/) {
1.620     albertel 7874:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7875:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7876:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7877: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  7878: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7879: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7880: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7881: 			$env{'request.course.id'});
                   7882: 	   }
1.237     www      7883:            return '';
                   7884:        }
                   7885: 
1.620     albertel 7886:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7887: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  7888: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7889: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7890: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7891: 			$env{'request.course.id'});
                   7892: 	   }
1.54      www      7893:            return '';
                   7894:        }
1.53      www      7895:    }
                   7896: 
                   7897: # Resource preferences
                   7898: 
                   7899:    if ($thisallowed=~/R/) {
1.620     albertel 7900:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7901:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7902: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7903: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7904: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7905: 	   }
                   7906: 	   return '';
1.54      www      7907:        }
1.53      www      7908:    }
1.30      www      7909: 
1.246     www      7910: # Restricted by state or randomout?
1.30      www      7911: 
1.52      www      7912:    if ($thisallowed=~/X/) {
1.620     albertel 7913:       if ($env{'acc.randomout'}) {
1.579     albertel 7914: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7915:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7916:             return ''; 
                   7917:          }
1.247     www      7918:       }
                   7919:       if (&condval($statecond)) {
1.52      www      7920: 	 return '2';
                   7921:       } else {
                   7922:          return '';
                   7923:       }
                   7924:    }
1.30      www      7925: 
1.766     albertel 7926:     if ($thisallowed eq 'A') {
                   7927: 	return 'A';
1.814     raeburn  7928:     } elsif ($thisallowed eq 'B') {
                   7929:         return 'B';
1.766     albertel 7930:     }
1.52      www      7931:    return 'F';
1.232     www      7932: }
1.1162    raeburn  7933: 
1.1192    raeburn  7934: # ------------------------------------------- Check construction space access
                   7935: 
                   7936: sub constructaccess {
                   7937:     my ($url,$setpriv)=@_;
                   7938: 
                   7939: # We do not allow editing of previous versions of files
                   7940:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7941: 
                   7942: # Get username and domain from URL
                   7943:     my ($ownername,$ownerdomain,$ownerhome);
                   7944: 
                   7945:     ($ownerdomain,$ownername) =
1.1325    raeburn  7946:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  7947: 
                   7948: # The URL does not really point to any authorspace, forget it
                   7949:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7950: 
                   7951: # Now we need to see if the user has access to the authorspace of
                   7952: # $ownername at $ownerdomain
                   7953: 
                   7954:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7955: # Real author for this?
                   7956:        $ownerhome = $env{'user.home'};
                   7957:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7958:           return ($ownername,$ownerdomain,$ownerhome);
                   7959:        }
                   7960:     } else {
                   7961: # Co-author for this?
                   7962:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7963:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7964:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7965:             return ($ownername,$ownerdomain,$ownerhome);
                   7966:         }
1.1312    raeburn  7967:         if ($env{'request.course.id'}) {
                   7968:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   7969:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   7970:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   7971:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   7972:                     return ($ownername,$ownerdomain,$ownerhome);
                   7973:                 }
                   7974:             }
                   7975:         }
1.1192    raeburn  7976:     }
                   7977: 
                   7978: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7979: # we might as well leave
                   7980:    unless ($setpriv) { return ''; }
                   7981: 
                   7982: # Backdoor access?
                   7983:     my $allowed=&allowed('eco',$ownerdomain);
                   7984: # Nope
                   7985:     unless ($allowed) { return ''; }
                   7986: # Looks like we may have access, but could be locked by the owner of the construction space
                   7987:     if ($allowed eq 'U') {
                   7988:         my %blocked=&get('environment',['domcoord.author'],
                   7989:                          $ownerdomain,$ownername);
                   7990: # Is blocked by owner
                   7991:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7992:     }
                   7993:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7994: # Grant temporary access
                   7995:         my $then=$env{'user.login.time'};
1.1209    raeburn  7996:         my $update=$env{'user.update.time'};
1.1192    raeburn  7997:         if (!$update) { $update = $then; }
                   7998:         my $refresh=$env{'user.refresh.time'};
                   7999:         if (!$refresh) { $refresh = $update; }
                   8000:         my $now = time;
                   8001:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8002:                            $now,'ca','constructaccess');
                   8003:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8004:         return($ownername,$ownerdomain,$ownerhome);
                   8005:     }
                   8006: # No business here
                   8007:     return '';
                   8008: }
                   8009: 
1.1282    raeburn  8010: # ----------------------------------------------------------- Content Blocking
                   8011: 
                   8012: {
                   8013: # Caches for faster Course Contents display where content blocking
                   8014: # is in operation (i.e., interval param set) for timed quiz.
                   8015: #
                   8016: # User for whom data are being temporarily cached.
                   8017: my $cacheduser='';
                   8018: # Cached blockers for this user (a hash of blocking items). 
                   8019: my %cachedblockers=();
                   8020: # When the data were last cached.
                   8021: my $cachedlast='';
                   8022: 
                   8023: sub load_all_blockers {
                   8024:     my ($uname,$udom,$blocks)=@_;
                   8025:     if (($uname ne '') && ($udom ne '')) { 
                   8026:         if (($cacheduser eq $uname.':'.$udom) &&
                   8027:             (abs($cachedlast-time)<5)) {
                   8028:             return;
                   8029:         }
                   8030:     }
                   8031:     $cachedlast=time;
                   8032:     $cacheduser=$uname.':'.$udom;
                   8033:     %cachedblockers = &get_commblock_resources($blocks);
                   8034: }
                   8035: 
1.1162    raeburn  8036: sub get_comm_blocks {
                   8037:     my ($cdom,$cnum) = @_;
                   8038:     if ($cdom eq '' || $cnum eq '') {
                   8039:         return unless ($env{'request.course.id'});
                   8040:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8041:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8042:     }
                   8043:     my %commblocks;
                   8044:     my $hashid=$cdom.'_'.$cnum;
                   8045:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8046:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8047:         %commblocks = %{$blocksref};
                   8048:     } else {
                   8049:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8050:         my $cachetime = 600;
                   8051:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8052:     }
                   8053:     return %commblocks;
                   8054: }
                   8055: 
1.1282    raeburn  8056: sub get_commblock_resources {
                   8057:     my ($blocks) = @_;
                   8058:     my %blockers = ();
                   8059:     return %blockers unless ($env{'request.course.id'});
                   8060:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8061:     my %commblocks;
                   8062:     if (ref($blocks) eq 'HASH') {
                   8063:         %commblocks = %{$blocks};
                   8064:     } else {
                   8065:         %commblocks = &get_comm_blocks();
                   8066:     }
1.1282    raeburn  8067:     return %blockers unless (keys(%commblocks) > 0); 
                   8068:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8069:     return %blockers unless (ref($navmap));
1.1162    raeburn  8070:     my $now = time;
                   8071:     foreach my $block (keys(%commblocks)) {
                   8072:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8073:             my ($start,$end) = ($1,$2);
                   8074:             if ($start <= $now && $end >= $now) {
                   8075:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8076:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8077:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8078:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8079:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8080:                             }
                   8081:                         }
                   8082:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8083:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8084:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8085:                             }
                   8086:                         }
                   8087:                     }
                   8088:                 }
                   8089:             }
                   8090:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8091:             my $item = $1;
1.1163    raeburn  8092:             my @to_test;
1.1162    raeburn  8093:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8094:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  8095:                     my @interval;
                   8096:                     my $type = 'map';
                   8097:                     if ($item eq 'course') {
                   8098:                         $type = 'course';
                   8099:                         @interval=&EXT("resource.0.interval");
                   8100:                     } else {
                   8101:                         if ($item =~ /___\d+___/) {
                   8102:                             $type = 'resource';
                   8103:                             @interval=&EXT("resource.0.interval",$item);
                   8104:                             if (ref($navmap)) {                        
                   8105:                                 my $res = $navmap->getBySymb($item); 
                   8106:                                 push(@to_test,$res);
                   8107:                             }
1.1162    raeburn  8108:                         } else {
1.1282    raeburn  8109:                             my $mapsymb = &symbread($item,1);
                   8110:                             if ($mapsymb) {
                   8111:                                 if (ref($navmap)) {
                   8112:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8113:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8114:                                     foreach my $res (@to_test) {
                   8115:                                         my $symb = $res->symb();
                   8116:                                         next if ($symb eq $mapsymb);
                   8117:                                         if ($symb ne '') {
                   8118:                                             @interval=&EXT("resource.0.interval",$symb);
                   8119:                                             if ($interval[1] eq 'map') {
                   8120:                                                 last;
1.1162    raeburn  8121:                                             }
                   8122:                                         }
                   8123:                                     }
                   8124:                                 }
                   8125:                             }
                   8126:                         }
1.1282    raeburn  8127:                     }
1.1310    raeburn  8128:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8129:                         my $timelimit = $1; 
1.1282    raeburn  8130:                         my $first_access;
                   8131:                         if ($type eq 'resource') {
                   8132:                             $first_access=&get_first_access($interval[1],$item);
                   8133:                         } elsif ($type eq 'map') {
                   8134:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8135:                         } else {
                   8136:                             $first_access=&get_first_access($interval[1]);
                   8137:                         }
                   8138:                         if ($first_access) {
1.1292    raeburn  8139:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8140:                             if ($timesup > $now) {
                   8141:                                 my $activeblock;
                   8142:                                 foreach my $res (@to_test) {
1.1283    raeburn  8143:                                     if ($res->answerable()) {
1.1282    raeburn  8144:                                         $activeblock = 1;
                   8145:                                         last;
                   8146:                                     }
                   8147:                                 }
                   8148:                                 if ($activeblock) {
                   8149:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8150:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8151:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8152:                                          }
                   8153:                                     }
                   8154:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8155:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8156:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8157:                                         }
1.1162    raeburn  8158:                                     }
                   8159:                                 }
                   8160:                             }
                   8161:                         }
                   8162:                     }
                   8163:                 }
                   8164:             }
                   8165:         }
                   8166:     }
1.1282    raeburn  8167:     return %blockers;
1.1162    raeburn  8168: }
                   8169: 
1.1282    raeburn  8170: sub has_comm_blocking {
                   8171:     my ($priv,$symb,$uri,$blocks) = @_;
                   8172:     my @blockers;
                   8173:     return unless ($env{'request.course.id'});
                   8174:     return unless ($priv eq 'bre');
                   8175:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8176:     return if ($env{'request.state'} eq 'construct');
                   8177:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8178:     return unless (keys(%cachedblockers) > 0);
                   8179:     my (%possibles,@symbs);
                   8180:     if (!$symb) {
                   8181:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8182:     }
1.1282    raeburn  8183:     if ($symb) {
                   8184:         @symbs = ($symb);
                   8185:     } elsif (keys(%possibles)) { 
                   8186:         @symbs = keys(%possibles);
                   8187:     }
                   8188:     my $noblock;
                   8189:     foreach my $symb (@symbs) {
                   8190:         last if ($noblock);
                   8191:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8192:         foreach my $block (keys(%cachedblockers)) {
                   8193:             if ($block =~ /^firstaccess____(.+)$/) {
                   8194:                 my $item = $1;
                   8195:                 if (($item eq $map) || ($item eq $symb)) {
                   8196:                     $noblock = 1;
                   8197:                     last;
                   8198:                 }
                   8199:             }
                   8200:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8201:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8202:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8203:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8204:                             push(@blockers,$block);
                   8205:                         }
                   8206:                     }
                   8207:                 }
1.1162    raeburn  8208:             }
1.1282    raeburn  8209:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8210:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8211:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8212:                         push(@blockers,$block);
                   8213:                     }
                   8214:                 }
1.1162    raeburn  8215:             }
                   8216:         }
                   8217:     }
1.1282    raeburn  8218:     return if ($noblock);
                   8219:     return @blockers;
                   8220: }
1.1162    raeburn  8221: }
                   8222: 
1.1282    raeburn  8223: # -------------------------------- Deversion and split uri into path an filename   
                   8224: 
1.1133    foxr     8225: #
1.1282    raeburn  8226: #   Removes the version from a URI and
1.1133    foxr     8227: #   splits it in to its filename and path to the filename.
                   8228: #   Seems like File::Basename could have done this more clearly.
                   8229: #   Parameters:
                   8230: #      $uri   - input URI
                   8231: #   Returns:
                   8232: #     Two element list consisting of 
                   8233: #     $pathname  - the URI up to and excluding the trailing /
                   8234: #     $filename  - The part of the URI following the last /
                   8235: #  NOTE:
                   8236: #    Another realization of this is simply:
                   8237: #    use File::Basename;
                   8238: #    ...
                   8239: #    $uri = shift;
                   8240: #    $filename = basename($uri);
                   8241: #    $path     = dirname($uri);
                   8242: #    return ($filename, $path);
                   8243: #
                   8244: #     The implementation below is probably faster however.
                   8245: #
1.710     albertel 8246: sub split_uri_for_cond {
                   8247:     my $uri=&deversion(&declutter(shift));
                   8248:     my @uriparts=split(/\//,$uri);
                   8249:     my $filename=pop(@uriparts);
                   8250:     my $pathname=join('/',@uriparts);
                   8251:     return ($pathname,$filename);
                   8252: }
1.232     www      8253: # --------------------------------------------------- Is a resource on the map?
                   8254: 
                   8255: sub is_on_map {
1.710     albertel 8256:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8257:     #Trying to find the conditional for the file
1.620     albertel 8258:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8259: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8260:     if ($match) {
1.289     bowersj2 8261: 	return (1,$1);
                   8262:     } else {
1.434     www      8263: 	return (0,0);
1.289     bowersj2 8264:     }
1.12      www      8265: }
                   8266: 
1.427     www      8267: # --------------------------------------------------------- Get symb from alias
                   8268: 
                   8269: sub get_symb_from_alias {
                   8270:     my $symb=shift;
                   8271:     my ($map,$resid,$url)=&decode_symb($symb);
                   8272: # Already is a symb
                   8273:     if ($url) { return $symb; }
                   8274: # Must be an alias
                   8275:     my $aliassymb='';
                   8276:     my %bighash;
1.620     albertel 8277:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8278:                             &GDBM_READER(),0640)) {
                   8279:         my $rid=$bighash{'mapalias_'.$symb};
                   8280: 	if ($rid) {
                   8281: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8282: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8283: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8284: 	}
                   8285:         untie %bighash;
                   8286:     }
                   8287:     return $aliassymb;
                   8288: }
                   8289: 
1.12      www      8290: # ----------------------------------------------------------------- Define Role
                   8291: 
                   8292: sub definerole {
                   8293:   if (allowed('mcr','/')) {
1.1326    raeburn  8294:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8295:     foreach my $role (split(':',$sysrole)) {
                   8296: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8297:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8298:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8299: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8300:                return "refused:s:$crole&$cqual"; 
                   8301:             }
                   8302:         }
1.191     harris41 8303:     }
1.800     albertel 8304:     foreach my $role (split(':',$domrole)) {
                   8305: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8306:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8307:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8308: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8309:                return "refused:d:$crole&$cqual"; 
                   8310:             }
                   8311:         }
1.191     harris41 8312:     }
1.800     albertel 8313:     foreach my $role (split(':',$courole)) {
                   8314: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8315:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8316:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8317: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8318:                return "refused:c:$crole&$cqual"; 
                   8319:             }
                   8320:         }
1.191     harris41 8321:     }
1.1326    raeburn  8322:     my $uhome;
                   8323:     if (($uname ne '') && ($udom ne '')) {
                   8324:         $uhome = &homeserver($uname,$udom);
                   8325:         return $uhome if ($uhome eq 'no_host');
                   8326:     } else {
                   8327:         $uname = $env{'user.name'};
                   8328:         $udom = $env{'user.domain'};
                   8329:         $uhome = $env{'user.home'};
                   8330:     }
1.620     albertel 8331:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  8332:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8333:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  8334:     return reply($command,$uhome);
1.12      www      8335:   } else {
                   8336:     return 'refused';
                   8337:   }
1.105     harris41 8338: }
                   8339: 
                   8340: # ---------------- Make a metadata query against the network of library servers
                   8341: 
                   8342: sub metadata_query {
1.1237    raeburn  8343:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8344:     my %rhash;
1.845     albertel 8345:     my %libserv = &all_library();
1.244     matthew  8346:     my @server_list = (defined($server_array) ? @$server_array
                   8347:                                               : keys(%libserv) );
                   8348:     for my $server (@server_list) {
1.1237    raeburn  8349:         my $domains = ''; 
                   8350:         if (ref($domains_hash) eq 'HASH') {
                   8351:             $domains = $domains_hash->{$server}; 
                   8352:         }
1.118     harris41 8353: 	unless ($custom or $customshow) {
1.1237    raeburn  8354: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8355: 	    $rhash{$server}=$reply;
                   8356: 	}
                   8357: 	else {
                   8358: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  8359: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8360: 			     $server);
                   8361: 	    $rhash{$server}=$reply;
                   8362: 	}
1.112     harris41 8363:     }
1.118     harris41 8364:     return \%rhash;
1.240     www      8365: }
                   8366: 
                   8367: # ----------------------------------------- Send log queries and wait for reply
                   8368: 
                   8369: sub log_query {
                   8370:     my ($uname,$udom,$query,%filters)=@_;
                   8371:     my $uhome=&homeserver($uname,$udom);
                   8372:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8373:     my $uhost=&hostname($uhome);
1.800     albertel 8374:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8375:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8376:                        $uhome);
1.479     albertel 8377:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8378:     return get_query_reply($queryid);
                   8379: }
                   8380: 
1.818     raeburn  8381: # -------------------------- Update MySQL table for portfolio file
                   8382: 
                   8383: sub update_portfolio_table {
1.821     raeburn  8384:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8385:     if ($group ne '') {
                   8386:         $file_name =~s /^\Q$group\E//;
                   8387:     }
1.818     raeburn  8388:     my $homeserver = &homeserver($uname,$udom);
                   8389:     my $queryid=
1.821     raeburn  8390:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8391:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8392:     my $reply = &get_query_reply($queryid);
                   8393:     return $reply;
                   8394: }
                   8395: 
1.899     raeburn  8396: # -------------------------- Update MySQL allusers table
                   8397: 
                   8398: sub update_allusers_table {
                   8399:     my ($uname,$udom,$names) = @_;
                   8400:     my $homeserver = &homeserver($uname,$udom);
                   8401:     my $queryid=
                   8402:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8403:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8404:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8405:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8406:                'generation='.&escape($names->{'generation'}).'%%'.
                   8407:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8408:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8409:     return;
1.899     raeburn  8410: }
                   8411: 
1.508     raeburn  8412: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8413: 
                   8414: sub fetch_enrollment_query {
1.511     raeburn  8415:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  8416:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8417:     my $maxtries = 1;
1.508     raeburn  8418:     if ($context eq 'automated') {
                   8419:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  8420:         $sleep = 2;
                   8421:         $loopmax = 100;
1.547     raeburn  8422:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8423:     } else {
                   8424:         $homeserver = &homeserver($cnum,$dom);
                   8425:     }
1.838     albertel 8426:     my $host=&hostname($homeserver);
1.506     raeburn  8427:     my $cmd = '';
1.1000    raeburn  8428:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8429:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8430:     }
                   8431:     $cmd =~ s/%%$//;
                   8432:     $cmd = &escape($cmd);
                   8433:     my $query = 'fetchenrollment';
1.620     albertel 8434:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8435:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8436:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8437:         return 'error: '.$queryid;
                   8438:     }
1.1317    raeburn  8439:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8440:     my $tries = 1;
                   8441:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  8442:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8443:         $tries ++;
                   8444:     }
1.526     raeburn  8445:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8446:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8447:     } else {
1.901     albertel 8448:         my @responses = split(/:/,$reply);
1.1322    raeburn  8449:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8450:             foreach my $line (@responses) {
                   8451:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8452:                 $$replyref{$key} = $value;
                   8453:             }
                   8454:         } else {
1.1117    foxr     8455:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8456:             foreach my $line (@responses) {
                   8457:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8458:                 $$replyref{$key} = $value;
                   8459:                 if ($value > 0) {
1.800     albertel 8460:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8461:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8462:                         my $destname = $pathname.'/'.$filename;
                   8463:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8464:                         if ($xml_classlist =~ /^error/) {
                   8465:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8466:                         } else {
1.1359    raeburn  8467:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8468:                                 print FILE &unescape($xml_classlist);
                   8469:                                 close(FILE);
1.526     raeburn  8470:                             } else {
                   8471:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8472:                             }
                   8473:                         }
                   8474:                     }
                   8475:                 }
                   8476:             }
                   8477:         }
                   8478:         return 'ok';
                   8479:     }
                   8480:     return 'error';
                   8481: }
                   8482: 
1.242     www      8483: sub get_query_reply {
1.1317    raeburn  8484:     my ($queryid,$sleep,$loopmax) = @_;;
                   8485:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8486:         $sleep = 0.2;
                   8487:     }
                   8488:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8489:         $loopmax = 100;
                   8490:     }
1.1117    foxr     8491:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8492:     my $reply='';
1.1317    raeburn  8493:     for (1..$loopmax) {
                   8494: 	sleep($sleep);
1.240     www      8495:         if (-e $replyfile.'.end') {
1.1359    raeburn  8496: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8497: 		$reply = join('',<$fh>);
                   8498: 		close($fh);
1.240     www      8499: 	   } else { return 'error: reply_file_error'; }
1.242     www      8500:            return &unescape($reply);
                   8501: 	}
1.240     www      8502:     }
1.242     www      8503:     return 'timeout:'.$queryid;
1.240     www      8504: }
                   8505: 
                   8506: sub courselog_query {
1.241     www      8507: #
                   8508: # possible filters:
                   8509: # url: url or symb
                   8510: # username
                   8511: # domain
                   8512: # action: view, submit, grade
                   8513: # start: timestamp
                   8514: # end: timestamp
                   8515: #
1.240     www      8516:     my (%filters)=@_;
1.620     albertel 8517:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8518:     if ($filters{'url'}) {
                   8519: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8520:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8521:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8522:     }
1.620     albertel 8523:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8524:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8525:     return &log_query($cname,$cdom,'courselog',%filters);
                   8526: }
                   8527: 
                   8528: sub userlog_query {
1.858     raeburn  8529: #
                   8530: # possible filters:
                   8531: # action: log check role
                   8532: # start: timestamp
                   8533: # end: timestamp
                   8534: #
1.240     www      8535:     my ($uname,$udom,%filters)=@_;
                   8536:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8537: }
                   8538: 
1.506     raeburn  8539: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8540: 
                   8541: sub auto_run {
1.508     raeburn  8542:     my ($cnum,$cdom) = @_;
1.876     raeburn  8543:     my $response = 0;
                   8544:     my $settings;
                   8545:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8546:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8547:         $settings = $domconfig{'autoenroll'};
                   8548:         if ($settings->{'run'} eq '1') {
                   8549:             $response = 1;
                   8550:         }
                   8551:     } else {
1.934     raeburn  8552:         my $homeserver;
                   8553:         if (&is_course($cdom,$cnum)) {
                   8554:             $homeserver = &homeserver($cnum,$cdom);
                   8555:         } else {
                   8556:             $homeserver = &domain($cdom,'primary');
                   8557:         }
                   8558:         if ($homeserver ne 'no_host') {
                   8559:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8560:         }
1.876     raeburn  8561:     }
1.506     raeburn  8562:     return $response;
                   8563: }
1.776     albertel 8564: 
1.506     raeburn  8565: sub auto_get_sections {
1.508     raeburn  8566:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8567:     my $homeserver;
                   8568:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8569:         $homeserver = &homeserver($cnum,$cdom);
                   8570:     }
                   8571:     if (!defined($homeserver)) { 
                   8572:         if ($cdom =~ /^$match_domain$/) {
                   8573:             $homeserver = &domain($cdom,'primary');
                   8574:         }
                   8575:     }
                   8576:     my @secs;
                   8577:     if (defined($homeserver)) {
                   8578:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8579:         unless ($response eq 'refused') {
                   8580:             @secs = split(/:/,$response);
                   8581:         }
1.506     raeburn  8582:     }
                   8583:     return @secs;
                   8584: }
1.776     albertel 8585: 
1.506     raeburn  8586: sub auto_new_course {
1.1099    raeburn  8587:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8588:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8589:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8590:     return $response;
                   8591: }
1.776     albertel 8592: 
1.506     raeburn  8593: sub auto_validate_courseID {
1.508     raeburn  8594:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8595:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8596:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8597:     return $response;
                   8598: }
1.776     albertel 8599: 
1.1007    raeburn  8600: sub auto_validate_instcode {
1.1020    raeburn  8601:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8602:     my ($homeserver,$response);
                   8603:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8604:         $homeserver = &homeserver($cnum,$cdom);
                   8605:     }
                   8606:     if (!defined($homeserver)) {
                   8607:         if ($cdom =~ /^$match_domain$/) {
                   8608:             $homeserver = &domain($cdom,'primary');
                   8609:         }
                   8610:     }
1.1065    raeburn  8611:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8612:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8613:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8614:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8615: }
                   8616: 
1.506     raeburn  8617: sub auto_create_password {
1.873     raeburn  8618:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8619:     my ($homeserver,$response);
1.506     raeburn  8620:     my $create_passwd = 0;
                   8621:     my $authchk = '';
1.873     raeburn  8622:     if ($udom =~ /^$match_domain$/) {
                   8623:         $homeserver = &domain($udom,'primary');
                   8624:     }
                   8625:     if ($homeserver eq '') {
                   8626:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8627:             $homeserver = &homeserver($cnum,$cdom);
                   8628:         }
                   8629:     }
                   8630:     if ($homeserver eq '') {
                   8631:         $authchk = 'nodomain';
1.506     raeburn  8632:     } else {
1.873     raeburn  8633:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8634:         if ($response eq 'refused') {
                   8635:             $authchk = 'refused';
                   8636:         } else {
1.901     albertel 8637:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8638:         }
1.506     raeburn  8639:     }
                   8640:     return ($authparam,$create_passwd,$authchk);
                   8641: }
                   8642: 
1.706     raeburn  8643: sub auto_photo_permission {
                   8644:     my ($cnum,$cdom,$students) = @_;
                   8645:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8646:     my ($outcome,$perm_reqd,$conditions) = 
                   8647: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8648:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8649: 	return (undef,undef);
                   8650:     }
1.706     raeburn  8651:     return ($outcome,$perm_reqd,$conditions);
                   8652: }
                   8653: 
                   8654: sub auto_checkphotos {
                   8655:     my ($uname,$udom,$pid) = @_;
                   8656:     my $homeserver = &homeserver($uname,$udom);
                   8657:     my ($result,$resulttype);
                   8658:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8659: 				   &escape($uname).':'.&escape($pid),
                   8660: 				   $homeserver));
1.709     albertel 8661:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8662: 	return (undef,undef);
                   8663:     }
1.706     raeburn  8664:     if ($outcome) {
                   8665:         ($result,$resulttype) = split(/:/,$outcome);
                   8666:     } 
                   8667:     return ($result,$resulttype);
                   8668: }
                   8669: 
                   8670: sub auto_photochoice {
                   8671:     my ($cnum,$cdom) = @_;
                   8672:     my $homeserver = &homeserver($cnum,$cdom);
                   8673:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8674: 						       &escape($cdom),
                   8675: 						       $homeserver)));
1.709     albertel 8676:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8677: 	return (undef,undef);
                   8678:     }
1.706     raeburn  8679:     return ($update,$comment);
                   8680: }
                   8681: 
                   8682: sub auto_photoupdate {
                   8683:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8684:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8685:     my $host=&hostname($homeserver);
1.706     raeburn  8686:     my $cmd = '';
                   8687:     my $maxtries = 1;
1.800     albertel 8688:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8689:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8690:     }
                   8691:     $cmd =~ s/%%$//;
                   8692:     $cmd = &escape($cmd);
                   8693:     my $query = 'institutionalphotos';
                   8694:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8695:     unless ($queryid=~/^\Q$host\E\_/) {
                   8696:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8697:         return 'error: '.$queryid;
                   8698:     }
                   8699:     my $reply = &get_query_reply($queryid);
                   8700:     my $tries = 1;
                   8701:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8702:         $reply = &get_query_reply($queryid);
                   8703:         $tries ++;
                   8704:     }
                   8705:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8706:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8707:     } else {
                   8708:         my @responses = split(/:/,$reply);
                   8709:         my $outcome = shift(@responses); 
                   8710:         foreach my $item (@responses) {
                   8711:             my ($key,$value) = split(/=/,$item);
                   8712:             $$photo{$key} = $value;
                   8713:         }
                   8714:         return $outcome;
                   8715:     }
                   8716:     return 'error';
                   8717: }
                   8718: 
1.521     raeburn  8719: sub auto_instcode_format {
1.793     albertel 8720:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8721: 	$cat_order) = @_;
1.521     raeburn  8722:     my $courses = '';
1.772     raeburn  8723:     my @homeservers;
1.521     raeburn  8724:     if ($caller eq 'global') {
1.841     albertel 8725: 	my %servers = &get_servers($codedom,'library');
                   8726: 	foreach my $tryserver (keys(%servers)) {
                   8727: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8728: 		push(@homeservers,$tryserver);
                   8729: 	    }
1.584     raeburn  8730:         }
1.1022    raeburn  8731:     } elsif ($caller eq 'requests') {
                   8732:         if ($codedom =~ /^$match_domain$/) {
                   8733:             my $chome = &domain($codedom,'primary');
                   8734:             unless ($chome eq 'no_host') {
                   8735:                 push(@homeservers,$chome);
                   8736:             }
                   8737:         }
1.521     raeburn  8738:     } else {
1.772     raeburn  8739:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8740:     }
1.793     albertel 8741:     foreach my $code (keys(%{$instcodes})) {
                   8742:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8743:     }
                   8744:     chop($courses);
1.772     raeburn  8745:     my $ok_response = 0;
                   8746:     my $response;
                   8747:     while (@homeservers > 0 && $ok_response == 0) {
                   8748:         my $server = shift(@homeservers); 
                   8749:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8750:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8751:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8752: 		split(/:/,$response);
1.772     raeburn  8753:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8754:             push(@{$codetitles},&str2array($codetitles_str));
                   8755:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8756:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8757:             $ok_response = 1;
                   8758:         }
                   8759:     }
                   8760:     if ($ok_response) {
1.521     raeburn  8761:         return 'ok';
1.772     raeburn  8762:     } else {
                   8763:         return $response;
1.521     raeburn  8764:     }
                   8765: }
                   8766: 
1.792     raeburn  8767: sub auto_instcode_defaults {
                   8768:     my ($domain,$returnhash,$code_order) = @_;
                   8769:     my @homeservers;
1.841     albertel 8770: 
                   8771:     my %servers = &get_servers($domain,'library');
                   8772:     foreach my $tryserver (keys(%servers)) {
                   8773: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8774: 	    push(@homeservers,$tryserver);
                   8775: 	}
1.792     raeburn  8776:     }
1.841     albertel 8777: 
1.792     raeburn  8778:     my $response;
1.841     albertel 8779:     foreach my $server (@homeservers) {
1.792     raeburn  8780:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8781:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8782: 	
                   8783: 	foreach my $pair (split(/\&/,$response)) {
                   8784: 	    my ($name,$value)=split(/\=/,$pair);
                   8785: 	    if ($name eq 'code_order') {
                   8786: 		@{$code_order} = split(/\&/,&unescape($value));
                   8787: 	    } else {
                   8788: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8789: 	    }
                   8790: 	}
                   8791: 	return 'ok';
1.792     raeburn  8792:     }
1.841     albertel 8793: 
                   8794:     return $response;
1.1003    raeburn  8795: }
                   8796: 
                   8797: sub auto_possible_instcodes {
1.1007    raeburn  8798:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8799:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8800:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8801:         return;
                   8802:     }
1.1003    raeburn  8803:     my (@homeservers,$uhome);
                   8804:     if (defined(&domain($domain,'primary'))) {
                   8805:         $uhome=&domain($domain,'primary');
                   8806:         push(@homeservers,&domain($domain,'primary'));
                   8807:     } else {
                   8808:         my %servers = &get_servers($domain,'library');
                   8809:         foreach my $tryserver (keys(%servers)) {
                   8810:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8811:                 push(@homeservers,$tryserver);
                   8812:             }
                   8813:         }
                   8814:     }
                   8815:     my $response;
                   8816:     foreach my $server (@homeservers) {
                   8817:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8818:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8819:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8820:             split(':',$response);
                   8821:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8822:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8823:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8824:             my ($name,$value)=split('=',$item);
                   8825:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8826:         }
                   8827:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8828:             my ($name,$value)=split('=',$item);
                   8829:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8830:         }
                   8831:         return 'ok';
                   8832:     }
                   8833:     return $response;
                   8834: }
1.792     raeburn  8835: 
1.1010    raeburn  8836: sub auto_courserequest_checks {
                   8837:     my ($dom) = @_;
1.1020    raeburn  8838:     my ($homeserver,%validations);
                   8839:     if ($dom =~ /^$match_domain$/) {
                   8840:         $homeserver = &domain($dom,'primary');
                   8841:     }
                   8842:     unless ($homeserver eq 'no_host') {
                   8843:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8844:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8845:             my @items = split(/&/,$response);
                   8846:             foreach my $item (@items) {
                   8847:                 my ($key,$value) = split('=',$item);
                   8848:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8849:             }
                   8850:         }
                   8851:     }
1.1010    raeburn  8852:     return %validations; 
                   8853: }
                   8854: 
1.1020    raeburn  8855: sub auto_courserequest_validation {
1.1255    raeburn  8856:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8857:     my ($homeserver,$response);
                   8858:     if ($dom =~ /^$match_domain$/) {
                   8859:         $homeserver = &domain($dom,'primary');
                   8860:     }
1.1255    raeburn  8861:     unless ($homeserver eq 'no_host') {
                   8862:         my $customdata;
                   8863:         if (ref($custominfo) eq 'HASH') {
                   8864:             $customdata = &freeze_escape($custominfo);
                   8865:         }
1.1020    raeburn  8866:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8867:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8868:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8869:                                     $customdata,$homeserver));
1.1020    raeburn  8870:     }
                   8871:     return $response;
                   8872: }
                   8873: 
1.777     albertel 8874: sub auto_validate_class_sec {
1.918     raeburn  8875:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8876:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8877:     my $ownerlist;
                   8878:     if (ref($owners) eq 'ARRAY') {
                   8879:         $ownerlist = join(',',@{$owners});
                   8880:     } else {
                   8881:         $ownerlist = $owners;
                   8882:     }
1.773     raeburn  8883:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8884:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8885:     return $response;
                   8886: }
                   8887: 
1.1248    raeburn  8888: sub auto_crsreq_update {
                   8889:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8890:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8891:     my ($homeserver,%crsreqresponse);
                   8892:     if ($cdom =~ /^$match_domain$/) {
                   8893:         $homeserver = &domain($cdom,'primary');
                   8894:     }
                   8895:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8896:         my $info;
                   8897:         if (ref($inbound) eq 'HASH') {
                   8898:             $info = &freeze_escape($inbound);
                   8899:         }
                   8900:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8901:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8902:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8903:                             &escape($title).':'.&escape($code).':'.
                   8904:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8905:                             $homeserver);
1.1248    raeburn  8906:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8907:             my @items = split(/&/,$response);
                   8908:             foreach my $item (@items) {
                   8909:                 my ($key,$value) = split('=',$item);
                   8910:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8911:             }
                   8912:         }
                   8913:     }
                   8914:     return \%crsreqresponse;
                   8915: }
                   8916: 
1.1305    raeburn  8917: sub auto_export_grades {
1.1309    raeburn  8918:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8919:     my ($homeserver,%exportresponse);
                   8920:     if ($cdom =~ /^$match_domain$/) {
                   8921:         $homeserver = &domain($cdom,'primary');
                   8922:     }
                   8923:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8924:         my $info;
                   8925:         if (ref($inforef) eq 'HASH') {
                   8926:             $info = &freeze_escape($inforef);
                   8927:         }
                   8928:         if (ref($gradesref) eq 'HASH') {
                   8929:             my $grades = &freeze_escape($gradesref);
                   8930:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8931:                                 $info.':'.$grades,$homeserver);
                   8932:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8933:                 my @items = split(/&/,$response);
                   8934:                 foreach my $item (@items) {
                   8935:                     my ($key,$value) = split('=',$item);
                   8936:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8937:                 }
                   8938:             }
                   8939:         }
                   8940:     }
                   8941:     return \%exportresponse;
1.1305    raeburn  8942: }
                   8943: 
1.1287    raeburn  8944: sub check_instcode_cloning {
                   8945:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8946:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8947:         return;
                   8948:     }
                   8949:     my $canclone;
                   8950:     if (@{$code_order} > 0) {
                   8951:         my $instcoderegexp ='^';
                   8952:         my @clonecodes = split(/\&/,$cloner);
                   8953:         foreach my $item (@{$code_order}) {
                   8954:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8955:                 foreach my $pair (@clonecodes) {
                   8956:                     my ($key,$val) = split(/\=/,$pair,2);
                   8957:                     $val = &unescape($val);
                   8958:                     if ($key eq $item) {
                   8959:                         $instcoderegexp .= '('.$val.')';
                   8960:                         last;
                   8961:                     }
                   8962:                 }
                   8963:             } else {
                   8964:                 $instcoderegexp .= $codedefaults->{$item};
                   8965:             }
                   8966:         }
                   8967:         $instcoderegexp .= '$';
                   8968:         my (@from,@to);
                   8969:         eval {
                   8970:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8971:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8972:         };
                   8973:         if ((@from > 0) && (@to > 0)) {
                   8974:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8975:             if (!@diffs) {
                   8976:                 $canclone = 1;
                   8977:             }
                   8978:         }
                   8979:     }
                   8980:     return $canclone;
                   8981: }
                   8982: 
                   8983: sub default_instcode_cloning {
                   8984:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8985:     my (%codedefaults,@code_order,$canclone);
                   8986:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8987:         %codedefaults = %{$codedefaultsref};
                   8988:         @code_order = @{$codeorderref};
                   8989:     } elsif ($clonedom) {
                   8990:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8991:     }
                   8992:     if (($domdefclone) && (@code_order)) {
                   8993:         my @clonecodes = split(/\+/,$domdefclone);
                   8994:         my $instcoderegexp ='^';
                   8995:         foreach my $item (@code_order) {
                   8996:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8997:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8998:             } else {
                   8999:                 $instcoderegexp .= $codedefaults{$item};
                   9000:             }
                   9001:         }
                   9002:         $instcoderegexp .= '$';
                   9003:         my (@from,@to);
                   9004:         eval {
                   9005:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9006:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9007:         };
                   9008:         if ((@from > 0) && (@to > 0)) {
                   9009:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9010:             if (!@diffs) {
                   9011:                 $canclone = 1;
                   9012:             }
                   9013:         }
                   9014:     }
                   9015:     return $canclone;
                   9016: }
                   9017: 
1.679     raeburn  9018: # ------------------------------------------------------- Course Group routines
                   9019: 
                   9020: sub get_coursegroups {
1.809     raeburn  9021:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9022:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9023: }
                   9024: 
1.679     raeburn  9025: sub modify_coursegroup {
                   9026:     my ($cdom,$cnum,$groupsettings) = @_;
                   9027:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9028: }
                   9029: 
1.809     raeburn  9030: sub toggle_coursegroup_status {
                   9031:     my ($cdom,$cnum,$group,$action) = @_;
                   9032:     my ($from_namespace,$to_namespace);
                   9033:     if ($action eq 'delete') {
                   9034:         $from_namespace = 'coursegroups';
                   9035:         $to_namespace = 'deleted_groups';
                   9036:     } else {
                   9037:         $from_namespace = 'deleted_groups';
                   9038:         $to_namespace = 'coursegroups';
                   9039:     }
                   9040:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9041:     if (my $tmp = &error(%curr_group)) {
                   9042:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9043:         return ('read error',$tmp);
                   9044:     } else {
                   9045:         my %savedsettings = %curr_group; 
1.809     raeburn  9046:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9047:         my $deloutcome;
                   9048:         if ($result eq 'ok') {
1.809     raeburn  9049:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9050:         } else {
                   9051:             return ('write error',$result);
                   9052:         }
                   9053:         if ($deloutcome eq 'ok') {
                   9054:             return 'ok';
                   9055:         } else {
                   9056:             return ('delete error',$deloutcome);
                   9057:         }
                   9058:     }
                   9059: }
                   9060: 
1.679     raeburn  9061: sub modify_group_roles {
1.957     raeburn  9062:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9063:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9064:     my $role = 'gr/'.&escape($userprivs);
                   9065:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9066:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9067:     if ($result eq 'ok') {
                   9068:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9069:     }
1.679     raeburn  9070:     return $result;
                   9071: }
                   9072: 
                   9073: sub modify_coursegroup_membership {
                   9074:     my ($cdom,$cnum,$membership) = @_;
                   9075:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9076:     return $result;
                   9077: }
                   9078: 
1.682     raeburn  9079: sub get_active_groups {
                   9080:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9081:     my $now = time;
                   9082:     my %groups = ();
                   9083:     foreach my $key (keys(%env)) {
1.811     albertel 9084:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9085:             my ($start,$end) = split(/\./,$env{$key});
                   9086:             if (($end!=0) && ($end<$now)) { next; }
                   9087:             if (($start!=0) && ($start>$now)) { next; }
                   9088:             if ($1 eq $cdom && $2 eq $cnum) {
                   9089:                 $groups{$3} = $env{$key} ;
                   9090:             }
                   9091:         }
                   9092:     }
                   9093:     return %groups;
                   9094: }
                   9095: 
1.683     raeburn  9096: sub get_group_membership {
                   9097:     my ($cdom,$cnum,$group) = @_;
                   9098:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9099: }
                   9100: 
                   9101: sub get_users_groups {
                   9102:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9103:     my @usersgroups;
1.683     raeburn  9104:     my $cachetime=1800;
                   9105: 
                   9106:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9107:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9108:     if (defined($cached)) {
1.734     albertel 9109:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9110:     } else {  
                   9111:         $grouplist = '';
1.816     raeburn  9112:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9113:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9114:         my $access_end = $env{'course.'.$courseid.
                   9115:                               '.default_enrollment_end_date'};
                   9116:         my $now = time;
                   9117:         foreach my $key (keys(%roleshash)) {
                   9118:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9119:                 my $group = $1;
                   9120:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9121:                     my $start = $2;
                   9122:                     my $end = $1;
                   9123:                     if ($start == -1) { next; } # deleted from group
                   9124:                     if (($start!=0) && ($start>$now)) { next; }
                   9125:                     if (($end!=0) && ($end<$now)) {
                   9126:                         if ($access_end && $access_end < $now) {
                   9127:                             if ($access_end - $end < 86400) {
                   9128:                                 push(@usersgroups,$group);
1.733     raeburn  9129:                             }
                   9130:                         }
1.817     raeburn  9131:                         next;
1.733     raeburn  9132:                     }
1.817     raeburn  9133:                     push(@usersgroups,$group);
1.683     raeburn  9134:                 }
                   9135:             }
                   9136:         }
1.817     raeburn  9137:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9138:         $grouplist = join(':',@usersgroups);
                   9139:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9140:     }
1.733     raeburn  9141:     return @usersgroups;
1.683     raeburn  9142: }
                   9143: 
                   9144: sub devalidate_getgroups_cache {
                   9145:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9146:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9147: 
1.683     raeburn  9148:     my $hashid="$udom:$uname:$courseid";
                   9149:     &devalidate_cache_new('getgroups',$hashid);
                   9150: }
                   9151: 
1.12      www      9152: # ------------------------------------------------------------------ Plain Text
                   9153: 
                   9154: sub plaintext {
1.988     raeburn  9155:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9156:     if ($short =~ m{^cr/}) {
1.758     albertel 9157: 	return (split('/',$short))[-1];
                   9158:     }
1.742     raeburn  9159:     if (!defined($cid)) {
                   9160:         $cid = $env{'request.course.id'};
                   9161:     }
                   9162:     my %rolenames = (
1.1008    raeburn  9163:                       Course    => 'std',
                   9164:                       Community => 'alt1',
1.1305    raeburn  9165:                       Placement => 'std',
1.742     raeburn  9166:                     );
1.1037    raeburn  9167:     if ($cid ne '') {
                   9168:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9169:             unless ($forcedefault) {
                   9170:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9171:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9172:                 return &Apache::lonlocal::mt($roletext);
                   9173:             }
                   9174:         }
                   9175:     }
                   9176:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9177:         (defined($rolenames{$type})) && 
                   9178:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9179:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9180:     } elsif ($cid ne '') {
                   9181:         my $crstype = $env{'course.'.$cid.'.type'};
                   9182:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9183:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9184:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9185:         }
1.742     raeburn  9186:     }
1.1037    raeburn  9187:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9188: }
                   9189: 
                   9190: # ----------------------------------------------------------------- Assign Role
                   9191: 
                   9192: sub assignrole {
1.957     raeburn  9193:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9194:         $context)=@_;
1.21      www      9195:     my $mrole;
                   9196:     if ($role =~ /^cr\//) {
1.393     www      9197:         my $cwosec=$url;
1.811     albertel 9198:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9199: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9200:            my $refused = 1;
                   9201:            if ($context eq 'requestcourses') {
                   9202:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9203:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9204:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9205:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9206:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9207:                            if ($crsenv{'internal.courseowner'} eq
                   9208:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9209:                                $refused = '';
                   9210:                            }
                   9211:                        }
                   9212:                    }
                   9213:                }
                   9214:            }
                   9215:            if ($refused) {
                   9216:                &logthis('Refused custom assignrole: '.
                   9217:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9218:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9219:                return 'refused';
                   9220:            }
1.104     www      9221:         }
1.21      www      9222:         $mrole='cr';
1.678     raeburn  9223:     } elsif ($role =~ /^gr\//) {
                   9224:         my $cwogrp=$url;
1.811     albertel 9225:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9226:         unless (&allowed('mdg',$cwogrp)) {
                   9227:             &logthis('Refused group assignrole: '.
                   9228:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9229:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9230:             return 'refused';
                   9231:         }
                   9232:         $mrole='gr';
1.21      www      9233:     } else {
1.82      www      9234:         my $cwosec=$url;
1.811     albertel 9235:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9236:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9237:             my $refused;
                   9238:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9239:                 if (!(&allowed('c'.$role,$url))) {
                   9240:                     $refused = 1;
                   9241:                 }
                   9242:             } else {
                   9243:                 $refused = 1;
                   9244:             }
1.947     raeburn  9245:             if ($refused) {
1.1045    raeburn  9246:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9247:                 if (!$selfenroll && $context eq 'course') {
                   9248:                     my %crsenv;
                   9249:                     if ($role eq 'cc' || $role eq 'co') {
                   9250:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9251:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9252:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9253:                                 if ($crsenv{'internal.courseowner'} eq 
                   9254:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9255:                                     $refused = '';
                   9256:                                 }
                   9257:                             }
                   9258:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9259:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9260:                                 if ($crsenv{'internal.courseowner'} eq 
                   9261:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9262:                                     $refused = '';
                   9263:                                 }
                   9264:                             }
                   9265:                         }
                   9266:                     }
                   9267:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9268:                     $refused = '';
1.1017    raeburn  9269:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9270:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9271:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9272:                         my $wrongcc;
                   9273:                         if ($cnum =~ /^$match_community$/) {
                   9274:                             $wrongcc = 1 if ($role eq 'cc');
                   9275:                         } else {
                   9276:                             $wrongcc = 1 if ($role eq 'co');
                   9277:                         }
                   9278:                         unless ($wrongcc) {
                   9279:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9280:                             if ($crsenv{'internal.courseowner'} eq 
                   9281:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9282:                                 $refused = '';
                   9283:                             }
1.1017    raeburn  9284:                         }
                   9285:                     }
1.1183    raeburn  9286:                 } elsif ($context eq 'requestauthor') {
                   9287:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   9288:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9289:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9290:                             $refused = '';
                   9291:                         } else {
                   9292:                             my %domdefaults = &get_domain_defaults($udom);
                   9293:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9294:                                 my $checkbystatus;
                   9295:                                 if ($env{'user.adv'}) { 
                   9296:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9297:                                     if ($disposition eq 'automatic') {
                   9298:                                         $refused = '';
                   9299:                                     } elsif ($disposition eq '') {
                   9300:                                         $checkbystatus = 1;
                   9301:                                     } 
                   9302:                                 } else {
                   9303:                                     $checkbystatus = 1;
                   9304:                                 }
                   9305:                                 if ($checkbystatus) {
                   9306:                                     if ($env{'environment.inststatus'}) {
                   9307:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9308:                                         foreach my $type (@inststatuses) {
                   9309:                                             if (($type ne '') &&
                   9310:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9311:                                                 $refused = '';
                   9312:                                             }
                   9313:                                         }
                   9314:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9315:                                         $refused = '';
                   9316:                                     }
                   9317:                                 }
                   9318:                             }
                   9319:                         }
                   9320:                     }
1.1017    raeburn  9321:                 }
                   9322:                 if ($refused) {
1.947     raeburn  9323:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9324:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9325: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9326:                     return 'refused';
                   9327:                 }
1.932     raeburn  9328:             }
1.1131    raeburn  9329:         } elsif ($role eq 'au') {
                   9330:             if ($url ne '/'.$udom.'/') {
                   9331:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9332:                          ' to assign author role for '.$uname.':'.$udom.
                   9333:                          ' in domain: '.$url.' refused (wrong domain).');
                   9334:                 return 'refused';
                   9335:             }
1.104     www      9336:         }
1.21      www      9337:         $mrole=$role;
                   9338:     }
1.620     albertel 9339:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9340:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9341:     if ($end) { $command.='_'.$end; }
1.21      www      9342:     if ($start) {
                   9343: 	if ($end) { 
1.81      www      9344:            $command.='_'.$start; 
1.21      www      9345:         } else {
1.81      www      9346:            $command.='_0_'.$start;
1.21      www      9347:         }
                   9348:     }
1.739     raeburn  9349:     my $origstart = $start;
                   9350:     my $origend = $end;
1.957     raeburn  9351:     my $delflag;
1.357     www      9352: # actually delete
                   9353:     if ($deleteflag) {
1.373     www      9354: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9355: # modify command to delete the role
1.620     albertel 9356:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9357:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9358: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9359: # set start and finish to negative values for userrolelog
                   9360:            $start=-1;
                   9361:            $end=-1;
1.957     raeburn  9362:            $delflag = 1;
1.357     www      9363:         }
                   9364:     }
                   9365: # send command
1.349     www      9366:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9367: # log new user role if status is ok
1.349     www      9368:     if ($answer eq 'ok') {
1.663     raeburn  9369: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  9370:         if (($role eq 'cc') || ($role eq 'in') ||
                   9371:             ($role eq 'ep') || ($role eq 'ad') ||
                   9372:             ($role eq 'ta') || ($role eq 'st') ||
                   9373:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9374:             ($role eq 'co')) {
1.1200    raeburn  9375: # for course roles, perform group memberships changes triggered by role change.
                   9376:             unless ($role =~ /^gr/) {
                   9377:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9378:                                                  $origstart,$selfenroll,$context);
                   9379:             }
1.1184    raeburn  9380:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9381:                            $selfenroll,$context);
                   9382:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  9383:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9384:                  ($role eq 'da')) {
1.1184    raeburn  9385:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9386:                            $context);
                   9387:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9388:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9389:                              $context); 
                   9390:         }
1.1053    raeburn  9391:         if ($role eq 'cc') {
                   9392:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9393:         }
1.349     www      9394:     }
                   9395:     return $answer;
1.169     harris41 9396: }
                   9397: 
1.1053    raeburn  9398: sub autoupdate_coowners {
                   9399:     my ($url,$end,$start,$uname,$udom) = @_;
                   9400:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9401:     if (($cdom ne '') && ($cnum ne '')) {
                   9402:         my $now = time;
                   9403:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9404:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9405:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9406:             my $instcode = $coursehash{'internal.coursecode'};
                   9407:             if ($instcode ne '') {
1.1056    raeburn  9408:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9409:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9410:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9411:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9412:                         if ($result eq 'valid') {
                   9413:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9414:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9415:                                     push(@newcoowners,$coowner);
                   9416:                                 }
                   9417:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9418:                                     push(@newcoowners,$uname.':'.$udom);
                   9419:                                 }
                   9420:                                 @newcoowners = sort(@newcoowners);
                   9421:                             } else {
                   9422:                                 push(@newcoowners,$uname.':'.$udom);
                   9423:                             }
                   9424:                         } else {
                   9425:                             if ($coursehash{'internal.co-owners'}) {
                   9426:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9427:                                     unless ($coowner eq $uname.':'.$udom) {
                   9428:                                         push(@newcoowners,$coowner);
                   9429:                                     }
                   9430:                                 }
                   9431:                                 unless (@newcoowners > 0) {
                   9432:                                     $delcoowners = 1;
                   9433:                                     $coowners = '';
                   9434:                                 }
                   9435:                             }
                   9436:                         }
                   9437:                         if (@newcoowners || $delcoowners) {
                   9438:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9439:                                             $delcoowners,@newcoowners);
                   9440:                         }
                   9441:                     }
                   9442:                 }
                   9443:             }
                   9444:         }
                   9445:     }
                   9446: }
                   9447: 
                   9448: sub store_coowners {
                   9449:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9450:     my $cid = $cdom.'_'.$cnum;
                   9451:     my ($coowners,$delresult,$putresult);
                   9452:     if (@newcoowners) {
                   9453:         $coowners = join(',',@newcoowners);
                   9454:         my %coownershash = (
                   9455:                             'internal.co-owners' => $coowners,
                   9456:                            );
                   9457:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9458:         if ($putresult eq 'ok') {
                   9459:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9460:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9461:             }
                   9462:         }
                   9463:     }
                   9464:     if ($delcoowners) {
                   9465:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9466:         if ($delresult eq 'ok') {
                   9467:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9468:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9469:             }
                   9470:         }
                   9471:     }
                   9472:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9473:         my %crsinfo =
                   9474:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9475:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9476:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9477:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9478:         }
                   9479:     }
                   9480: }
                   9481: 
1.169     harris41 9482: # -------------------------------------------------- Modify user authentication
1.197     www      9483: # Overrides without validation
                   9484: 
1.169     harris41 9485: sub modifyuserauth {
                   9486:     my ($udom,$uname,$umode,$upass)=@_;
                   9487:     my $uhome=&homeserver($uname,$udom);
1.197     www      9488:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9489:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9490:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9491:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9492:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9493: 		     &escape($upass),$uhome);
1.620     albertel 9494:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9495:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9496:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9497:     &log($udom,,$uname,$uhome,
1.620     albertel 9498:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9499:                                      $env{'user.name'}.', '.$umode.
1.197     www      9500:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9501:     unless ($reply eq 'ok') {
1.197     www      9502:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9503: 	return 'error: '.$reply;
                   9504:     }   
1.170     harris41 9505:     return 'ok';
1.80      www      9506: }
                   9507: 
1.81      www      9508: # --------------------------------------------------------------- Modify a user
1.80      www      9509: 
1.81      www      9510: sub modifyuser {
1.206     matthew  9511:     my ($udom,    $uname, $uid,
                   9512:         $umode,   $upass, $first,
                   9513:         $middle,  $last,  $gene,
1.1058    raeburn  9514:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9515:     $udom= &LONCAPA::clean_domain($udom);
                   9516:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9517:     my $showcandelete = 'none';
                   9518:     if (ref($candelete) eq 'ARRAY') {
                   9519:         if (@{$candelete} > 0) {
                   9520:             $showcandelete = join(', ',@{$candelete});
                   9521:         }
                   9522:     }
1.81      www      9523:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9524:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9525: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9526:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9527:                                      ' desiredhome not specified'). 
1.620     albertel 9528:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9529:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9530:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9531:     my $newuser;
                   9532:     if ($uhome eq 'no_host') {
                   9533:         $newuser = 1;
                   9534:     }
1.80      www      9535: # ----------------------------------------------------------------- Create User
1.406     albertel 9536:     if (($uhome eq 'no_host') && 
                   9537: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9538:         my $unhome='';
1.844     albertel 9539:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9540:             $unhome = $desiredhome;
1.620     albertel 9541: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9542: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9543:         } else { # load balancing routine for determining $unhome
1.81      www      9544:             my $loadm=10000000;
1.841     albertel 9545: 	    my %servers = &get_servers($udom,'library');
                   9546: 	    foreach my $tryserver (keys(%servers)) {
                   9547: 		my $answer=reply('load',$tryserver);
                   9548: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9549: 		    $loadm=$answer;
                   9550: 		    $unhome=$tryserver;
                   9551: 		}
1.80      www      9552: 	    }
                   9553:         }
                   9554:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9555: 	    return 'error: unable to find a home server for '.$uname.
                   9556:                    ' in domain '.$udom;
1.80      www      9557:         }
                   9558:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9559:                          &escape($upass),$unhome);
                   9560: 	unless ($reply eq 'ok') {
                   9561:             return 'error: '.$reply;
                   9562:         }   
1.230     stredwic 9563:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9564:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9565: 	    return 'error: unable verify users home machine.';
1.80      www      9566:         }
1.209     matthew  9567:     }   # End of creation of new user
1.80      www      9568: # ---------------------------------------------------------------------- Add ID
                   9569:     if ($uid) {
                   9570:        $uid=~tr/A-Z/a-z/;
                   9571:        my %uidhash=&idrget($udom,$uname);
1.196     www      9572:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9573:          && (!$forceid)) {
1.80      www      9574: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9575: 	      return 'error: user id "'.$uid.'" does not match '.
                   9576:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9577:           }
                   9578:        } else {
1.1300    raeburn  9579: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9580:        }
                   9581:     }
                   9582: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9583:     my @tmp=&get('environment',
1.899     raeburn  9584: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9585:                     'permanentemail','inststatus'],
1.134     albertel 9586: 		   $udom,$uname);
1.1075    raeburn  9587:     my (%names,%oldnames);
1.313     matthew  9588:     if ($tmp[0] =~ m/^error:.*/) { 
                   9589:         %names=(); 
                   9590:     } else {
                   9591:         %names = @tmp;
1.1075    raeburn  9592:         %oldnames = %names;
1.313     matthew  9593:     }
1.388     www      9594: #
1.1058    raeburn  9595: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9596: # of users did not contain them), do not overwrite existing values
                   9597: # unless field is in $candelete array ref.  
                   9598: #
                   9599: 
                   9600:     my @fields = ('firstname','middlename','lastname','generation',
                   9601:                   'permanentemail','id');
                   9602:     my %newvalues;
                   9603:     if (ref($candelete) eq 'ARRAY') {
                   9604:         foreach my $field (@fields) {
                   9605:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9606:                 if ($field eq 'firstname') {
                   9607:                     $names{$field} = $first;
                   9608:                 } elsif ($field eq 'middlename') {
                   9609:                     $names{$field} = $middle;
                   9610:                 } elsif ($field eq 'lastname') {
                   9611:                     $names{$field} = $last;
                   9612:                 } elsif ($field eq 'generation') { 
                   9613:                     $names{$field} = $gene;
                   9614:                 } elsif ($field eq 'permanentemail') {
                   9615:                     $names{$field} = $email;
                   9616:                 } elsif ($field eq 'id') {
                   9617:                     $names{$field}  = $uid;
                   9618:                 }
                   9619:             }
                   9620:         }
                   9621:     }
1.388     www      9622:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9623:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9624:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9625:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9626:     if ($email) {
                   9627:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9628:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9629:     }
1.899     raeburn  9630:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9631:     if (defined($inststatus)) {
                   9632:         $names{'inststatus'} = '';
                   9633:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9634:         if (ref($usertypes) eq 'HASH') {
                   9635:             my @okstatuses; 
                   9636:             foreach my $item (split(/:/,$inststatus)) {
                   9637:                 if (defined($usertypes->{$item})) {
                   9638:                     push(@okstatuses,$item);  
                   9639:                 }
                   9640:             }
                   9641:             if (@okstatuses) {
                   9642:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9643:             }
                   9644:         }
                   9645:     }
1.1075    raeburn  9646:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9647:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9648:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9649:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9650:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9651:     } else {
                   9652:         $logmsg .= ' during self creation';
                   9653:     }
1.1075    raeburn  9654:     my $changed;
                   9655:     if ($newuser) {
                   9656:         $changed = 1;
                   9657:     } else {
                   9658:         foreach my $field (@fields) {
                   9659:             if ($names{$field} ne $oldnames{$field}) {
                   9660:                 $changed = 1;
                   9661:                 last;
                   9662:             }
                   9663:         }
                   9664:     }
                   9665:     unless ($changed) {
                   9666:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9667:         &logthis($logmsg);
                   9668:         return 'ok';
                   9669:     }
                   9670:     my $reply = &put('environment', \%names, $udom,$uname);
                   9671:     if ($reply ne 'ok') { 
                   9672:         return 'error: '.$reply;
                   9673:     }
1.1087    raeburn  9674:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9675:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9676:     }
1.1075    raeburn  9677:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9678:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9679:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9680:     &logthis($logmsg);
1.134     albertel 9681:     return 'ok';
1.80      www      9682: }
                   9683: 
1.81      www      9684: # -------------------------------------------------------------- Modify student
1.80      www      9685: 
1.81      www      9686: sub modifystudent {
                   9687:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9688:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9689:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9690:     if (!$cid) {
1.620     albertel 9691: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9692: 	    return 'not_in_class';
                   9693: 	}
1.80      www      9694:     }
                   9695: # --------------------------------------------------------------- Make the user
1.81      www      9696:     my $reply=&modifyuser
1.209     matthew  9697: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9698:          $desiredhome,$email,$inststatus);
1.80      www      9699:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9700:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9701:     # student's environment
1.297     matthew  9702:     $uid = undef if (!$forceid);
1.455     albertel 9703:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9704:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9705:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9706:     return $reply;
                   9707: }
                   9708: 
                   9709: sub modify_student_enrollment {
1.1216    raeburn  9710:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9711:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9712:     my ($cdom,$cnum,$chome);
                   9713:     if (!$cid) {
1.620     albertel 9714: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9715: 	    return 'not_in_class';
                   9716: 	}
1.620     albertel 9717: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9718: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9719:     } else {
                   9720: 	($cdom,$cnum)=split(/_/,$cid);
                   9721:     }
1.620     albertel 9722:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9723:     if (!$chome) {
1.457     raeburn  9724: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9725:     }
1.455     albertel 9726:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9727:     # Make sure the user exists
1.81      www      9728:     my $uhome=&homeserver($uname,$udom);
                   9729:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9730: 	return 'error: no such user';
                   9731:     }
1.297     matthew  9732:     # Get student data if we were not given enough information
                   9733:     if (!defined($first)  || $first  eq '' || 
                   9734:         !defined($last)   || $last   eq '' || 
                   9735:         !defined($uid)    || $uid    eq '' || 
                   9736:         !defined($middle) || $middle eq '' || 
                   9737:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9738:         # They did not supply us with enough data to enroll the student, so
                   9739:         # we need to pick up more information.
1.297     matthew  9740:         my %tmp = &get('environment',
1.294     matthew  9741:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9742:                        ,$udom,$uname);
                   9743: 
1.800     albertel 9744:         #foreach my $key (keys(%tmp)) {
                   9745:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9746:         #}
1.294     matthew  9747:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9748:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9749:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9750:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9751:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9752:     }
1.556     albertel 9753:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9754:     my $user = "$uname:$udom";
                   9755:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9756:     my $reply=cput('classlist',
1.1148    raeburn  9757: 		   {$user => 
1.1314    raeburn  9758: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9759: 		   $cdom,$cnum);
1.1148    raeburn  9760:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9761:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9762:     } else { 
1.81      www      9763: 	return 'error: '.$reply;
                   9764:     }
1.297     matthew  9765:     # Add student role to user
1.83      www      9766:     my $uurl='/'.$cid;
1.81      www      9767:     $uurl=~s/\_/\//g;
                   9768:     if ($usec) {
                   9769: 	$uurl.='/'.$usec;
                   9770:     }
1.1148    raeburn  9771:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9772:                              $selfenroll,$context);
                   9773:     if ($result ne 'ok') {
                   9774:         if ($old_entry{$user} ne '') {
                   9775:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9776:         } else {
                   9777:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9778:         }
                   9779:     }
                   9780:     return $result; 
1.21      www      9781: }
                   9782: 
1.556     albertel 9783: sub format_name {
                   9784:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9785:     my $name;
                   9786:     if ($first ne 'lastname') {
                   9787: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9788:     } else {
                   9789: 	if ($lastname=~/\S/) {
                   9790: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9791: 	    $name=~s/\s+,/,/;
                   9792: 	} else {
                   9793: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9794: 	}
                   9795:     }
                   9796:     $name=~s/^\s+//;
                   9797:     $name=~s/\s+$//;
                   9798:     $name=~s/\s+/ /g;
                   9799:     return $name;
                   9800: }
                   9801: 
1.84      www      9802: # ------------------------------------------------- Write to course preferences
                   9803: 
                   9804: sub writecoursepref {
                   9805:     my ($courseid,%prefs)=@_;
                   9806:     $courseid=~s/^\///;
                   9807:     $courseid=~s/\_/\//g;
                   9808:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9809:     my $chome=homeserver($cnum,$cdomain);
                   9810:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9811: 	return 'error: no such course';
                   9812:     }
                   9813:     my $cstring='';
1.800     albertel 9814:     foreach my $pref (keys(%prefs)) {
                   9815: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9816:     }
1.84      www      9817:     $cstring=~s/\&$//;
                   9818:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9819: }
                   9820: 
                   9821: # ---------------------------------------------------------- Make/modify course
                   9822: 
                   9823: sub createcourse {
1.741     raeburn  9824:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9825:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9826:     $url=&declutter($url);
                   9827:     my $cid='';
1.1028    raeburn  9828:     if ($context eq 'requestcourses') {
                   9829:         my $can_create = 0;
                   9830:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9831:         if ($udom eq $ownerdom) {
                   9832:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9833:                                   $context)) {
                   9834:                 $can_create = 1;
                   9835:             }
                   9836:         } else {
                   9837:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9838:                                            $category);
                   9839:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9840:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9841:                 if (@curr > 0) {
                   9842:                     my @options = qw(approval validate autolimit);
                   9843:                     my $optregex = join('|',@options);
                   9844:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9845:                         $can_create = 1;
                   9846:                     }
                   9847:                 }
                   9848:             }
                   9849:         }
                   9850:         if ($can_create) {
                   9851:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9852:                 unless (&allowed('ccc',$udom)) {
                   9853:                     return 'refused'; 
                   9854:                 }
1.1017    raeburn  9855:             }
                   9856:         } else {
                   9857:             return 'refused';
                   9858:         }
1.1028    raeburn  9859:     } elsif (!&allowed('ccc',$udom)) {
                   9860:         return 'refused';
1.84      www      9861:     }
1.1011    raeburn  9862: # --------------------------------------------------------------- Get Unique ID
                   9863:     my $uname;
                   9864:     if ($cnum =~ /^$match_courseid$/) {
                   9865:         my $chome=&homeserver($cnum,$udom,'true');
                   9866:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9867:             $uname = $cnum;
                   9868:         } else {
1.1038    raeburn  9869:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9870:         }
                   9871:     } else {
1.1038    raeburn  9872:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9873:     }
                   9874:     return $uname if ($uname =~ /^error/);
                   9875: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9876:     if (!defined($course_server)) {
                   9877:         if (defined(&domain($udom,'primary'))) {
                   9878:             $course_server = &domain($udom,'primary');
                   9879:         } else {
                   9880:             $course_server = $env{'user.home'}; 
                   9881:         }
                   9882:     }
                   9883:     my %host_servers =
                   9884:         &Apache::lonnet::get_servers($udom,'library');
                   9885:     unless ($host_servers{$course_server}) {
                   9886:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9887:     }
1.84      www      9888: # ------------------------------------------------------------- Make the course
                   9889:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9890:                       $course_server);
1.84      www      9891:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9892:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9893:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9894: 	return 'error: no such course';
                   9895:     }
1.271     www      9896: # ----------------------------------------------------------------- Course made
1.516     raeburn  9897: # log existence
1.1029    raeburn  9898:     my $now = time;
1.918     raeburn  9899:     my $newcourse = {
                   9900:                     $udom.'_'.$uname => {
1.921     raeburn  9901:                                      description => $description,
                   9902:                                      inst_code   => $inst_code,
                   9903:                                      owner       => $course_owner,
                   9904:                                      type        => $crstype,
1.1029    raeburn  9905:                                      creator     => $env{'user.name'}.':'.
                   9906:                                                     $env{'user.domain'},
                   9907:                                      created     => $now,
                   9908:                                      context     => $context,
1.918     raeburn  9909:                                                 },
                   9910:                     };
1.921     raeburn  9911:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9912: # set toplevel url
1.271     www      9913:     my $topurl=$url;
                   9914:     unless ($nonstandard) {
                   9915: # ------------------------------------------ For standard courses, make top url
                   9916:         my $mapurl=&clutter($url);
1.278     www      9917:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9918:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9919: <map>
                   9920: <resource id="1" type="start"></resource>
                   9921: <resource id="2" src="$mapurl"></resource>
                   9922: <resource id="3" type="finish"></resource>
                   9923: <link index="1" from="1" to="2"></link>
                   9924: <link index="2" from="2" to="3"></link>
                   9925: </map>
                   9926: ENDINITMAP
                   9927:         $topurl=&declutter(
1.638     albertel 9928:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9929:                           );
                   9930:     }
                   9931: # ----------------------------------------------------------- Write preferences
1.84      www      9932:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9933:                      ('description'              => $description,
                   9934:                       'url'                      => $topurl,
                   9935:                       'internal.creator'         => $env{'user.name'}.':'.
                   9936:                                                     $env{'user.domain'},
                   9937:                       'internal.created'         => $now,
                   9938:                       'internal.creationcontext' => $context)
                   9939:                     );
1.84      www      9940:     return '/'.$udom.'/'.$uname;
                   9941: }
                   9942: 
1.1011    raeburn  9943: # ------------------------------------------------------------------- Create ID
                   9944: sub generate_coursenum {
1.1038    raeburn  9945:     my ($udom,$crstype) = @_;
1.1011    raeburn  9946:     my $domdesc = &domain($udom);
                   9947:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9948:     my $first;
                   9949:     if ($crstype eq 'Community') {
                   9950:         $first = '0';
                   9951:     } else {
                   9952:         $first = int(1+rand(9)); 
                   9953:     } 
                   9954:     my $uname=$first.
1.1011    raeburn  9955:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9956:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9957:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9958: # ----------------------------------------------- Make sure that does not exist
                   9959:     my $uhome=&homeserver($uname,$udom,'true');
                   9960:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9961:         if ($crstype eq 'Community') {
                   9962:             $first = '0';
                   9963:         } else {
                   9964:             $first = int(1+rand(9));
                   9965:         }
                   9966:         $uname=$first.
1.1011    raeburn  9967:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9968:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9969:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9970:         $uhome=&homeserver($uname,$udom,'true');
                   9971:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9972:             return 'error: unable to generate unique course-ID';
                   9973:         }
                   9974:     }
                   9975:     return $uname;
                   9976: }
                   9977: 
1.813     albertel 9978: sub is_course {
1.1167    droeschl 9979:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9980:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9981: 
                   9982:     return unless $cdom and $cnum;
                   9983: 
                   9984:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9985:         '.');
                   9986: 
1.1219    raeburn  9987:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9988:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9989: }
                   9990: 
1.1015    raeburn  9991: sub store_userdata {
                   9992:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9993:     my $result;
1.1016    raeburn  9994:     if ($datakey ne '') {
1.1013    raeburn  9995:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9996:             if ($udom eq '' || $uname eq '') {
                   9997:                 $udom = $env{'user.domain'};
                   9998:                 $uname = $env{'user.name'};
                   9999:             }
                   10000:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10001:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10002:                 $result = 'error: no_host';
                   10003:             } else {
                   10004:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10005:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10006: 
                   10007:                 my $namevalue='';
                   10008:                 foreach my $key (keys(%{$storehash})) {
                   10009:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10010:                 }
                   10011:                 $namevalue=~s/\&$//;
1.1224    raeburn  10012:                 unless ($namespace eq 'courserequests') {
                   10013:                     $datakey = &escape($datakey);
                   10014:                 }
1.1105    raeburn  10015:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10016:                                   $namevalue,$uhome);
1.1013    raeburn  10017:             }
                   10018:         } else {
                   10019:             $result = 'error: data to store was not a hash reference'; 
                   10020:         }
                   10021:     } else {
                   10022:         $result= 'error: invalid requestkey'; 
                   10023:     }
                   10024:     return $result;
                   10025: }
                   10026: 
1.21      www      10027: # ---------------------------------------------------------- Assign Custom Role
                   10028: 
                   10029: sub assigncustomrole {
1.957     raeburn  10030:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10031:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10032:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10033: }
                   10034: 
                   10035: # ----------------------------------------------------------------- Revoke Role
                   10036: 
                   10037: sub revokerole {
1.957     raeburn  10038:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10039:     my $now=time;
1.965     raeburn  10040:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10041: }
                   10042: 
                   10043: # ---------------------------------------------------------- Revoke Custom Role
                   10044: 
                   10045: sub revokecustomrole {
1.957     raeburn  10046:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10047:     my $now=time;
1.357     www      10048:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10049:            $deleteflag,$selfenroll,$context);
1.17      www      10050: }
                   10051: 
1.533     banghart 10052: # ------------------------------------------------------------ Disk usage
1.535     albertel 10053: sub diskusage {
1.955     raeburn  10054:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10055:     $directorypath =~ s/\/$//;
                   10056:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10057:                        .&escape($getpropath).':'.&escape($uname).':'
                   10058:                        .&escape($udom),homeserver($uname,$udom));
                   10059:     if ($listing eq 'unknown_cmd') {
                   10060:         if ($getpropath) {
                   10061:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10062:         }
                   10063:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10064:     }
1.514     albertel 10065:     return $listing;
1.512     banghart 10066: }
                   10067: 
1.566     banghart 10068: sub is_locked {
1.1096    raeburn  10069:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10070:     my @check;
                   10071:     my $is_locked;
1.1093    raeburn  10072:     push (@check,$file_name);
1.613     albertel 10073:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10074: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10075:     my ($tmp)=keys(%locked);
                   10076:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10077:     
1.566     banghart 10078:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10079:         $is_locked = 'false';
                   10080:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10081:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10082:                $is_locked = 'true';
1.1096    raeburn  10083:                if (ref($which) eq 'ARRAY') {
                   10084:                    push(@{$which},$entry);
                   10085:                } else {
                   10086:                    last;
                   10087:                }
1.745     raeburn  10088:            }
                   10089:        }
1.566     banghart 10090:     } else {
                   10091:         $is_locked = 'false';
                   10092:     }
1.1093    raeburn  10093:     return $is_locked;
1.566     banghart 10094: }
                   10095: 
1.759     albertel 10096: sub declutter_portfile {
                   10097:     my ($file) = @_;
1.833     albertel 10098:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10099:     return $file;
                   10100: }
                   10101: 
1.559     banghart 10102: # ------------------------------------------------------------- Mark as Read Only
                   10103: 
                   10104: sub mark_as_readonly {
                   10105:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10106:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10107:     my ($tmp)=keys(%current_permissions);
                   10108:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10109:     foreach my $file (@{$files}) {
1.759     albertel 10110: 	$file = &declutter_portfile($file);
1.561     banghart 10111:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10112:     }
1.613     albertel 10113:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10114:     return;
                   10115: }
                   10116: 
1.572     banghart 10117: # ------------------------------------------------------------Save Selected Files
                   10118: 
                   10119: sub save_selected_files {
                   10120:     my ($user, $path, @files) = @_;
                   10121:     my $filename = $user."savedfiles";
1.573     banghart 10122:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  10123:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10124:     foreach my $file (@files) {
1.620     albertel 10125:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10126:     }
                   10127:     foreach my $file (@other_files) {
1.574     banghart 10128:         print (OUT $file."\n");
1.572     banghart 10129:     }
1.574     banghart 10130:     close (OUT);
1.572     banghart 10131:     return 'ok';
                   10132: }
                   10133: 
1.574     banghart 10134: sub clear_selected_files {
                   10135:     my ($user) = @_;
                   10136:     my $filename = $user."savedfiles";
1.1359    raeburn  10137:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10138:     print (OUT undef);
                   10139:     close (OUT);
                   10140:     return ("ok");    
                   10141: }
                   10142: 
1.572     banghart 10143: sub files_in_path {
                   10144:     my ($user, $path) = @_;
                   10145:     my $filename = $user."savedfiles";
                   10146:     my %return_files;
1.1359    raeburn  10147:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10148:     while (my $line_in = <IN>) {
1.574     banghart 10149:         chomp ($line_in);
                   10150:         my @paths_and_file = split (m!/!, $line_in);
                   10151:         my $file_part = pop (@paths_and_file);
                   10152:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10153:         $path_part.='/';
                   10154:         my $path_and_file = $path_part.$file_part;
                   10155:         if ($path_part eq $path) {
                   10156:             $return_files{$file_part}= 'selected';
                   10157:         }
                   10158:     }
1.574     banghart 10159:     close (IN);
                   10160:     return (\%return_files);
1.572     banghart 10161: }
                   10162: 
                   10163: # called in portfolio select mode, to show files selected NOT in current directory
                   10164: sub files_not_in_path {
                   10165:     my ($user, $path) = @_;
                   10166:     my $filename = $user."savedfiles";
                   10167:     my @return_files;
                   10168:     my $path_part;
1.1359    raeburn  10169:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10170:     while (my $line = <IN>) {
1.572     banghart 10171:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10172:         my @paths_and_file = split(m|/|, $line);
                   10173:         my $file_part = pop(@paths_and_file);
                   10174:         chomp($file_part);
                   10175:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10176:         $path_part .= '/';
                   10177:         my $path_and_file = $path_part.$file_part;
                   10178:         if ($path_part ne $path) {
1.800     albertel 10179:             push(@return_files, ($path_and_file));
1.572     banghart 10180:         }
                   10181:     }
1.800     albertel 10182:     close(OUT);
1.574     banghart 10183:     return (@return_files);
1.572     banghart 10184: }
                   10185: 
1.1273    raeburn  10186: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   10187:  
                   10188: sub portfiles_versioning {
                   10189:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   10190:     my $portfolio_root = '/userfiles/portfolio';
                   10191:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   10192:     foreach my $file (@{$portfiles}) {
                   10193:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   10194:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   10195:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   10196:         my $getpropath = 1;
                   10197:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   10198:                                              $stu_name,$getpropath);
                   10199:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   10200:         my $new_answer = 
                   10201:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   10202:         if ($new_answer ne 'problem getting file') {
                   10203:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   10204:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   10205:                               [$symb,$env{'request.course.id'},'graded']);
                   10206:         }
                   10207:     }
                   10208: }
                   10209: 
                   10210: sub get_next_version {
                   10211:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   10212:     my $version;
                   10213:     if (ref($dir_list) eq 'ARRAY') {
                   10214:         foreach my $row (@{$dir_list}) {
                   10215:             my ($file) = split(/\&/,$row,2);
                   10216:             my ($file_name,$file_version,$file_ext) =
                   10217:                 &file_name_version_ext($file);
                   10218:             if (($file_name eq $answer_name) &&
                   10219:                 ($file_ext eq $answer_ext)) {
                   10220:                      # gets here if filename and extension match,
                   10221:                      # regardless of version
                   10222:                 if ($file_version ne '') {
                   10223:                     # a versioned file is found  so save it for later
                   10224:                     if ($file_version > $version) {
                   10225:                         $version = $file_version;
                   10226:                     }
                   10227:                 }
                   10228:             }
                   10229:         }
                   10230:     }
                   10231:     $version ++;
                   10232:     return($version);
                   10233: }
                   10234: 
                   10235: sub version_selected_portfile {
                   10236:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   10237:     my ($answer_name,$answer_ver,$answer_ext) =
                   10238:         &file_name_version_ext($file_name);
                   10239:     my $new_answer;
                   10240:     $env{'form.copy'} =
                   10241:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   10242:     if($env{'form.copy'} eq '-1') {
                   10243:         $new_answer = 'problem getting file';
                   10244:     } else {
                   10245:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   10246:         my $copy_result = 
                   10247:             &finishuserfileupload($stu_name,$domain,'copy',
                   10248:                                   '/portfolio'.$directory.$new_answer);
                   10249:     }
                   10250:     undef($env{'form.copy'});
                   10251:     return ($new_answer);
                   10252: }
                   10253: 
                   10254: sub file_name_version_ext {
                   10255:     my ($file)=@_;
                   10256:     my @file_parts = split(/\./, $file);
                   10257:     my ($name,$version,$ext);
                   10258:     if (@file_parts > 1) {
                   10259:         $ext=pop(@file_parts);
                   10260:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   10261:             $version=pop(@file_parts);
                   10262:         }
                   10263:         $name=join('.',@file_parts);
                   10264:     } else {
                   10265:         $name=join('.',@file_parts);
                   10266:     }
                   10267:     return($name,$version,$ext);
                   10268: }
                   10269: 
1.745     raeburn  10270: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10271: 
1.745     raeburn  10272: sub get_portfile_permissions {
                   10273:     my ($domain,$user) = @_;
1.613     albertel 10274:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10275:     my ($tmp)=keys(%current_permissions);
                   10276:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10277:     return \%current_permissions;
                   10278: }
                   10279: 
                   10280: #---------------------------------------------Get portfolio file access controls
                   10281: 
1.749     raeburn  10282: sub get_access_controls {
1.745     raeburn  10283:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10284:     my %access;
                   10285:     my $real_file = $file;
                   10286:     $file =~ s/\.meta$//;
1.745     raeburn  10287:     if (defined($file)) {
1.749     raeburn  10288:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10289:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10290:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10291:             }
                   10292:         }
1.745     raeburn  10293:     } else {
1.749     raeburn  10294:         foreach my $key (keys(%{$current_permissions})) {
                   10295:             if ($key =~ /\0accesscontrol$/) {
                   10296:                 if (defined($group)) {
                   10297:                     if ($key !~ m-^\Q$group\E/-) {
                   10298:                         next;
                   10299:                     }
                   10300:                 }
                   10301:                 my ($fullpath) = split(/\0/,$key);
                   10302:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10303:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10304:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10305:                     }
                   10306:                 }
                   10307:             }
                   10308:         }
                   10309:     }
                   10310:     return %access;
                   10311: }
                   10312: 
                   10313: sub modify_access_controls {
                   10314:     my ($file_name,$changes,$domain,$user)=@_;
                   10315:     my ($outcome,$deloutcome);
                   10316:     my %store_permissions;
                   10317:     my %new_values;
                   10318:     my %new_control;
                   10319:     my %translation;
                   10320:     my @deletions = ();
                   10321:     my $now = time;
                   10322:     if (exists($$changes{'activate'})) {
                   10323:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10324:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10325:             my $numnew = scalar(@newitems);
                   10326:             for (my $i=0; $i<$numnew; $i++) {
                   10327:                 my $newkey = $newitems[$i];
                   10328:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10329:                 if ($newkey =~ /^\d+:/) { 
                   10330:                     $newkey =~ s/^(\d+)/$newid/;
                   10331:                     $translation{$1} = $newid;
                   10332:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10333:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10334:                     $translation{$1} = $newid;
                   10335:                 }
1.749     raeburn  10336:                 $new_values{$file_name."\0".$newkey} = 
                   10337:                                           $$changes{'activate'}{$newitems[$i]};
                   10338:                 $new_control{$newkey} = $now;
                   10339:             }
                   10340:         }
                   10341:     }
                   10342:     my %todelete;
                   10343:     my %changed_items;
                   10344:     foreach my $action ('delete','update') {
                   10345:         if (exists($$changes{$action})) {
                   10346:             if (ref($$changes{$action}) eq 'HASH') {
                   10347:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10348:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10349:                     if ($action eq 'delete') { 
                   10350:                         $todelete{$itemnum} = 1;
                   10351:                     } else {
                   10352:                         $changed_items{$itemnum} = $key;
                   10353:                     }
                   10354:                 }
1.745     raeburn  10355:             }
                   10356:         }
1.749     raeburn  10357:     }
                   10358:     # get lock on access controls for file.
                   10359:     my $lockhash = {
                   10360:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10361:                                                        ':'.$env{'user.domain'},
                   10362:                    }; 
                   10363:     my $tries = 0;
                   10364:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10365:    
1.1288    damieng  10366:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10367:         $tries ++;
1.1289    damieng  10368:         sleep(0.1);
1.749     raeburn  10369:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10370:     }
                   10371:     if ($gotlock eq 'ok') {
                   10372:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10373:         my ($tmp)=keys(%curr_permissions);
                   10374:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10375:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10376:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10377:             if (ref($curr_controls) eq 'HASH') {
                   10378:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10379:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10380:                     if (defined($todelete{$itemnum})) {
                   10381:                         push(@deletions,$file_name."\0".$control_item);
                   10382:                     } else {
                   10383:                         if (defined($changed_items{$itemnum})) {
                   10384:                             $new_control{$changed_items{$itemnum}} = $now;
                   10385:                             push(@deletions,$file_name."\0".$control_item);
                   10386:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10387:                         } else {
                   10388:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10389:                         }
                   10390:                     }
1.745     raeburn  10391:                 }
                   10392:             }
                   10393:         }
1.970     raeburn  10394:         my ($group);
                   10395:         if (&is_course($domain,$user)) {
                   10396:             ($group,my $file) = split(/\//,$file_name,2);
                   10397:         }
1.749     raeburn  10398:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10399:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10400:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10401:         #  remove lock
                   10402:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10403:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10404:         my $sqlresult =
1.970     raeburn  10405:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10406:                                     $group);
1.749     raeburn  10407:     } else {
                   10408:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10409:     }
1.749     raeburn  10410:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10411: }
                   10412: 
1.827     raeburn  10413: sub make_public_indefinitely {
1.1271    raeburn  10414:     my (@requrl) = @_;
                   10415:     return &automated_portfile_access('public',\@requrl);
                   10416: }
                   10417: 
                   10418: sub automated_portfile_access {
                   10419:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  10420:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   10421:         return 'invalid';
                   10422:     }
1.1271    raeburn  10423:     my %urls;
                   10424:     if (ref($addsref) eq 'ARRAY') {
                   10425:         foreach my $requrl (@{$addsref}) {
                   10426:             if (&is_portfolio_url($requrl)) {
                   10427:                 unless (exists($urls{$requrl})) {
                   10428:                     $urls{$requrl} = 'add';
                   10429:                 }
                   10430:             }
                   10431:         }
                   10432:     }
                   10433:     if (ref($delsref) eq 'ARRAY') {
                   10434:         foreach my $requrl (@{$delsref}) { 
                   10435:             if (&is_portfolio_url($requrl)) {
                   10436:                 unless (exists($urls{$requrl})) {
                   10437:                     $urls{$requrl} = 'delete'; 
                   10438:                 }
                   10439:             }
                   10440:         }
                   10441:     }
                   10442:     unless (keys(%urls)) {
                   10443:         return 'invalid';
                   10444:     }
                   10445:     my $ip;
                   10446:     if ($accesstype eq 'ip') {
                   10447:         if (ref($info) eq 'HASH') {
                   10448:             if ($info->{'ip'} ne '') {
                   10449:                 $ip = $info->{'ip'};
                   10450:             }
                   10451:         }
                   10452:         if ($ip eq '') {
                   10453:             return 'invalid';
                   10454:         }
                   10455:     }
                   10456:     my $errors;
1.827     raeburn  10457:     my $now = time;
1.1271    raeburn  10458:     my %current_perms;
                   10459:     foreach my $requrl (sort(keys(%urls))) {
                   10460:         my $action;
                   10461:         if ($urls{$requrl} eq 'add') {
                   10462:             $action = 'activate';
                   10463:         } else {
                   10464:             $action = 'none';
                   10465:         }
                   10466:         my $aclnum = 0;
1.827     raeburn  10467:         my (undef,$udom,$unum,$file_name,$group) =
                   10468:             &parse_portfolio_url($requrl);
1.1271    raeburn  10469:         unless (exists($current_perms{$unum.':'.$udom})) {
                   10470:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   10471:         }
                   10472:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  10473:                                                    $group,$file_name);
                   10474:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10475:             my ($num,$scope,$end,$start) = 
                   10476:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  10477:             if ($scope eq $accesstype) {
                   10478:                 if (($start <= $now) && ($end == 0)) {
                   10479:                     if ($accesstype eq 'ip') {
                   10480:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   10481:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   10482:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   10483:                                     if ($urls{$requrl} eq 'add') {
                   10484:                                         $action = 'none';
                   10485:                                         last;
                   10486:                                     } else {
                   10487:                                         $action = 'delete';
                   10488:                                         $aclnum = $num;
                   10489:                                         last;
                   10490:                                     }
                   10491:                                 }
                   10492:                             }
                   10493:                         }
                   10494:                     } elsif ($accesstype eq 'public') {
                   10495:                         if ($urls{$requrl} eq 'add') {
                   10496:                             $action = 'none';
                   10497:                             last;
                   10498:                         } else {
                   10499:                             $action = 'delete';
                   10500:                             $aclnum = $num;
                   10501:                             last;
                   10502:                         }
                   10503:                     }
                   10504:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  10505:                     $action = 'update';
                   10506:                     $aclnum = $num;
1.1271    raeburn  10507:                     last;
1.827     raeburn  10508:                 }
                   10509:             }
                   10510:         }
                   10511:         if ($action eq 'none') {
1.1271    raeburn  10512:             next;
1.827     raeburn  10513:         } else {
                   10514:             my %changes;
                   10515:             my $newend = 0;
                   10516:             my $newstart = $now;
1.1271    raeburn  10517:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  10518:             $changes{$action}{$newkey} = {
1.1271    raeburn  10519:                 type => $accesstype,
1.827     raeburn  10520:                 time => {
                   10521:                     start => $newstart,
                   10522:                     end   => $newend,
                   10523:                 },
                   10524:             };
1.1271    raeburn  10525:             if ($accesstype eq 'ip') {
                   10526:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   10527:             }
1.827     raeburn  10528:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10529:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  10530:             unless ($outcome eq 'ok') {
                   10531:                 $errors .= $outcome.' ';
                   10532:             }
1.827     raeburn  10533:         }
1.1271    raeburn  10534:     }
                   10535:     if ($errors) {
                   10536:         $errors =~ s/\s$//;
                   10537:         return $errors;
1.827     raeburn  10538:     } else {
1.1271    raeburn  10539:         return 'ok';
1.827     raeburn  10540:     }
                   10541: }
                   10542: 
1.745     raeburn  10543: #------------------------------------------------------Get Marked as Read Only
                   10544: 
                   10545: sub get_marked_as_readonly {
                   10546:     my ($domain,$user,$what,$group) = @_;
                   10547:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10548:     my @readonly_files;
1.629     banghart 10549:     my $cmp1=$what;
                   10550:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10551:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10552:         if (defined($group)) {
                   10553:             if ($file_name !~ m-^\Q$group\E/-) {
                   10554:                 next;
                   10555:             }
                   10556:         }
1.561     banghart 10557:         if (ref($value) eq "ARRAY"){
                   10558:             foreach my $stored_what (@{$value}) {
1.629     banghart 10559:                 my $cmp2=$stored_what;
1.759     albertel 10560:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10561:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10562:                 }
1.629     banghart 10563:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10564:                     push(@readonly_files, $file_name);
1.745     raeburn  10565:                     last;
1.563     banghart 10566:                 } elsif (!defined($what)) {
                   10567:                     push(@readonly_files, $file_name);
1.745     raeburn  10568:                     last;
1.561     banghart 10569:                 }
                   10570:             }
1.745     raeburn  10571:         }
1.561     banghart 10572:     }
                   10573:     return @readonly_files;
                   10574: }
1.577     banghart 10575: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10576: 
1.577     banghart 10577: sub get_marked_as_readonly_hash {
1.745     raeburn  10578:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10579:     my %readonly_files;
1.745     raeburn  10580:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10581:         if (defined($group)) {
                   10582:             if ($file_name !~ m-^\Q$group\E/-) {
                   10583:                 next;
                   10584:             }
                   10585:         }
1.577     banghart 10586:         if (ref($value) eq "ARRAY"){
                   10587:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10588:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10589:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10590:                         if ($lock_descriptor eq 'graded') {
                   10591:                             $readonly_files{$file_name} = 'graded';
                   10592:                         } elsif ($lock_descriptor eq 'handback') {
                   10593:                             $readonly_files{$file_name} = 'handback';
                   10594:                         } else {
                   10595:                             if (!exists($readonly_files{$file_name})) {
                   10596:                                 $readonly_files{$file_name} = 'locked';
                   10597:                             }
                   10598:                         }
1.745     raeburn  10599:                     }
1.750     banghart 10600:                 } 
1.577     banghart 10601:             }
                   10602:         } 
                   10603:     }
                   10604:     return %readonly_files;
                   10605: }
1.559     banghart 10606: # ------------------------------------------------------------ Unmark as Read Only
                   10607: 
                   10608: sub unmark_as_readonly {
1.629     banghart 10609:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10610:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10611:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10612:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10613:     my $symb_crs = $what;
                   10614:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10615:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10616:     my ($tmp)=keys(%current_permissions);
                   10617:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10618:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10619:     foreach my $file (@readonly_files) {
1.759     albertel 10620: 	my $clean_file = &declutter_portfile($file);
                   10621: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10622: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10623:         my @new_locks;
                   10624:         my @del_keys;
                   10625:         if (ref($current_locks) eq "ARRAY"){
                   10626:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10627:                 my $compare=$locker;
1.749     raeburn  10628:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10629:                     $compare=join('',@{$locker});
1.746     raeburn  10630:                     if ($compare ne $symb_crs) {
                   10631:                         push(@new_locks, $locker);
                   10632:                     }
1.563     banghart 10633:                 }
                   10634:             }
1.650     albertel 10635:             if (scalar(@new_locks) > 0) {
1.563     banghart 10636:                 $current_permissions{$file} = \@new_locks;
                   10637:             } else {
                   10638:                 push(@del_keys, $file);
1.613     albertel 10639:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10640:                 delete($current_permissions{$file});
1.563     banghart 10641:             }
                   10642:         }
1.561     banghart 10643:     }
1.613     albertel 10644:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10645:     return;
                   10646: }
1.512     banghart 10647: 
1.17      www      10648: # ------------------------------------------------------------ Directory lister
                   10649: 
                   10650: sub dirlist {
1.955     raeburn  10651:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10652:     $uri=~s/^\///;
                   10653:     $uri=~s/\/$//;
1.253     stredwic 10654:     my ($udom, $uname);
1.955     raeburn  10655:     if ($getuserdir) {
1.253     stredwic 10656:         $udom = $userdomain;
                   10657:         $uname = $username;
1.955     raeburn  10658:     } else {
                   10659:         (undef,$udom,$uname)=split(/\//,$uri);
                   10660:         if(defined($userdomain)) {
                   10661:             $udom = $userdomain;
                   10662:         }
                   10663:         if(defined($username)) {
                   10664:             $uname = $username;
                   10665:         }
1.253     stredwic 10666:     }
1.955     raeburn  10667:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10668: 
1.955     raeburn  10669:     $dirRoot = $perlvar{'lonDocRoot'};
                   10670:     if (defined($getpropath)) {
                   10671:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10672:         $dirRoot =~ s/\/$//;
1.955     raeburn  10673:     } elsif (defined($getuserdir)) {
                   10674:         my $subdir=$uname.'__';
                   10675:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10676:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10677:                    ."/$udom/$subdir/$uname";
                   10678:     } elsif (defined($alternateRoot)) {
                   10679:         $dirRoot = $alternateRoot;
1.751     banghart 10680:     }
1.253     stredwic 10681: 
                   10682:     if($udom) {
                   10683:         if($uname) {
1.1135    raeburn  10684:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10685:             if ($uhome eq 'no_host') {
                   10686:                 return ([],'no_host');
                   10687:             }
1.955     raeburn  10688:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10689:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10690:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10691:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10692:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10693:             } else {
                   10694:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10695:             }
1.605     matthew  10696:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10697:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10698:                 @listing_results = split(/:/,$listing);
                   10699:             } else {
                   10700:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10701:             }
1.1135    raeburn  10702:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10703:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10704:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10705:                 return ([],$listing);
                   10706:             } else {
                   10707:                 return (\@listing_results);
1.1135    raeburn  10708:             }
1.955     raeburn  10709:         } elsif(!$alternateRoot) {
1.1136    raeburn  10710:             my (%allusers,%listerror);
1.841     albertel 10711: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10712:  	    foreach my $tryserver (keys(%servers)) {
                   10713:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10714:                                   &escape($udom),$tryserver);
                   10715:                 if ($listing eq 'unknown_cmd') {
                   10716: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10717: 				      $udom, $tryserver);
                   10718:                 } else {
                   10719:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10720:                 }
1.841     albertel 10721: 		if ($listing eq 'unknown_cmd') {
                   10722: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10723: 				      $udom, $tryserver);
                   10724: 		    @listing_results = split(/:/,$listing);
                   10725: 		} else {
                   10726: 		    @listing_results =
                   10727: 			map { &unescape($_); } split(/:/,$listing);
                   10728: 		}
1.1136    raeburn  10729:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10730:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10731:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10732:                     $listerror{$tryserver} = $listing;
                   10733:                 } else {
1.841     albertel 10734: 		    foreach my $line (@listing_results) {
                   10735: 			my ($entry) = split(/&/,$line,2);
                   10736: 			$allusers{$entry} = 1;
                   10737: 		    }
                   10738: 		}
1.253     stredwic 10739:             }
1.1136    raeburn  10740:             my @alluserslist=();
1.800     albertel 10741:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10742:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10743:             }
1.1318    droeschl 10744: 
                   10745:             if (!%listerror) {
                   10746:                 # no errors
                   10747:                 return (\@alluserslist);
                   10748:             } elsif (scalar(keys(%servers)) == 1) {
                   10749:                 # one library server, one error 
                   10750:                 my ($key) = keys(%listerror);
                   10751:                 return (\@alluserslist, $listerror{$key});
                   10752:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10753:                 # con_lost indicates that we might miss data from at least one
                   10754:                 # library server
                   10755:                 return (\@alluserslist, 'con_lost');
                   10756:             } else {
                   10757:                 # multiple library servers and no con_lost -> data should be
                   10758:                 # complete. 
                   10759:                 return (\@alluserslist);
                   10760:             }
                   10761: 
1.253     stredwic 10762:         } else {
1.1136    raeburn  10763:             return ([],'missing username');
1.253     stredwic 10764:         }
1.955     raeburn  10765:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10766:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10767:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10768:         return (\@all_domains);
1.955     raeburn  10769:     } else {
1.1136    raeburn  10770:         return ([],'missing domain');
1.275     stredwic 10771:     }
                   10772: }
                   10773: 
                   10774: # --------------------------------------------- GetFileTimestamp
                   10775: # This function utilizes dirlist and returns the date stamp for
                   10776: # when it was last modified.  It will also return an error of -1
                   10777: # if an error occurs
                   10778: 
                   10779: sub GetFileTimestamp {
1.955     raeburn  10780:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10781:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10782:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10783:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10784:                                     undef,$getuserdir);
                   10785:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10786:         return -1;
                   10787:     }
                   10788:     if (ref($fileref) eq 'ARRAY') {
                   10789:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10790:         # @stats contains first the filename, then the stat output
                   10791:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10792:     } else {
                   10793:         return -1;
1.253     stredwic 10794:     }
1.26      www      10795: }
                   10796: 
1.712     albertel 10797: sub stat_file {
                   10798:     my ($uri) = @_;
1.787     albertel 10799:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10800: 
1.955     raeburn  10801:     my ($udom,$uname,$file);
1.712     albertel 10802:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10803: 	($udom,$uname,$file) =
1.811     albertel 10804: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10805: 	$file = 'userfiles/'.$file;
                   10806:     }
                   10807:     if ($uri =~ m-^/res/-) {
                   10808: 	($udom,$uname) = 
1.807     albertel 10809: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10810: 	$file = $uri;
                   10811:     }
                   10812: 
                   10813:     if (!$udom || !$uname || !$file) {
                   10814: 	# unable to handle the uri
                   10815: 	return ();
                   10816:     }
1.956     raeburn  10817:     my $getpropath;
                   10818:     if ($file =~ /^userfiles\//) {
                   10819:         $getpropath = 1;
                   10820:     }
1.1136    raeburn  10821:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10822:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10823:         return ();
                   10824:     } else {
                   10825:         if (ref($listref) eq 'ARRAY') {
                   10826:             my @stats = split('&',$listref->[0]);
                   10827: 	    shift(@stats); #filename is first
                   10828: 	    return @stats;
                   10829:         }
1.712     albertel 10830:     }
                   10831:     return ();
                   10832: }
                   10833: 
1.1313    raeburn  10834: # --------------------------------------------------------- recursedirs
                   10835: # Recursive function to traverse either a specific user's Authoring Space
                   10836: # or corresponding Published Resource Space, and populate the hash ref:
                   10837: # $dirhashref with URLs of all directories, and if $filehashref hash
                   10838: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   10839: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   10840: # files in Authoring Space.
                   10841: #
                   10842: # Inputs:
                   10843: #
                   10844: # $is_home - true if current server is home server for user's space
                   10845: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   10846: # $docroot - Document root (i.e., /home/httpd/html
                   10847: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   10848: # $relpath - Current path (relative to top level).
                   10849: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   10850: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   10851: #
                   10852: # Returns: nothing
                   10853: #
                   10854: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   10855: #
                   10856: # Currently used by interface/londocs.pm to create linked select boxes for
                   10857: # directory and filename to import a Course "Author" resource into a course, and
                   10858: # also to create linked select boxes for Authoring Space and Directory to choose
                   10859: # save location for creation of a new "standard" problem from the Course Editor.
                   10860: #
                   10861: 
                   10862: sub recursedirs {
                   10863:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   10864:     return unless (ref($dirhashref) eq 'HASH');
                   10865:     my $currpath = $docroot.$toppath;
                   10866:     if ($relpath) {
                   10867:         $currpath .= "/$relpath";
                   10868:     }
                   10869:     my $savefile;
                   10870:     if (ref($filehashref)) {
                   10871:         $savefile = 1;
                   10872:     }
                   10873:     if ($is_home) {
                   10874:         if (opendir(my $dirh,$currpath)) {
                   10875:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   10876:                 next if ($item eq '');
                   10877:                 if (-d "$currpath/$item") {
                   10878:                     my $newpath;
                   10879:                     if ($relpath) {
                   10880:                         $newpath = "$relpath/$item";
                   10881:                     } else {
                   10882:                         $newpath = $item;
                   10883:                     }
                   10884:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10885:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10886:                 } elsif ($savefile) {
                   10887:                     if ($context eq 'priv') {
                   10888:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10889:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10890:                         }
                   10891:                     } else {
                   10892:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   10893:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10894:                         }
                   10895:                     }
                   10896:                 }
                   10897:             }
                   10898:             closedir($dirh);
                   10899:         }
                   10900:     } else {
                   10901:         my ($dirlistref,$listerror) =
                   10902:             &dirlist($toppath.$relpath);
                   10903:         my @dir_lines;
                   10904:         my $dirptr=16384;
                   10905:         if (ref($dirlistref) eq 'ARRAY') {
                   10906:             foreach my $dir_line (sort
                   10907:                               {
                   10908:                                   my ($afile)=split('&',$a,2);
                   10909:                                   my ($bfile)=split('&',$b,2);
                   10910:                                   return (lc($afile) cmp lc($bfile));
                   10911:                               } (@{$dirlistref})) {
                   10912:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   10913:                     split(/\&/,$dir_line,16);
                   10914:                 $item =~ s/\s+$//;
                   10915:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   10916:                 if ($dirptr&$testdir) {
                   10917:                     my $newpath;
                   10918:                     if ($relpath) {
                   10919:                         $newpath = "$relpath/$item";
                   10920:                     } else {
                   10921:                         $relpath = '/';
                   10922:                         $newpath = $item;
                   10923:                     }
                   10924:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10925:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10926:                 } elsif ($savefile) {
                   10927:                     if ($context eq 'priv') {
                   10928:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10929:                             $filehashref->{$relpath}{$item} = 1;
                   10930:                         }
                   10931:                     } else {
                   10932:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   10933:                             $filehashref->{$relpath}{$item} = 1;
                   10934:                         }
                   10935:                     }
                   10936:                 }
                   10937:             }
                   10938:         }
                   10939:     }
                   10940:     return;
                   10941: }
                   10942: 
1.26      www      10943: # -------------------------------------------------------- Value of a Condition
                   10944: 
1.713     albertel 10945: # gets the value of a specific preevaluated condition
                   10946: #    stored in the string  $env{user.state.<cid>}
                   10947: # or looks up a condition reference in the bighash and if if hasn't
                   10948: # already been evaluated recurses into docondval to get the value of
                   10949: # the condition, then memoizing it to 
                   10950: #   $env{user.state.<cid>.<condition>}
1.40      www      10951: sub directcondval {
                   10952:     my $number=shift;
1.620     albertel 10953:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10954: 	&Apache::lonuserstate::evalstate();
                   10955:     }
1.713     albertel 10956:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10957: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10958:     } elsif ($number =~ /^_/) {
                   10959: 	my $sub_condition;
                   10960: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10961: 		&GDBM_READER(),0640)) {
                   10962: 	    $sub_condition=$bighash{'conditions'.$number};
                   10963: 	    untie(%bighash);
                   10964: 	}
                   10965: 	my $value = &docondval($sub_condition);
1.949     raeburn  10966: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10967: 	return $value;
                   10968:     }
1.620     albertel 10969:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10970:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10971:     } else {
                   10972:        return 2;
                   10973:     }
                   10974: }
                   10975: 
1.713     albertel 10976: # get the collection of conditions for this resource
1.26      www      10977: sub condval {
                   10978:     my $condidx=shift;
1.54      www      10979:     my $allpathcond='';
1.713     albertel 10980:     foreach my $cond (split(/\|/,$condidx)) {
                   10981: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10982: 	    $allpathcond.=
                   10983: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10984: 	}
1.191     harris41 10985:     }
1.54      www      10986:     $allpathcond=~s/\|$//;
1.713     albertel 10987:     return &docondval($allpathcond);
                   10988: }
                   10989: 
                   10990: #evaluates an expression of conditions
                   10991: sub docondval {
                   10992:     my ($allpathcond) = @_;
                   10993:     my $result=0;
                   10994:     if ($env{'request.course.id'}
                   10995: 	&& defined($allpathcond)) {
                   10996: 	my $operand='|';
                   10997: 	my @stack;
                   10998: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10999: 	    if ($chunk eq '(') {
                   11000: 		push @stack,($operand,$result);
                   11001: 	    } elsif ($chunk eq ')') {
                   11002: 		my $before=pop @stack;
                   11003: 		if (pop @stack eq '&') {
                   11004: 		    $result=$result>$before?$before:$result;
                   11005: 		} else {
                   11006: 		    $result=$result>$before?$result:$before;
                   11007: 		}
                   11008: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11009: 		$operand=$chunk;
                   11010: 	    } else {
                   11011: 		my $new=directcondval($chunk);
                   11012: 		if ($operand eq '&') {
                   11013: 		    $result=$result>$new?$new:$result;
                   11014: 		} else {
                   11015: 		    $result=$result>$new?$result:$new;
                   11016: 		}
                   11017: 	    }
                   11018: 	}
1.26      www      11019:     }
                   11020:     return $result;
1.421     albertel 11021: }
                   11022: 
                   11023: # ---------------------------------------------------- Devalidate courseresdata
                   11024: 
                   11025: sub devalidatecourseresdata {
                   11026:     my ($coursenum,$coursedomain)=@_;
                   11027:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11028:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11029: }
                   11030: 
1.763     www      11031: 
1.200     www      11032: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11033: #
                   11034: #  Parameters:
                   11035: #      $coursenum    - Number of the course.
                   11036: #      $coursedomain - Domain at which the course was created.
                   11037: #  Returns:
                   11038: #     A hash of the course parameters along (I think) with timestamps
                   11039: #     and version info.
1.877     foxr     11040: 
1.624     albertel 11041: sub get_courseresdata {
                   11042:     my ($coursenum,$coursedomain)=@_;
1.200     www      11043:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11044:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11045:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11046:     my %dumpreply;
1.417     albertel 11047:     unless (defined($cached)) {
1.624     albertel 11048: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11049: 	$result=\%dumpreply;
1.251     albertel 11050: 	my ($tmp) = keys(%dumpreply);
                   11051: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11052: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11053: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11054: 	    return $tmp;
1.416     albertel 11055: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11056: 	    $result=undef;
1.599     albertel 11057: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11058: 	}
                   11059:     }
1.624     albertel 11060:     return $result;
                   11061: }
                   11062: 
1.633     albertel 11063: sub devalidateuserresdata {
                   11064:     my ($uname,$udom)=@_;
                   11065:     my $hashid="$udom:$uname";
                   11066:     &devalidate_cache_new('userres',$hashid);
                   11067: }
                   11068: 
1.624     albertel 11069: sub get_userresdata {
                   11070:     my ($uname,$udom)=@_;
                   11071:     #most student don\'t have any data set, check if there is some data
                   11072:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11073: 
                   11074:     my $hashid="$udom:$uname";
                   11075:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11076:     if (!defined($cached)) {
                   11077: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11078: 	$result=\%resourcedata;
                   11079: 	&do_cache_new('userres',$hashid,$result,600);
                   11080:     }
                   11081:     my ($tmp)=keys(%$result);
                   11082:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11083: 	return $result;
                   11084:     }
                   11085:     #error 2 occurs when the .db doesn't exist
                   11086:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  11087:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11088: 	    &logthis("<font color=\"blue\">WARNING:".
                   11089: 		     " Trying to get resource data for ".
                   11090: 		     $uname." at ".$udom.": ".
                   11091: 		     $tmp."</font>");
                   11092:         }
1.624     albertel 11093:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11094: 	#&EXT_cache_set($udom,$uname);
                   11095: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11096: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11097:     }
                   11098:     return $tmp;
                   11099: }
1.879     foxr     11100: #----------------------------------------------- resdata - return resource data
                   11101: #  Purpose:
                   11102: #    Return resource data for either users or for a course.
                   11103: #  Parameters:
                   11104: #     $name      - Course/user name.
                   11105: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  11106: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  11107: #     $mapp      - decluttered URL of enclosing map  
                   11108: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   11109: #     $recurseup - Ref to array of map URLs, starting with map containing
                   11110: #                  $mapp up through hierarchy of nested maps to top level map.  
                   11111: #     $courseid  - CourseID (first part of param identifier).
                   11112: #     $modifier  - Middle part of param identifier.
                   11113: #     $what      - Last part of param identifier.
1.879     foxr     11114: #     @which     - Array of names of resources desired.
                   11115: #  Returns:
                   11116: #     The value of the first reasource in @which that is found in the
                   11117: #     resource hash.
                   11118: #  Exceptional Conditions:
                   11119: #     If the $type passed in is not valid (not the string 'course' or 
                   11120: #     'user', an undefined  reference is returned.
                   11121: #     If none of the resources are found, an undef is returned
1.624     albertel 11122: sub resdata {
1.1301    raeburn  11123:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   11124:         $modifier,$what,@which)=@_;
1.624     albertel 11125:     my $result;
                   11126:     if ($type eq 'course') {
                   11127: 	$result=&get_courseresdata($name,$domain);
                   11128:     } elsif ($type eq 'user') {
                   11129: 	$result=&get_userresdata($name,$domain);
                   11130:     }
                   11131:     if (!ref($result)) { return $result; }    
1.251     albertel 11132:     foreach my $item (@which) {
1.1301    raeburn  11133:         if ($item->[1] eq 'course') {
                   11134:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   11135:                 unless ($$recursed) {
1.1302    raeburn  11136:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  11137:                     $$recursed = 1;
                   11138:                 }
                   11139:                 foreach my $item (@${recurseup}) {
                   11140:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   11141:                     last if (defined($result->{$norecursechk}));
                   11142:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   11143:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   11144:                 }
                   11145:             }
                   11146:         }
                   11147:         if (defined($result->{$item->[0]})) {
1.927     albertel 11148: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11149: 	}
1.250     albertel 11150:     }
1.291     albertel 11151:     return undef;
1.200     www      11152: }
                   11153: 
1.1360  ! raeburn  11154: sub get_domain_lti {
        !          11155:     my ($cdom,$context) = @_;
        !          11156:     my ($name,%lti);
        !          11157:     if ($context eq 'consumer') {
        !          11158:         $name = 'ltitools';
        !          11159:     } elsif ($context eq 'provider') {
        !          11160:         $name = 'lti';
        !          11161:     } else {
        !          11162:         return %lti;
        !          11163:     }
        !          11164:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  11165:     if (defined($cached)) {
                   11166:         if (ref($result) eq 'HASH') {
1.1360  ! raeburn  11167:             %lti = %{$result};
1.1298    raeburn  11168:         }
                   11169:     } else {
1.1360  ! raeburn  11170:         my %domconfig = &get_dom('configuration',[$name],$cdom);
        !          11171:         if (ref($domconfig{$name}) eq 'HASH') {
        !          11172:             %lti = %{$domconfig{$name}};
        !          11173:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
        !          11174:             if (ref($encdomconfig{$name}) eq 'HASH') {
        !          11175:                 foreach my $id (keys(%lti)) {
        !          11176:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  11177:                         foreach my $item ('key','secret') {
1.1360  ! raeburn  11178:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  11179:                         }
                   11180:                     }
                   11181:                 }
                   11182:             }
1.1298    raeburn  11183:         }
                   11184:         my $cachetime = 24*60*60;
1.1360  ! raeburn  11185:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  11186:     }
1.1360  ! raeburn  11187:     return %lti;
1.1298    raeburn  11188: }
                   11189: 
1.1236    raeburn  11190: sub get_numsuppfiles {
                   11191:     my ($cnum,$cdom,$ignorecache)=@_;
                   11192:     my $hashid=$cnum.':'.$cdom;
                   11193:     my ($suppcount,$cached);
                   11194:     unless ($ignorecache) {
                   11195:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11196:     }
                   11197:     unless (defined($cached)) {
                   11198:         my $chome=&homeserver($cnum,$cdom);
                   11199:         unless ($chome eq 'no_host') {
                   11200:             ($suppcount,my $errors) = (0,0);
                   11201:             my $suppmap = 'supplemental.sequence';
                   11202:             ($suppcount,$errors) = 
                   11203:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11204:         }
                   11205:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11206:     }
                   11207:     return $suppcount;
                   11208: }
                   11209: 
1.379     matthew  11210: #
                   11211: # EXT resource caching routines
                   11212: #
                   11213: 
1.1302    raeburn  11214: {
                   11215: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11216: #
                   11217: # The course for which we cache
                   11218: my $cachedmapkey='';
                   11219: # The cached recursive maps for this course
                   11220: my %cachedmaps=();
                   11221: # When this was last done
                   11222: my $cachedmaptime='';
                   11223: 
1.379     matthew  11224: sub clear_EXT_cache_status {
1.383     albertel 11225:     &delenv('cache.EXT.');
1.379     matthew  11226: }
                   11227: 
                   11228: sub EXT_cache_status {
                   11229:     my ($target_domain,$target_user) = @_;
1.383     albertel 11230:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11231:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11232:         # We know already the user has no data
                   11233:         return 1;
                   11234:     } else {
                   11235:         return 0;
                   11236:     }
                   11237: }
                   11238: 
                   11239: sub EXT_cache_set {
                   11240:     my ($target_domain,$target_user) = @_;
1.383     albertel 11241:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11242:     #&appenv({$cachename => time});
1.379     matthew  11243: }
                   11244: 
1.28      www      11245: # --------------------------------------------------------- Value of a Variable
1.58      www      11246: sub EXT {
1.715     albertel 11247: 
1.1228    raeburn  11248:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11249:     unless ($varname) { return ''; }
1.218     albertel 11250:     #get real user name/domain, courseid and symb
                   11251:     my $courseid;
1.359     albertel 11252:     my $publicuser;
1.427     www      11253:     if ($symbparm) {
                   11254: 	$symbparm=&get_symb_from_alias($symbparm);
                   11255:     }
1.218     albertel 11256:     if (!($uname && $udom)) {
1.790     albertel 11257:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11258:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11259:     } else {
1.620     albertel 11260: 	$courseid=$env{'request.course.id'};
1.218     albertel 11261:     }
1.48      www      11262:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11263:     my $rest;
1.320     albertel 11264:     if (defined($therest[0])) {
1.48      www      11265:        $rest=join('.',@therest);
                   11266:     } else {
                   11267:        $rest='';
                   11268:     }
1.320     albertel 11269: 
1.57      www      11270:     my $qualifierrest=$qualifier;
                   11271:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11272:     my $spacequalifierrest=$space;
                   11273:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11274:     if ($realm eq 'user') {
1.48      www      11275: # --------------------------------------------------------------- user.resource
                   11276: 	if ($space eq 'resource') {
1.651     albertel 11277: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11278: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11279: 		 &&
1.744     albertel 11280: 		 ($symbparm eq &symbread()) ) {	
                   11281: 		# if we are in the middle of processing the resource the
                   11282: 		# get the value we are planning on committing
                   11283:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11284:                     return $Apache::lonhomework::results{$qualifierrest};
                   11285:                 } else {
                   11286:                     return $Apache::lonhomework::history{$qualifierrest};
                   11287:                 }
1.335     albertel 11288: 	    } else {
1.359     albertel 11289: 		my %restored;
1.620     albertel 11290: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11291: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11292: 		} else {
                   11293: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11294: 		}
1.335     albertel 11295: 		return $restored{$qualifierrest};
                   11296: 	    }
1.48      www      11297: # ----------------------------------------------------------------- user.access
                   11298:         } elsif ($space eq 'access') {
1.218     albertel 11299: 	    # FIXME - not supporting calls for a specific user
1.48      www      11300:             return &allowed($qualifier,$rest);
                   11301: # ------------------------------------------ user.preferences, user.environment
                   11302:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11303: 	    if (($uname eq $env{'user.name'}) &&
                   11304: 		($udom eq $env{'user.domain'})) {
                   11305: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11306: 	    } else {
1.359     albertel 11307: 		my %returnhash;
                   11308: 		if (!$publicuser) {
                   11309: 		    %returnhash=&userenvironment($udom,$uname,
                   11310: 						 $qualifierrest);
                   11311: 		}
1.218     albertel 11312: 		return $returnhash{$qualifierrest};
                   11313: 	    }
1.48      www      11314: # ----------------------------------------------------------------- user.course
                   11315:         } elsif ($space eq 'course') {
1.218     albertel 11316: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11317:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11318: # ------------------------------------------------------------------- user.role
                   11319:         } elsif ($space eq 'role') {
1.218     albertel 11320: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11321:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11322:             if ($qualifier eq 'value') {
                   11323: 		return $role;
                   11324:             } elsif ($qualifier eq 'extent') {
                   11325:                 return $where;
                   11326:             }
                   11327: # ----------------------------------------------------------------- user.domain
                   11328:         } elsif ($space eq 'domain') {
1.218     albertel 11329:             return $udom;
1.48      www      11330: # ------------------------------------------------------------------- user.name
                   11331:         } elsif ($space eq 'name') {
1.218     albertel 11332:             return $uname;
1.48      www      11333: # ---------------------------------------------------- Any other user namespace
1.29      www      11334:         } else {
1.359     albertel 11335: 	    my %reply;
                   11336: 	    if (!$publicuser) {
                   11337: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11338: 	    }
                   11339: 	    return $reply{$qualifierrest};
1.48      www      11340:         }
1.236     www      11341:     } elsif ($realm eq 'query') {
                   11342: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11343:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11344: 						[$spacequalifierrest]);
1.620     albertel 11345: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11346:    } elsif ($realm eq 'request') {
1.48      www      11347: # ------------------------------------------------------------- request.browser
                   11348:         if ($space eq 'browser') {
1.1145    bisitz   11349:             return $env{'browser.'.$qualifier};
1.57      www      11350: # ------------------------------------------------------------ request.filename
                   11351:         } else {
1.620     albertel 11352:             return $env{'request.'.$spacequalifierrest};
1.29      www      11353:         }
1.28      www      11354:     } elsif ($realm eq 'course') {
1.48      www      11355: # ---------------------------------------------------------- course.description
1.620     albertel 11356:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11357:     } elsif ($realm eq 'resource') {
1.165     www      11358: 
1.620     albertel 11359: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11360: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11361: 	}
1.693     albertel 11362: 
1.1232    raeburn  11363:         if ($qualifier eq '') {
                   11364: 	    if ($space eq 'title') {
                   11365: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11366: 	        return &gettitle($symbparm);
                   11367: 	    }
1.693     albertel 11368: 	
1.1232    raeburn  11369: 	    if ($space eq 'map') {
                   11370: 	        my ($map) = &decode_symb($symbparm);
                   11371: 	        return &symbread($map);
                   11372: 	    }
                   11373:             if ($space eq 'maptitle') {
                   11374:                 my ($map) = &decode_symb($symbparm);
                   11375:                 return &gettitle($map);
                   11376:             }
                   11377: 	    if ($space eq 'filename') {
                   11378: 	        if ($symbparm) {
                   11379: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11380: 	        }
                   11381: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11382: 	    }
1.1232    raeburn  11383: 
1.1233    raeburn  11384:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11385:                 if ($space eq 'visibleparts') {
                   11386:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11387:                     my $item;
                   11388:                     if (ref($navmap)) {
                   11389:                         my $res = $navmap->getBySymb($symbparm);
                   11390:                         my $parts = $res->parts();
                   11391:                         if (ref($parts) eq 'ARRAY') {
                   11392:                             $item = join(',',@{$parts});
                   11393:                         }
                   11394:                         undef($navmap);
1.1232    raeburn  11395:                     }
1.1233    raeburn  11396:                     return $item;
1.1232    raeburn  11397:                 }
                   11398:             }
                   11399:         }
1.693     albertel 11400: 
1.1301    raeburn  11401: 	my ($section, $group, @groups, @recurseup, $recursed);
                   11402: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  11403:         if (($courseid eq '') && ($cid)) {
                   11404:             $courseid = $cid;
                   11405:         }
                   11406: 	if (($symbparm && $courseid) && 
                   11407: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      11408: 
1.218     albertel 11409: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11410: 
1.60      www      11411: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11412: 	    my $symbp=$symbparm;
1.1301    raeburn  11413: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11414: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  11415:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 11416: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 11417: 	    if (($env{'user.name'} eq $uname) &&
                   11418: 		($env{'user.domain'} eq $udom)) {
                   11419: 		$section=$env{'request.course.sec'};
1.733     raeburn  11420:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11421:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11422: 	    } else {
1.539     albertel 11423: 		if (! defined($usection)) {
1.551     albertel 11424: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11425: 		} else {
                   11426: 		    $section = $usection;
                   11427: 		}
1.733     raeburn  11428:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11429: 	    }
                   11430: 
                   11431: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11432: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  11433:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 11434: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11435: 
1.593     albertel 11436: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11437: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  11438:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 11439: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11440: 
1.60      www      11441: # ----------------------------------------------------------- first, check user
1.624     albertel 11442: 
1.1301    raeburn  11443: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   11444:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 11445: 				       ([$courselevelr,'resource'],
                   11446: 					[$courselevelm,'map'     ],
1.1301    raeburn  11447:                                         [$courseleveli,'map'     ],
1.927     albertel 11448: 					[$courselevel, 'course'  ]));
1.931     albertel 11449: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11450: 
1.594     albertel 11451: # ------------------------------------------------ second, check some of course
1.684     raeburn  11452:             my $coursereply;
1.691     raeburn  11453:             if (@groups > 0) {
                   11454:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  11455:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   11456:                                        $mapp,\$recursed,\@recurseup);
                   11457:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  11458:             }
1.96      www      11459: 
1.684     raeburn  11460: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11461: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11462: 				  'course',$mapp,\$recursed,\@recurseup,
                   11463:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 11464: 				  ([$seclevelr,   'resource'],
                   11465: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  11466:                                    [$secleveli,   'map'     ],
1.927     albertel 11467: 				   [$seclevel,    'course'  ],
                   11468: 				   [$courselevelr,'resource']));
                   11469: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11470: 
1.60      www      11471: # ------------------------------------------------------ third, check map parms
1.218     albertel 11472: 	    my %parmhash=();
                   11473: 	    my $thisparm='';
                   11474: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11475: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11476: 		    &GDBM_READER(),0640)) {
1.218     albertel 11477: 		$thisparm=$parmhash{$symbparm};
                   11478: 		untie(%parmhash);
                   11479: 	    }
1.927     albertel 11480: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11481: 	}
1.594     albertel 11482: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  11483:  
                   11484:         my $what = $spacequalifierrest;
                   11485: 	$what=~s/\./\_/;
1.282     albertel 11486: 	my $filename;
                   11487: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11488: 	if ($symbparm) {
1.409     www      11489: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11490: 	} else {
1.620     albertel 11491: 	    $filename=$env{'request.filename'};
1.282     albertel 11492: 	}
1.1301    raeburn  11493: 	my $metadata=&metadata($filename,$what);
1.927     albertel 11494: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301    raeburn  11495: 	$metadata=&metadata($filename,'parameter_'.$what);
1.927     albertel 11496: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11497: 
1.1301    raeburn  11498: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 11499: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11500: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11501: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11502: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11503: 				     'course',$mapp,\$recursed,\@recurseup,
                   11504:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 11505: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  11506:                                       [$courseleveli,'map'   ],
1.927     albertel 11507: 				      [$courselevel, 'course']));
                   11508: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11509: 	}
1.145     www      11510: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11511: 	unless ($space eq '0') {
1.336     albertel 11512: 	    my @parts=split(/_/,$space);
                   11513: 	    my $id=pop(@parts);
                   11514: 	    my $part=join('_',@parts);
                   11515: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11516: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11517: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11518: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11519: 	}
1.395     albertel 11520: 	if ($recurse) { return undef; }
                   11521: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11522: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11523: # ---------------------------------------------------- Any other user namespace
                   11524:     } elsif ($realm eq 'environment') {
                   11525: # ----------------------------------------------------------------- environment
1.620     albertel 11526: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11527: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11528: 	} else {
1.770     albertel 11529: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11530: 		return '';
                   11531: 	    }
1.219     albertel 11532: 	    my %returnhash=&userenvironment($udom,$uname,
                   11533: 					    $spacequalifierrest);
                   11534: 	    return $returnhash{$spacequalifierrest};
                   11535: 	}
1.28      www      11536:     } elsif ($realm eq 'system') {
1.48      www      11537: # ----------------------------------------------------------------- system.time
                   11538: 	if ($space eq 'time') {
                   11539: 	    return time;
                   11540:         }
1.696     albertel 11541:     } elsif ($realm eq 'server') {
                   11542: # ----------------------------------------------------------------- system.time
                   11543: 	if ($space eq 'name') {
                   11544: 	    return $ENV{'SERVER_NAME'};
                   11545:         }
1.28      www      11546:     }
1.48      www      11547:     return '';
1.61      www      11548: }
                   11549: 
1.927     albertel 11550: sub get_reply {
                   11551:     my ($reply_value) = @_;
1.940     raeburn  11552:     if (ref($reply_value) eq 'ARRAY') {
                   11553:         if (wantarray) {
                   11554: 	    return @$reply_value;
                   11555:         }
                   11556:         return $reply_value->[0];
                   11557:     } else {
                   11558:         return $reply_value;
1.927     albertel 11559:     }
                   11560: }
                   11561: 
1.691     raeburn  11562: sub check_group_parms {
1.1301    raeburn  11563:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   11564:         $recursed,$recurseupref) = @_;
                   11565:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   11566:                   [$what,'course']);
                   11567:     my $coursereply;
1.691     raeburn  11568:     foreach my $group (@{$groups}) {
1.1301    raeburn  11569:         my @groupitems = ();
1.691     raeburn  11570:         foreach my $level (@levels) {
1.927     albertel 11571:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11572:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11573:         }
1.1301    raeburn  11574:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11575:                                    $env{'course.'.$courseid.'.domain'},
                   11576:                                    'course',$mapp,$recursed,$recurseupref,
                   11577:                                    $courseid,'.['.$group.'].',$what,
                   11578:                                    @groupitems);
                   11579:         last if (defined($coursereply));
1.691     raeburn  11580:     }
                   11581:     return $coursereply;
                   11582: }
                   11583: 
1.1301    raeburn  11584: sub get_map_hierarchy {
1.1302    raeburn  11585:     my ($mapname,$courseid) = @_;
                   11586:     my @recurseup = ();
1.1301    raeburn  11587:     if ($mapname) {
1.1302    raeburn  11588:         if (($cachedmapkey eq $courseid) &&
                   11589:             (abs($cachedmaptime-time)<5)) {
                   11590:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11591:                 return @{$cachedmaps{$mapname}};
                   11592:             }
                   11593:         }
1.1301    raeburn  11594:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11595:         if (ref($navmap)) {
                   11596:             @recurseup = $navmap->recurseup_maps($mapname);
                   11597:             undef($navmap);
1.1302    raeburn  11598:             $cachedmaps{$mapname} = \@recurseup;
                   11599:             $cachedmaptime=time;
                   11600:             $cachedmapkey=$courseid;
1.1301    raeburn  11601:         }
                   11602:     }
                   11603:     return @recurseup;
                   11604: }
                   11605: 
1.1302    raeburn  11606: }
                   11607: 
1.691     raeburn  11608: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11609:     my ($courseid,@groups) = @_;
                   11610:     @groups = sort(@groups);
1.691     raeburn  11611:     return @groups;
                   11612: }
                   11613: 
1.395     albertel 11614: sub packages_tab_default {
                   11615:     my ($uri,$varname)=@_;
                   11616:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11617: 
                   11618:     my (@extension,@specifics,$do_default);
                   11619:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11620: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11621: 	if ($pack_type eq 'default') {
                   11622: 	    $do_default=1;
                   11623: 	} elsif ($pack_type eq 'extension') {
                   11624: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11625: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11626: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11627: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11628: 	}
                   11629:     }
                   11630:     # first look for a package that matches the requested part id
                   11631:     foreach my $package (@specifics) {
                   11632: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11633: 	next if ($pack_part ne $part);
                   11634: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11635: 	    return $packagetab{"$pack_type&$name&default"};
                   11636: 	}
                   11637:     }
                   11638:     # look for any possible matching non extension_ package
                   11639:     foreach my $package (@specifics) {
                   11640: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11641: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11642: 	    return $packagetab{"$pack_type&$name&default"};
                   11643: 	}
1.585     albertel 11644: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11645: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11646: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11647: 	}
                   11648:     }
1.738     albertel 11649:     # look for any posible extension_ match
                   11650:     foreach my $package (@extension) {
                   11651: 	my ($package,$pack_type)=@{$package};
                   11652: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11653: 	    return $packagetab{"$pack_type&$name&default"};
                   11654: 	}
                   11655: 	if (defined($packagetab{$package."&$name&default"})) {
                   11656: 	    return $packagetab{$package."&$name&default"};
                   11657: 	}
                   11658:     }
                   11659:     # look for a global default setting
                   11660:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11661: 	return $packagetab{"default&$name&default"};
                   11662:     }
1.395     albertel 11663:     return undef;
                   11664: }
                   11665: 
1.334     albertel 11666: sub add_prefix_and_part {
                   11667:     my ($prefix,$part)=@_;
                   11668:     my $keyroot;
                   11669:     if (defined($prefix) && $prefix !~ /^__/) {
                   11670: 	# prefix that has a part already
                   11671: 	$keyroot=$prefix;
                   11672:     } elsif (defined($prefix)) {
                   11673: 	# prefix that is missing a part
                   11674: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11675:     } else {
                   11676: 	# no prefix at all
                   11677: 	if (defined($part)) { $keyroot='_'.$part; }
                   11678:     }
                   11679:     return $keyroot;
                   11680: }
                   11681: 
1.71      www      11682: # ---------------------------------------------------------------- Get metadata
                   11683: 
1.599     albertel 11684: my %metaentry;
1.1070    www      11685: my %importedpartids;
1.71      www      11686: sub metadata {
1.176     www      11687:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11688:     $uri=&declutter($uri);
1.288     albertel 11689:     # if it is a non metadata possible uri return quickly
1.529     albertel 11690:     if (($uri eq '') || 
                   11691: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  11692: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11693:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11694: 	return undef;
                   11695:     }
1.1261    raeburn  11696:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11697: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11698: 	return undef;
1.288     albertel 11699:     }
1.73      www      11700:     my $filename=$uri;
                   11701:     $uri=~s/\.meta$//;
1.172     www      11702: #
                   11703: # Is the metadata already cached?
1.177     www      11704: # Look at timestamp of caching
1.172     www      11705: # Everything is cached by the main uri, libraries are never directly cached
                   11706: #
1.428     albertel 11707:     if (!defined($liburi)) {
1.599     albertel 11708: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11709: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11710:     }
                   11711:     {
1.1069    www      11712: # Imported parts would go here
1.1070    www      11713:         my %importedids=();
                   11714:         my @origfileimportpartids=();
1.1069    www      11715:         my $importedparts=0;
1.172     www      11716: #
                   11717: # Is this a recursive call for a library?
                   11718: #
1.599     albertel 11719: #	if (! exists($metacache{$uri})) {
                   11720: #	    $metacache{$uri}={};
                   11721: #	}
1.924     albertel 11722: 	my $cachetime = 60*60;
1.171     www      11723:         if ($liburi) {
                   11724: 	    $liburi=&declutter($liburi);
                   11725:             $filename=$liburi;
1.401     bowersj2 11726:         } else {
1.599     albertel 11727: 	    &devalidate_cache_new('meta',$uri);
                   11728: 	    undef(%metaentry);
1.401     bowersj2 11729: 	}
1.140     www      11730:         my %metathesekeys=();
1.73      www      11731:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11732: 	my $metastring;
1.1140    www      11733: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11734: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11735: 	    $metastring = 
1.929     albertel 11736: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11737: 					  ('grade_target' => 'meta'));
                   11738: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11739: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11740:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11741: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11742: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11743: 	    $metastring=&getfile($file);
1.489     albertel 11744: 	}
1.208     albertel 11745:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11746:         my $token;
1.140     www      11747:         undef %metathesekeys;
1.71      www      11748:         while ($token=$parser->get_token) {
1.339     albertel 11749: 	    if ($token->[0] eq 'S') {
                   11750: 		if (defined($token->[2]->{'package'})) {
1.172     www      11751: #
                   11752: # This is a package - get package info
                   11753: #
1.339     albertel 11754: 		    my $package=$token->[2]->{'package'};
                   11755: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11756: 		    if (defined($token->[2]->{'id'})) { 
                   11757: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11758: 		    }
1.599     albertel 11759: 		    if ($metaentry{':packages'}) {
                   11760: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11761: 		    } else {
1.599     albertel 11762: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11763: 		    }
1.736     albertel 11764: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11765: 			my $part=$keyroot;
                   11766: 			$part=~s/^\_//;
1.736     albertel 11767: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11768: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11769: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11770: 			    # ignore package.tab specified default values
                   11771:                             # here &package_tab_default() will fetch those
                   11772: 			    if ($subp eq 'default') { next; }
1.736     albertel 11773: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11774: 			    my $unikey;
                   11775: 			    if ($pack =~ /_0$/) {
                   11776: 				$unikey='parameter_0_'.$name;
                   11777: 				$part=0;
                   11778: 			    } else {
                   11779: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11780: 			    }
1.339     albertel 11781: 			    if ($subp eq 'display') {
                   11782: 				$value.=' [Part: '.$part.']';
                   11783: 			    }
1.599     albertel 11784: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11785: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11786: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11787: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11788: 			    }
1.599     albertel 11789: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11790: 				$metaentry{':'.$unikey}=
                   11791: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11792: 			    }
1.339     albertel 11793: 			}
                   11794: 		    }
                   11795: 		} else {
1.172     www      11796: #
                   11797: # This is not a package - some other kind of start tag
1.339     albertel 11798: #
                   11799: 		    my $entry=$token->[1];
1.1068    www      11800: 		    my $unikey='';
1.175     www      11801: 
1.339     albertel 11802: 		    if ($entry eq 'import') {
1.175     www      11803: #
                   11804: # Importing a library here
1.339     albertel 11805: #
1.1067    www      11806:                         my $location=$parser->get_text('/import');
                   11807:                         my $dir=$filename;
                   11808:                         $dir=~s|[^/]*$||;
                   11809:                         $location=&filelocation($dir,$location);
1.1069    www      11810:                        
1.1068    www      11811:                         my $importmode=$token->[2]->{'importmode'};
                   11812:                         if ($importmode eq 'problem') {
1.1069    www      11813: # Import as problem/response
1.1068    www      11814:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11815:                         } elsif ($importmode eq 'part') {
                   11816: # Import as part(s)
1.1069    www      11817:                            $importedparts=1;
                   11818: # We need to get the original file and the imported file to get the part order correct
                   11819: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   11820: # Load and inspect original file
1.1070    www      11821:                            if ($#origfileimportpartids<0) {
                   11822:                               undef(%importedpartids);
                   11823:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11824:                               my $origfile=&getfile($origfilelocation);
                   11825:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11826:                            }
                   11827: 
1.1069    www      11828: # Load and inspect imported file
                   11829:                            my $impfile=&getfile($location);
                   11830:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11831:                            if ($#impfilepartids>=0) {
                   11832: # This problem had parts
1.1070    www      11833:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11834:                            } else {
                   11835: # Importing by turning a single problem into a problem part
                   11836: # It gets the import-tags ID as part-ID
                   11837:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11838:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11839:                            }
1.1068    www      11840:                         } else {
                   11841: # Normal import
                   11842:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11843:                            if (defined($token->[2]->{'id'})) {
                   11844:                               $unikey.='_'.$token->[2]->{'id'};
                   11845:                            }
1.1067    www      11846:                         }
                   11847: 
1.339     albertel 11848: 			if ($depthcount<20) {
1.736     albertel 11849: 			    my $metadata = 
                   11850: 				&metadata($uri,'keys', $location,$unikey,
                   11851: 					  $depthcount+1);
                   11852: 			    foreach my $meta (split(',',$metadata)) {
                   11853: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11854: 				$metathesekeys{$meta}=1;
1.339     albertel 11855: 			    }
1.1068    www      11856: 			
                   11857:                         }
1.1067    www      11858: 		    } else {
                   11859: #
                   11860: # Not importing, some other kind of non-package, non-library start tag
                   11861: # 
                   11862:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11863:                         if (defined($token->[2]->{'id'})) {
                   11864:                             $unikey.='_'.$token->[2]->{'id'};
                   11865:                         }
1.339     albertel 11866: 			if (defined($token->[2]->{'name'})) { 
                   11867: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11868: 			}
                   11869: 			$metathesekeys{$unikey}=1;
1.736     albertel 11870: 			foreach my $param (@{$token->[3]}) {
                   11871: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11872: 				$token->[2]->{$param};
1.339     albertel 11873: 			}
                   11874: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11875: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11876: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11877: 		 # only ws inside the tag, and not in default, so use default
                   11878: 		 # as value
1.599     albertel 11879: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11880: 			} elsif ( $internaltext =~ /\S/ ) {
                   11881: 		  # something interesting inside the tag
                   11882: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11883: 			} else {
1.908     albertel 11884: 		  # no interesting values, don't set a default
1.339     albertel 11885: 			}
1.172     www      11886: # end of not-a-package not-a-library import
1.339     albertel 11887: 		    }
1.172     www      11888: # end of not-a-package start tag
1.339     albertel 11889: 		}
1.172     www      11890: # the next is the end of "start tag"
1.339     albertel 11891: 	    }
                   11892: 	}
1.483     albertel 11893: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11894: 	$extension = lc($extension);
                   11895: 	if ($extension eq 'htm') { $extension='html'; }
                   11896: 
1.737     albertel 11897: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11898: 	    #no specific packages #how's our extension
                   11899: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11900: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11901: 					 \%metathesekeys);
                   11902: 	}
1.883     albertel 11903: 
                   11904: 	if (!exists($metaentry{':packages'})
                   11905: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11906: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11907: 		#no specific packages well let's get default then
                   11908: 		if ($key!~/^default&/) { next; }
1.488     albertel 11909: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11910: 					     \%metathesekeys);
                   11911: 	    }
                   11912: 	}
1.338     www      11913: # are there custom rights to evaluate
1.599     albertel 11914: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11915: 
1.338     www      11916:     #
                   11917:     # Importing a rights file here
1.339     albertel 11918:     #
                   11919: 	    unless ($depthcount) {
1.599     albertel 11920: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11921: 		my $dir=$filename;
                   11922: 		$dir=~s|[^/]*$||;
                   11923: 		$location=&filelocation($dir,$location);
1.736     albertel 11924: 		my $rights_metadata =
                   11925: 		    &metadata($uri,'keys',$location,'_rights',
                   11926: 			      $depthcount+1);
                   11927: 		foreach my $rights (split(',',$rights_metadata)) {
                   11928: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11929: 		    $metathesekeys{$rights}=1;
1.339     albertel 11930: 		}
                   11931: 	    }
                   11932: 	}
1.737     albertel 11933: 	# uniqifiy package listing
                   11934: 	my %seen;
                   11935: 	my @uniq_packages =
                   11936: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11937: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11938: 
1.1070    www      11939:         if ($importedparts) {
                   11940: # We had imported parts and need to rebuild partorder
                   11941:            $metaentry{':partorder'}='';
                   11942:            $metathesekeys{'partorder'}=1;
                   11943:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   11944:                if ($origfileimportpartids[$index] eq 'part') {
                   11945: # original part, part of the problem
                   11946:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   11947:                } else {
                   11948: # we have imported parts at this position
                   11949:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   11950:                }
                   11951:            }
                   11952:            $metaentry{':partorder'}=~s/^\,//;
                   11953:         }
                   11954: 
1.737     albertel 11955: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11956: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  11957: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11958: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11959: # this is the end of "was not already recently cached
1.71      www      11960:     }
1.599     albertel 11961:     return $metaentry{':'.$what};
1.261     albertel 11962: }
                   11963: 
1.488     albertel 11964: sub metadata_create_package_def {
1.483     albertel 11965:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11966:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11967:     if ($subp eq 'default') { next; }
                   11968:     
1.599     albertel 11969:     if (defined($metaentry{':packages'})) {
                   11970: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11971:     } else {
1.599     albertel 11972: 	$metaentry{':packages'}=$package;
1.483     albertel 11973:     }
                   11974:     my $value=$packagetab{$key};
                   11975:     my $unikey;
                   11976:     $unikey='parameter_0_'.$name;
1.599     albertel 11977:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11978:     $$metathesekeys{$unikey}=1;
1.599     albertel 11979:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11980: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11981:     }
1.599     albertel 11982:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11983: 	$metaentry{':'.$unikey}=
                   11984: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11985:     }
                   11986: }
                   11987: 
1.261     albertel 11988: sub metadata_generate_part0 {
                   11989:     my ($metadata,$metacache,$uri) = @_;
                   11990:     my %allnames;
1.737     albertel 11991:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11992: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11993: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11994: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11995: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11996: 	    $allnames{$name}=$part;
                   11997: 	  }
                   11998: 	}
                   11999:     }
                   12000:     foreach my $name (keys(%allnames)) {
                   12001:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12002:       my $key=":parameter_0_$name";
1.261     albertel 12003:       $$metacache{"$key.part"}='0';
                   12004:       $$metacache{"$key.name"}=$name;
1.428     albertel 12005:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12006: 					   $allnames{$name}.'_'.$name.
                   12007: 					   '.type'};
1.428     albertel 12008:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12009: 			     '.display'};
1.644     www      12010:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12011:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12012:       $$metacache{"$key.display"}=$olddis;
                   12013:     }
1.71      www      12014: }
                   12015: 
1.764     albertel 12016: # ------------------------------------------------------ Devalidate title cache
                   12017: 
                   12018: sub devalidate_title_cache {
                   12019:     my ($url)=@_;
                   12020:     if (!$env{'request.course.id'}) { return; }
                   12021:     my $symb=&symbread($url);
                   12022:     if (!$symb) { return; }
                   12023:     my $key=$env{'request.course.id'}."\0".$symb;
                   12024:     &devalidate_cache_new('title',$key);
                   12025: }
                   12026: 
1.1014    droeschl 12027: # ------------------------------------------------- Get the title of a course
                   12028: 
                   12029: sub current_course_title {
                   12030:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12031: }
1.301     www      12032: # ------------------------------------------------- Get the title of a resource
                   12033: 
                   12034: sub gettitle {
                   12035:     my $urlsymb=shift;
                   12036:     my $symb=&symbread($urlsymb);
1.534     albertel 12037:     if ($symb) {
1.620     albertel 12038: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12039: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12040: 	if (defined($cached)) { 
                   12041: 	    return $result;
                   12042: 	}
1.534     albertel 12043: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12044: 	my $title='';
1.907     albertel 12045: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12046: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12047: 	} else {
                   12048: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12049: 		    &GDBM_READER(),0640)) {
                   12050: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12051: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12052: 		untie(%bighash);
                   12053: 	    }
1.534     albertel 12054: 	}
                   12055: 	$title=~s/\&colon\;/\:/gs;
                   12056: 	if ($title) {
1.1159    www      12057: # Remember both $symb and $title for dynamic metadata
                   12058:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12059:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12060: # Cache this title and then return it
1.599     albertel 12061: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12062: 	}
                   12063: 	$urlsymb=$url;
                   12064:     }
                   12065:     my $title=&metadata($urlsymb,'title');
                   12066:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12067:     return $title;
1.301     www      12068: }
1.613     albertel 12069: 
1.614     albertel 12070: sub get_slot {
                   12071:     my ($which,$cnum,$cdom)=@_;
                   12072:     if (!$cnum || !$cdom) {
1.790     albertel 12073: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12074: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12075: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12076:     }
1.703     albertel 12077:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12078:     my %slotinfo;
                   12079:     if (exists($remembered{$key})) {
                   12080: 	$slotinfo{$which} = $remembered{$key};
                   12081:     } else {
                   12082: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12083: 	&Apache::lonhomework::showhash(%slotinfo);
                   12084: 	my ($tmp)=keys(%slotinfo);
                   12085: 	if ($tmp=~/^error:/) { return (); }
                   12086: 	$remembered{$key} = $slotinfo{$which};
                   12087:     }
1.616     albertel 12088:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12089: 	return %{$slotinfo{$which}};
                   12090:     }
                   12091:     return $slotinfo{$which};
1.614     albertel 12092: }
1.1150    raeburn  12093: 
                   12094: sub get_reservable_slots {
                   12095:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12096:     my $now = time;
                   12097:     my $reservable_info;
                   12098:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12099:     if (exists($remembered{$key})) {
                   12100:         $reservable_info = $remembered{$key};
                   12101:     } else {
                   12102:         my %resv;
                   12103:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12104:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12105:         $reservable_info = \%resv;
                   12106:         $remembered{$key} = $reservable_info;
                   12107:     }
                   12108:     return $reservable_info;
                   12109: }
                   12110: 
                   12111: sub get_course_slots {
                   12112:     my ($cnum,$cdom) = @_;
                   12113:     my $hashid=$cnum.':'.$cdom;
                   12114:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12115:     if (defined($cached)) {
                   12116:         if (ref($result) eq 'HASH') {
                   12117:             return %{$result};
                   12118:         }
                   12119:     } else {
                   12120:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12121:         my ($tmp) = keys(%slots);
                   12122:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  12123:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12124:             return %slots;
                   12125:         }
                   12126:     }
                   12127:     return;
                   12128: }
                   12129: 
                   12130: sub devalidate_slots_cache {
                   12131:     my ($cnum,$cdom)=@_;
                   12132:     my $hashid=$cnum.':'.$cdom;
                   12133:     &devalidate_cache_new('allslots',$hashid);
                   12134: }
                   12135: 
1.1181    raeburn  12136: sub get_coursechange {
                   12137:     my ($cdom,$cnum) = @_;
                   12138:     if ($cdom eq '' || $cnum eq '') {
                   12139:         return unless ($env{'request.course.id'});
                   12140:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12141:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12142:     }
                   12143:     my $hashid=$cdom.'_'.$cnum;
                   12144:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12145:     if ((defined($cached)) && ($change ne '')) {
                   12146:         return $change;
                   12147:     } else {
                   12148:         my %crshash;
                   12149:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12150:         if ($crshash{'internal.contentchange'} eq '') {
                   12151:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12152:             if ($change eq '') {
                   12153:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12154:                 $change = $crshash{'internal.created'};
                   12155:             }
                   12156:         } else {
                   12157:             $change = $crshash{'internal.contentchange'};
                   12158:         }
                   12159:         my $cachetime = 600;
                   12160:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12161:     }
                   12162:     return $change;
                   12163: }
                   12164: 
                   12165: sub devalidate_coursechange_cache {
                   12166:     my ($cnum,$cdom)=@_;
                   12167:     my $hashid=$cnum.':'.$cdom;
                   12168:     &devalidate_cache_new('crschange',$hashid);
                   12169: }
                   12170: 
1.31      www      12171: # ------------------------------------------------- Update symbolic store links
                   12172: 
                   12173: sub symblist {
                   12174:     my ($mapname,%newhash)=@_;
1.438     www      12175:     $mapname=&deversion(&declutter($mapname));
1.31      www      12176:     my %hash;
1.620     albertel 12177:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12178:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12179:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12180: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12181: 		next if ($url eq 'last_known'
                   12182: 			 && $env{'form.no_update_last_known'});
                   12183: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12184: 						    $newhash{$url}->[1],
                   12185: 						    $newhash{$url}->[0]);
1.191     harris41 12186:             }
1.31      www      12187:             if (untie(%hash)) {
                   12188: 		return 'ok';
                   12189:             }
                   12190:         }
                   12191:     }
                   12192:     return 'error';
1.212     www      12193: }
                   12194: 
                   12195: # --------------------------------------------------------------- Verify a symb
                   12196: 
                   12197: sub symbverify {
1.1190    raeburn  12198:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12199:     my $thisfn=$thisurl;
1.439     www      12200:     $thisfn=&declutter($thisfn);
1.215     www      12201: # direct jump to resource in page or to a sequence - will construct own symbs
                   12202:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12203: # check URL part
1.409     www      12204:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12205: 
1.431     www      12206:     unless ($url eq $thisfn) { return 0; }
1.213     www      12207: 
1.216     www      12208:     $symb=&symbclean($symb);
1.510     www      12209:     $thisurl=&deversion($thisurl);
1.439     www      12210:     $thisfn=&deversion($thisfn);
1.213     www      12211: 
                   12212:     my %bighash;
                   12213:     my $okay=0;
1.431     www      12214: 
1.620     albertel 12215:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12216:                             &GDBM_READER(),0640)) {
1.1204    raeburn  12217:         my $noclutter;
1.1032    raeburn  12218:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12219:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  12220:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12221:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12222:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12223:                 $noclutter = 1;
                   12224:             }
                   12225:         }
                   12226:         my $ids;
                   12227:         if ($noclutter) {
                   12228:             $ids=$bighash{'ids_'.$thisurl};
                   12229:         } else {
                   12230:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12231:         }
1.1102    raeburn  12232:         unless ($ids) {
                   12233:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   12234:             $ids=$bighash{$idkey};
1.216     www      12235:         }
                   12236:         if ($ids) {
                   12237: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  12238:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  12239:                 $symb =~ s/\?.+$//;
1.1202    raeburn  12240:             }
1.800     albertel 12241: 	    foreach my $id (split(/\,/,$ids)) {
                   12242: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12243:                if (
                   12244:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  12245:    eq $symb) {
                   12246:                    if (ref($encstate)) {
                   12247:                        $$encstate = $bighash{'encrypted_'.$id};
                   12248:                    }
1.620     albertel 12249: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  12250: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   12251:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  12252: 		       $okay=1;
1.1202    raeburn  12253:                        last;
1.582     albertel 12254: 		   }
                   12255: 	       }
1.216     www      12256: 	   }
                   12257:         }
1.213     www      12258: 	untie(%bighash);
                   12259:     }
                   12260:     return $okay;
1.31      www      12261: }
                   12262: 
1.210     www      12263: # --------------------------------------------------------------- Clean-up symb
                   12264: 
                   12265: sub symbclean {
                   12266:     my $symb=shift;
1.568     albertel 12267:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12268: # remove version from map
                   12269:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12270: 
1.210     www      12271: # remove version from URL
                   12272:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12273: 
1.507     www      12274: # remove wrapper
                   12275: 
1.510     www      12276:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12277:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12278:     return $symb;
1.409     www      12279: }
                   12280: 
                   12281: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12282: 
                   12283: sub encode_symb {
                   12284:     my ($map,$resid,$url)=@_;
                   12285:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12286: }
1.409     www      12287: 
                   12288: sub decode_symb {
1.568     albertel 12289:     my $symb=shift;
                   12290:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12291:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12292:     return (&fixversion($map),$resid,&fixversion($url));
                   12293: }
                   12294: 
                   12295: sub fixversion {
                   12296:     my $fn=shift;
1.609     banghart 12297:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12298:     my %bighash;
                   12299:     my $uri=&clutter($fn);
1.620     albertel 12300:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12301: # is this cached?
1.599     albertel 12302:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12303:     if (defined($cached)) { return $result; }
                   12304: # unfortunately not cached, or expired
1.620     albertel 12305:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12306: 	    &GDBM_READER(),0640)) {
                   12307:  	if ($bighash{'version_'.$uri}) {
                   12308:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12309:  	    unless (($version eq 'mostrecent') || 
                   12310: 		    ($version==&getversion($uri))) {
1.440     www      12311:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12312:  	    }
                   12313:  	}
                   12314:  	untie %bighash;
1.413     www      12315:     }
1.599     albertel 12316:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12317: }
                   12318: 
                   12319: sub deversion {
                   12320:     my $url=shift;
                   12321:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12322:     return $url;
1.210     www      12323: }
                   12324: 
1.31      www      12325: # ------------------------------------------------------ Return symb list entry
                   12326: 
                   12327: sub symbread {
1.1282    raeburn  12328:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  12329:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  12330:     if (defined($env{$cache_str})) {
                   12331:         if ($ignorecachednull) {
                   12332:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12333:         } else {
                   12334:             return $env{$cache_str};
                   12335:         }
                   12336:     }
1.242     www      12337: # no filename provided? try from environment
1.1265    raeburn  12338:     unless ($thisfn) {
1.620     albertel 12339:         if ($env{'request.symb'}) {
                   12340: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 12341: 	}
1.620     albertel 12342: 	$thisfn=$env{'request.filename'};
1.44      www      12343:     }
1.569     albertel 12344:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12345: # is that filename actually a symb? Verify, clean, and return
                   12346:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12347: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12348: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12349: 	}
1.242     www      12350:     }
1.44      www      12351:     $thisfn=declutter($thisfn);
1.31      www      12352:     my %hash;
1.37      www      12353:     my %bighash;
                   12354:     my $syval='';
1.620     albertel 12355:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12356:         my $targetfn = $thisfn;
1.609     banghart 12357:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12358:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12359:         }
1.687     albertel 12360: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12361: 	    $targetfn=$1;
                   12362: 	}
1.620     albertel 12363:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12364:                       &GDBM_READER(),0640)) {
1.481     raeburn  12365: 	    $syval=$hash{$targetfn};
1.37      www      12366:             untie(%hash);
                   12367:         }
                   12368: # ---------------------------------------------------------- There was an entry
                   12369:         if ($syval) {
1.601     albertel 12370: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12371: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12372: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12373: 		    #return $env{$cache_str}='';
1.601     albertel 12374: 		#}    
                   12375: 		#$syval.=$1;
                   12376: 	    #}
1.37      www      12377:         } else {
                   12378: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12379:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12380:                             &GDBM_READER(),0640)) {
1.37      www      12381: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12382:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12383:               unless ($ids) { 
                   12384:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12385:               }
                   12386:               unless ($ids) {
                   12387: # alias?
                   12388: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12389:               }
1.37      www      12390:               if ($ids) {
                   12391: # ------------------------------------------------------------------- Has ID(s)
                   12392:                  my @possibilities=split(/\,/,$ids);
1.39      www      12393:                  if ($#possibilities==0) {
                   12394: # ----------------------------------------------- There is only one possibility
1.37      www      12395: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12396: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12397: 						    $resid,$thisfn);
1.1282    raeburn  12398:                      if (ref($possibles) eq 'HASH') {
                   12399:                          $possibles->{$syval} = 1;    
                   12400:                      }
                   12401:                      if ($checkforblock) {
                   12402:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12403:                          if (@blockers) {
                   12404:                              $syval = '';
                   12405:                              return;
                   12406:                          }
                   12407:                      }
                   12408:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      12409: # ------------------------------------------ There is more than one possibility
                   12410:                      my $realpossible=0;
1.800     albertel 12411:                      foreach my $id (@possibilities) {
                   12412: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  12413:                          my $canaccess;
                   12414:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12415:                              $canaccess = 1;
                   12416:                          } else { 
                   12417:                              $canaccess = &allowed('bre',$file);
                   12418:                          }
                   12419:                          if ($canaccess) {
                   12420:          		     my ($mapid,$resid)=split(/\./,$id);
                   12421:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12422:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12423: 						             $resid,$thisfn);
                   12424:                                  if (ref($possibles) eq 'HASH') {
                   12425:                                      $possibles->{$syval} = 1;
                   12426:                                  }
                   12427:                                  if ($checkforblock) {
                   12428:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12429:                                      unless (@blockers > 0) {
                   12430:                                          $syval = $poss_syval;
                   12431:                                          $realpossible++;
                   12432:                                      }
                   12433:                                  } else {
                   12434:                                      $syval = $poss_syval;
                   12435:                                      $realpossible++;
                   12436:                                  }
                   12437:                              }
1.39      www      12438: 			 }
1.191     harris41 12439:                      }
1.39      www      12440: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12441:                  } else {
                   12442:                      $syval='';
1.37      www      12443:                  }
                   12444: 	      }
1.1282    raeburn  12445:               untie(%bighash);
1.481     raeburn  12446:            }
1.31      www      12447:         }
1.62      www      12448:         if ($syval) {
1.620     albertel 12449: 	    return $env{$cache_str}=$syval;
1.62      www      12450:         }
1.31      www      12451:     }
1.949     raeburn  12452:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12453:     return $env{$cache_str}='';
1.31      www      12454: }
                   12455: 
                   12456: # ---------------------------------------------------------- Return random seed
                   12457: 
1.32      www      12458: sub numval {
                   12459:     my $txt=shift;
                   12460:     $txt=~tr/A-J/0-9/;
                   12461:     $txt=~tr/a-j/0-9/;
                   12462:     $txt=~tr/K-T/0-9/;
                   12463:     $txt=~tr/k-t/0-9/;
                   12464:     $txt=~tr/U-Z/0-5/;
                   12465:     $txt=~tr/u-z/0-5/;
                   12466:     $txt=~s/\D//g;
1.564     albertel 12467:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12468:     return int($txt);
1.368     albertel 12469: }
                   12470: 
1.484     albertel 12471: sub numval2 {
                   12472:     my $txt=shift;
                   12473:     $txt=~tr/A-J/0-9/;
                   12474:     $txt=~tr/a-j/0-9/;
                   12475:     $txt=~tr/K-T/0-9/;
                   12476:     $txt=~tr/k-t/0-9/;
                   12477:     $txt=~tr/U-Z/0-5/;
                   12478:     $txt=~tr/u-z/0-5/;
                   12479:     $txt=~s/\D//g;
                   12480:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12481:     my $total;
                   12482:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12483:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12484:     return int($total);
                   12485: }
                   12486: 
1.575     albertel 12487: sub numval3 {
                   12488:     use integer;
                   12489:     my $txt=shift;
                   12490:     $txt=~tr/A-J/0-9/;
                   12491:     $txt=~tr/a-j/0-9/;
                   12492:     $txt=~tr/K-T/0-9/;
                   12493:     $txt=~tr/k-t/0-9/;
                   12494:     $txt=~tr/U-Z/0-5/;
                   12495:     $txt=~tr/u-z/0-5/;
                   12496:     $txt=~s/\D//g;
                   12497:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12498:     my $total;
                   12499:     foreach my $val (@txts) { $total+=$val; }
                   12500:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12501:     return $total;
                   12502: }
                   12503: 
1.675     albertel 12504: sub digest {
                   12505:     my ($data)=@_;
                   12506:     my $digest=&Digest::MD5::md5($data);
                   12507:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12508:     my ($e,$f);
                   12509:     {
                   12510:         use integer;
                   12511:         $e=($a+$b);
                   12512:         $f=($c+$d);
                   12513:         if ($_64bit) {
                   12514:             $e=(($e<<32)>>32);
                   12515:             $f=(($f<<32)>>32);
                   12516:         }
                   12517:     }
                   12518:     if (wantarray) {
                   12519: 	return ($e,$f);
                   12520:     } else {
                   12521: 	my $g;
                   12522: 	{
                   12523: 	    use integer;
                   12524: 	    $g=($e+$f);
                   12525: 	    if ($_64bit) {
                   12526: 		$g=(($g<<32)>>32);
                   12527: 	    }
                   12528: 	}
                   12529: 	return $g;
                   12530:     }
                   12531: }
                   12532: 
1.368     albertel 12533: sub latest_rnd_algorithm_id {
1.675     albertel 12534:     return '64bit5';
1.366     albertel 12535: }
1.32      www      12536: 
1.503     albertel 12537: sub get_rand_alg {
                   12538:     my ($courseid)=@_;
1.790     albertel 12539:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12540:     if ($courseid) {
1.620     albertel 12541: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12542:     }
                   12543:     return &latest_rnd_algorithm_id();
                   12544: }
                   12545: 
1.562     albertel 12546: sub validCODE {
                   12547:     my ($CODE)=@_;
                   12548:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12549:     return 0;
                   12550: }
                   12551: 
1.491     albertel 12552: sub getCODE {
1.620     albertel 12553:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12554:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12555: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12556: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12557: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12558:     }
                   12559:     return undef;
                   12560: }
1.1133    foxr     12561: #
                   12562: #  Determines the random seed for a specific context:
                   12563: #
                   12564: # parameters:
                   12565: #   symb      - in course context the symb for the seed.
                   12566: #   course_id - The course id of the form domain_coursenum.
                   12567: #   domain    - Domain for the user.
                   12568: #   course    - Course for the user.
                   12569: #   cenv      - environment of the course.
                   12570: #
                   12571: # NOTE:
                   12572: #   All parameters are picked out of the environment if missing
                   12573: #   or not defined.
                   12574: #   If a symb cannot be determined the current time is used instead.
                   12575: #
                   12576: #  For a given well defined symb, courside, domain, username,
                   12577: #  and course environment, the seed is reproducible.
                   12578: #
1.31      www      12579: sub rndseed {
1.1133    foxr     12580:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12581:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12582:     if (!defined($symb)) {
1.366     albertel 12583: 	unless ($symb=$wsymb) { return time; }
                   12584:     }
1.1146    foxr     12585:     if (!defined $courseid) { 
                   12586: 	$courseid=$wcourseid; 
                   12587:     }
                   12588:     if (!defined $domain) { $domain=$wdomain; }
                   12589:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12590: 
                   12591:     my $which;
                   12592:     if (defined($cenv->{'rndseed'})) {
                   12593: 	$which = $cenv->{'rndseed'};
                   12594:     } else {
                   12595: 	$which =&get_rand_alg($courseid);
                   12596:     }
1.491     albertel 12597:     if (defined(&getCODE())) {
1.1133    foxr     12598: 
1.675     albertel 12599: 	if ($which eq '64bit5') {
                   12600: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12601: 	} elsif ($which eq '64bit4') {
1.575     albertel 12602: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12603: 	} else {
                   12604: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12605: 	}
1.675     albertel 12606:     } elsif ($which eq '64bit5') {
                   12607: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12608:     } elsif ($which eq '64bit4') {
                   12609: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12610:     } elsif ($which eq '64bit3') {
                   12611: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12612:     } elsif ($which eq '64bit2') {
                   12613: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12614:     } elsif ($which eq '64bit') {
                   12615: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12616:     }
                   12617:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12618: }
                   12619: 
                   12620: sub rndseed_32bit {
                   12621:     my ($symb,$courseid,$domain,$username)=@_;
                   12622:     {
                   12623: 	use integer;
                   12624: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12625: 	my $symbseed=numval($symb) << 22;
                   12626: 	my $namechck=unpack("%32C*",$username) << 17;
                   12627: 	my $nameseed=numval($username) << 12;
                   12628: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12629: 	my $courseseed=unpack("%32C*",$courseid);
                   12630: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12631: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12632: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12633: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12634: 	return $num;
                   12635:     }
                   12636: }
                   12637: 
                   12638: sub rndseed_64bit {
                   12639:     my ($symb,$courseid,$domain,$username)=@_;
                   12640:     {
                   12641: 	use integer;
                   12642: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12643: 	my $symbseed=numval($symb) << 10;
                   12644: 	my $namechck=unpack("%32S*",$username);
                   12645: 	
                   12646: 	my $nameseed=numval($username) << 21;
                   12647: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12648: 	my $courseseed=unpack("%32S*",$courseid);
                   12649: 	
                   12650: 	my $num1=$symbchck+$symbseed+$namechck;
                   12651: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12652: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12653: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12654: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12655: 	return "$num1,$num2";
1.155     albertel 12656:     }
1.366     albertel 12657: }
                   12658: 
1.443     albertel 12659: sub rndseed_64bit2 {
                   12660:     my ($symb,$courseid,$domain,$username)=@_;
                   12661:     {
                   12662: 	use integer;
                   12663: 	# strings need to be an even # of cahracters long, it it is odd the
                   12664:         # last characters gets thrown away
                   12665: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12666: 	my $symbseed=numval($symb) << 10;
                   12667: 	my $namechck=unpack("%32S*",$username.' ');
                   12668: 	
                   12669: 	my $nameseed=numval($username) << 21;
1.501     albertel 12670: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12671: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12672: 	
                   12673: 	my $num1=$symbchck+$symbseed+$namechck;
                   12674: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12675: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12676: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12677: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12678: 	return "$num1,$num2";
                   12679:     }
                   12680: }
                   12681: 
                   12682: sub rndseed_64bit3 {
                   12683:     my ($symb,$courseid,$domain,$username)=@_;
                   12684:     {
                   12685: 	use integer;
                   12686: 	# strings need to be an even # of cahracters long, it it is odd the
                   12687:         # last characters gets thrown away
                   12688: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12689: 	my $symbseed=numval2($symb) << 10;
                   12690: 	my $namechck=unpack("%32S*",$username.' ');
                   12691: 	
                   12692: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12693: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12694: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12695: 	
                   12696: 	my $num1=$symbchck+$symbseed+$namechck;
                   12697: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12698: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12699: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12700: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12701: 	
1.503     albertel 12702: 	return "$num1:$num2";
1.443     albertel 12703:     }
                   12704: }
                   12705: 
1.575     albertel 12706: sub rndseed_64bit4 {
                   12707:     my ($symb,$courseid,$domain,$username)=@_;
                   12708:     {
                   12709: 	use integer;
                   12710: 	# strings need to be an even # of cahracters long, it it is odd the
                   12711:         # last characters gets thrown away
                   12712: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12713: 	my $symbseed=numval3($symb) << 10;
                   12714: 	my $namechck=unpack("%32S*",$username.' ');
                   12715: 	
                   12716: 	my $nameseed=numval3($username) << 21;
                   12717: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12718: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12719: 	
                   12720: 	my $num1=$symbchck+$symbseed+$namechck;
                   12721: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12722: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12723: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12724: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12725: 	
1.575     albertel 12726: 	return "$num1:$num2";
                   12727:     }
                   12728: }
                   12729: 
1.675     albertel 12730: sub rndseed_64bit5 {
                   12731:     my ($symb,$courseid,$domain,$username)=@_;
                   12732:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12733:     return "$num1:$num2";
                   12734: }
                   12735: 
1.366     albertel 12736: sub rndseed_CODE_64bit {
                   12737:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12738:     {
1.366     albertel 12739: 	use integer;
1.443     albertel 12740: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12741: 	my $symbseed=numval2($symb);
1.491     albertel 12742: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12743: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12744: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12745: 	my $num1=$symbseed+$CODEchck;
                   12746: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12747: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12748: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12749: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12750: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12751: 	return "$num1:$num2";
1.366     albertel 12752:     }
                   12753: }
                   12754: 
1.575     albertel 12755: sub rndseed_CODE_64bit4 {
                   12756:     my ($symb,$courseid,$domain,$username)=@_;
                   12757:     {
                   12758: 	use integer;
                   12759: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12760: 	my $symbseed=numval3($symb);
                   12761: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12762: 	my $CODEseed=numval3(&getCODE());
                   12763: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12764: 	my $num1=$symbseed+$CODEchck;
                   12765: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12766: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12767: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12768: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12769: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12770: 	return "$num1:$num2";
                   12771:     }
                   12772: }
                   12773: 
1.675     albertel 12774: sub rndseed_CODE_64bit5 {
                   12775:     my ($symb,$courseid,$domain,$username)=@_;
                   12776:     my $code = &getCODE();
                   12777:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12778:     return "$num1:$num2";
                   12779: }
                   12780: 
1.366     albertel 12781: sub setup_random_from_rndseed {
                   12782:     my ($rndseed)=@_;
1.503     albertel 12783:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  12784:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12785:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12786:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12787:         } else {
                   12788:             &Math::Random::random_set_seed($num1,$num2);
                   12789:         }
1.366     albertel 12790:     } else {
                   12791: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12792:     }
1.36      albertel 12793: }
                   12794: 
1.474     albertel 12795: sub latest_receipt_algorithm_id {
1.835     albertel 12796:     return 'receipt3';
1.474     albertel 12797: }
                   12798: 
1.480     www      12799: sub recunique {
                   12800:     my $fucourseid=shift;
                   12801:     my $unique;
1.835     albertel 12802:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12803: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12804: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12805:     } else {
                   12806: 	$unique=$perlvar{'lonReceipt'};
                   12807:     }
                   12808:     return unpack("%32C*",$unique);
                   12809: }
                   12810: 
                   12811: sub recprefix {
                   12812:     my $fucourseid=shift;
                   12813:     my $prefix;
1.835     albertel 12814:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12815: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12816: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12817:     } else {
                   12818: 	$prefix=$perlvar{'lonHostID'};
                   12819:     }
                   12820:     return unpack("%32C*",$prefix);
                   12821: }
                   12822: 
1.76      www      12823: sub ireceipt {
1.474     albertel 12824:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12825: 
                   12826:     my $return =&recprefix($fucourseid).'-';
                   12827: 
                   12828:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12829: 	$env{'request.state'} eq 'construct') {
                   12830: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12831: 	return $return;
                   12832:     }
                   12833: 
1.76      www      12834:     my $cuname=unpack("%32C*",$funame);
                   12835:     my $cudom=unpack("%32C*",$fudom);
                   12836:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12837:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12838:     my $cunique=&recunique($fucourseid);
1.474     albertel 12839:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12840:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12841: 
1.790     albertel 12842: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12843: 			       
                   12844: 	$return.= ($cunique%$cuname+
                   12845: 		   $cunique%$cudom+
                   12846: 		   $cusymb%$cuname+
                   12847: 		   $cusymb%$cudom+
                   12848: 		   $cucourseid%$cuname+
                   12849: 		   $cucourseid%$cudom+
                   12850: 		   $cpart%$cuname+
                   12851: 		   $cpart%$cudom);
                   12852:     } else {
                   12853: 	$return.= ($cunique%$cuname+
                   12854: 		   $cunique%$cudom+
                   12855: 		   $cusymb%$cuname+
                   12856: 		   $cusymb%$cudom+
                   12857: 		   $cucourseid%$cuname+
                   12858: 		   $cucourseid%$cudom);
                   12859:     }
                   12860:     return $return;
1.76      www      12861: }
                   12862: 
                   12863: sub receipt {
1.474     albertel 12864:     my ($part)=@_;
1.790     albertel 12865:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12866:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12867: }
1.260     ng       12868: 
1.790     albertel 12869: sub whichuser {
                   12870:     my ($passedsymb)=@_;
                   12871:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12872:     if (defined($env{'form.grade_symb'})) {
                   12873: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12874: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12875: 	if (!$allowed &&
                   12876: 	    exists($env{'request.course.sec'}) &&
                   12877: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12878: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12879: 			      '/'.$env{'request.course.sec'});
                   12880: 	}
                   12881: 	if ($allowed) {
                   12882: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12883: 	    $courseid=$tmp_courseid;
                   12884: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12885: 	    ($name)=&get_env_multiple('form.grade_username');
                   12886: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12887: 	}
                   12888:     }
                   12889:     if (!$passedsymb) {
                   12890: 	$symb=&symbread();
                   12891:     } else {
                   12892: 	$symb=$passedsymb;
                   12893:     }
                   12894:     $courseid=$env{'request.course.id'};
                   12895:     $domain=$env{'user.domain'};
                   12896:     $name=$env{'user.name'};
                   12897:     if ($name eq 'public' && $domain eq 'public') {
                   12898: 	if (!defined($env{'form.username'})) {
                   12899: 	    $env{'form.username'}.=time.rand(10000000);
                   12900: 	}
                   12901: 	$name.=$env{'form.username'};
                   12902:     }
                   12903:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12904: 
                   12905: }
                   12906: 
1.36      albertel 12907: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12908: # returns either the contents of the file or 
                   12909: # -1 if the file doesn't exist
1.481     raeburn  12910: #
                   12911: # if the target is a file that was uploaded via DOCS, 
                   12912: # a check will be made to see if a current copy exists on the local server,
                   12913: # if it does this will be served, otherwise a copy will be retrieved from
                   12914: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12915: # the local server.   
1.472     albertel 12916: 
1.36      albertel 12917: sub getfile {
1.538     albertel 12918:     my ($file) = @_;
1.609     banghart 12919:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12920:     &repcopy($file);
                   12921:     return &readfile($file);
                   12922: }
                   12923: 
                   12924: sub repcopy_userfile {
                   12925:     my ($file)=@_;
1.1142    raeburn  12926:     my $londocroot = $perlvar{'lonDocRoot'};
                   12927:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12928:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12929:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12930: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12931:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12932:     if (-e "$file") {
1.828     www      12933: # we already have a local copy, check it out
1.538     albertel 12934: 	my @fileinfo = stat($file);
1.828     www      12935: 	my $rtncode;
                   12936: 	my $info;
1.538     albertel 12937: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12938: 	if ($lwpresp ne 'ok') {
1.828     www      12939: # there is no such file anymore, even though we had a local copy
1.482     albertel 12940: 	    if ($rtncode eq '404') {
1.538     albertel 12941: 		unlink($file);
1.482     albertel 12942: 	    }
                   12943: 	    return -1;
                   12944: 	}
                   12945: 	if ($info < $fileinfo[9]) {
1.828     www      12946: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12947: 	    return 'ok';
1.828     www      12948: 	} else {
                   12949: # the file is outdated, get rid of it
                   12950: 	    unlink($file);
1.482     albertel 12951: 	}
1.828     www      12952:     }
                   12953: # one way or the other, at this point, we don't have the file
                   12954: # construct the correct path for the file
                   12955:     my @parts = ($cdom,$cnum); 
                   12956:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12957: 	push @parts, split(/\//,$1);
                   12958:     }
                   12959:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12960:     foreach my $part (@parts) {
                   12961: 	$path .= '/'.$part;
                   12962: 	if (!-e $path) {
                   12963: 	    mkdir($path,0770);
1.482     albertel 12964: 	}
                   12965:     }
1.828     www      12966: # now the path exists for sure
                   12967: # get a user agent
                   12968:     my $transferfile=$file.'.in.transfer';
                   12969: # FIXME: this should flock
                   12970:     if (-e $transferfile) { return 'ok'; }
                   12971:     my $request;
                   12972:     $uri=~s/^\///;
1.980     raeburn  12973:     my $homeserver = &homeserver($cnum,$cdom);
                   12974:     my $protocol = $protocol{$homeserver};
                   12975:     $protocol = 'http' if ($protocol ne 'https');
                   12976:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.1345    raeburn  12977:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      12978: # did it work?
                   12979:     if ($response->is_error()) {
                   12980: 	unlink($transferfile);
                   12981: 	&logthis("Userfile repcopy failed for $uri");
                   12982: 	return -1;
                   12983:     }
                   12984: # worked, rename the transfer file
                   12985:     rename($transferfile,$file);
1.607     raeburn  12986:     return 'ok';
1.481     raeburn  12987: }
                   12988: 
1.517     albertel 12989: sub tokenwrapper {
                   12990:     my $uri=shift;
1.980     raeburn  12991:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12992:     $uri=~s|^/||;
1.620     albertel 12993:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12994:     my $token=$1;
1.552     albertel 12995:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12996:     if ($udom && $uname && $file) {
                   12997: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12998:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12999:         my $homeserver = &homeserver($uname,$udom);
                   13000:         my $protocol = $protocol{$homeserver};
                   13001:         $protocol = 'http' if ($protocol ne 'https');
                   13002:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 13003:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13004:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13005:     } else {
                   13006:         return '/adm/notfound.html';
                   13007:     }
                   13008: }
                   13009: 
1.828     www      13010: # call with reqtype HEAD: get last modification time
                   13011: # call with reqtype GET: get the file contents
                   13012: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13013: #
1.481     raeburn  13014: sub getuploaded {
                   13015:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13016:     $uri=~s/^\///;
1.980     raeburn  13017:     my $homeserver = &homeserver($cnum,$cdom);
                   13018:     my $protocol = $protocol{$homeserver};
                   13019:     $protocol = 'http' if ($protocol ne 'https');
                   13020:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  13021:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  13022:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  13023:     $$rtncode = $response->code;
1.482     albertel 13024:     if (! $response->is_success()) {
                   13025: 	return 'failed';
                   13026:     }      
                   13027:     if ($reqtype eq 'HEAD') {
1.486     www      13028: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13029:     } elsif ($reqtype eq 'GET') {
                   13030: 	$$info = $response->content;
1.472     albertel 13031:     }
1.482     albertel 13032:     return 'ok';
1.36      albertel 13033: }
                   13034: 
1.481     raeburn  13035: sub readfile {
                   13036:     my $file = shift;
                   13037:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13038:     my $fh;
1.1359    raeburn  13039:     open($fh,"<",$file);
1.481     raeburn  13040:     my $a='';
1.800     albertel 13041:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13042:     return $a;
                   13043: }
                   13044: 
1.36      albertel 13045: sub filelocation {
1.590     banghart 13046:     my ($dir,$file) = @_;
                   13047:     my $location;
                   13048:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13049: 
                   13050:     if ($file =~ m-^/adm/-) {
                   13051: 	$file=~s-^/adm/wrapper/-/-;
                   13052: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13053:     }
1.882     albertel 13054: 
1.1139    www      13055:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13056:         $location = $file;
1.609     banghart 13057:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13058:         my ($udom,$uname,$filename)=
1.811     albertel 13059:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13060:         my $home=&homeserver($uname,$udom);
                   13061:         my $is_me=0;
                   13062:         my @ids=&current_machine_ids();
                   13063:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13064:         if ($is_me) {
1.1117    foxr     13065:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13066:         } else {
                   13067:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13068:   	      $udom.'/'.$uname.'/'.$filename;
                   13069:         }
1.882     albertel 13070:     } elsif ($file =~ m-^/adm/-) {
                   13071: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13072:     } else {
                   13073:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13074:         $file=~s:^/(res|priv)/:/:;
                   13075:         my $space=$1;
1.590     banghart 13076:         if ( !( $file =~ m:^/:) ) {
                   13077:             $location = $dir. '/'.$file;
                   13078:         } else {
1.1142    raeburn  13079:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13080:         }
1.59      albertel 13081:     }
1.590     banghart 13082:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13083:     while ($location=~m{/\.\./}) {
                   13084: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13085: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13086: 	} else {
                   13087: 	    $location=~ s{/\.\./}{/}g;
                   13088: 	}
                   13089:     } #remove dir/..
1.590     banghart 13090:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13091:     return $location;
1.46      www      13092: }
1.36      albertel 13093: 
1.46      www      13094: sub hreflocation {
                   13095:     my ($dir,$file)=@_;
1.980     raeburn  13096:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13097: 	$file=filelocation($dir,$file);
1.700     albertel 13098:     } elsif ($file=~m-^/adm/-) {
                   13099: 	$file=~s-^/adm/wrapper/-/-;
                   13100: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13101:     }
                   13102:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13103: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13104:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13105: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13106: 	        {/uploaded/$1/$2/}x;
1.46      www      13107:     }
1.913     albertel 13108:     if ($file=~ m{^/userfiles/}) {
                   13109: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13110:     }
1.462     albertel 13111:     return $file;
1.465     albertel 13112: }
                   13113: 
1.1139    www      13114: 
                   13115: 
                   13116: 
                   13117: 
1.465     albertel 13118: sub current_machine_domains {
1.853     albertel 13119:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13120: }
                   13121: 
                   13122: sub machine_domains {
                   13123:     my ($hostname) = @_;
1.465     albertel 13124:     my @domains;
1.838     albertel 13125:     my %hostname = &all_hostnames();
1.465     albertel 13126:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13127: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13128: 	if ($hostname eq $name) {
1.844     albertel 13129: 	    push(@domains,&host_domain($id));
1.465     albertel 13130: 	}
                   13131:     }
                   13132:     return @domains;
                   13133: }
                   13134: 
                   13135: sub current_machine_ids {
1.853     albertel 13136:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13137: }
                   13138: 
                   13139: sub machine_ids {
                   13140:     my ($hostname) = @_;
                   13141:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13142:     my @ids;
1.888     albertel 13143:     my %name_to_host = &all_names();
1.889     albertel 13144:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13145: 	return @{ $name_to_host{$hostname} };
                   13146:     }
                   13147:     return;
1.31      www      13148: }
                   13149: 
1.824     raeburn  13150: sub additional_machine_domains {
                   13151:     my @domains;
1.1359    raeburn  13152:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13153:     while( my $line = <$fh>) {
                   13154:         $line =~ s/\s//g;
                   13155:         push(@domains,$line);
                   13156:     }
                   13157:     return @domains;
                   13158: }
                   13159: 
                   13160: sub default_login_domain {
                   13161:     my $domain = $perlvar{'lonDefDomain'};
                   13162:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13163:     foreach my $posdom (&current_machine_domains(),
                   13164:                         &additional_machine_domains()) {
                   13165:         if (lc($posdom) eq lc($testdomain)) {
                   13166:             $domain=$posdom;
                   13167:             last;
                   13168:         }
                   13169:     }
                   13170:     return $domain;
                   13171: }
                   13172: 
1.31      www      13173: # ------------------------------------------------------------- Declutters URLs
                   13174: 
                   13175: sub declutter {
                   13176:     my $thisfn=shift;
1.569     albertel 13177:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  13178:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13179:         $thisfn=~s{^/home/httpd/html}{};
                   13180:     }
1.31      www      13181:     $thisfn=~s/^\///;
1.697     albertel 13182:     $thisfn=~s|^adm/wrapper/||;
                   13183:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13184:     $thisfn=~s/^res\///;
1.1172    bisitz   13185:     $thisfn=~s/^priv\///;
1.1032    raeburn  13186:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13187:         $thisfn=~s/\?.+$//;
                   13188:     }
1.268     www      13189:     return $thisfn;
                   13190: }
                   13191: 
                   13192: # ------------------------------------------------------------- Clutter up URLs
                   13193: 
                   13194: sub clutter {
                   13195:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13196:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13197: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13198:        $thisfn='/res'.$thisfn; 
                   13199:     }
1.1031    raeburn  13200:     if ($thisfn !~m|^/adm|) {
                   13201: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13202: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13203: 	} else {
                   13204: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13205: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13206: 	    if ($embstyle eq 'ssi'
                   13207: 		|| ($embstyle eq 'hdn')
                   13208: 		|| ($embstyle eq 'rat')
                   13209: 		|| ($embstyle eq 'prv')
                   13210: 		|| ($embstyle eq 'ign')) {
                   13211: 		#do nothing with these
                   13212: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13213: 		|| ($embstyle eq 'emb')
                   13214: 		|| ($embstyle eq 'wrp')) {
                   13215: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13216: 	    } elsif ($embstyle eq 'unk'
                   13217: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13218: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13219: 	    } else {
1.718     www      13220: #		&logthis("Got a blank emb style");
1.695     albertel 13221: 	    }
1.694     albertel 13222: 	}
1.1343    raeburn  13223:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  13224:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13225:     }
1.31      www      13226:     return $thisfn;
1.12      www      13227: }
                   13228: 
1.787     albertel 13229: sub clutter_with_no_wrapper {
                   13230:     my $uri = &clutter(shift);
                   13231:     if ($uri =~ m-^/adm/-) {
                   13232: 	$uri =~ s-^/adm/wrapper/-/-;
                   13233: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13234:     }
                   13235:     return $uri;
                   13236: }
                   13237: 
1.557     albertel 13238: sub freeze_escape {
                   13239:     my ($value)=@_;
                   13240:     if (ref($value)) {
                   13241: 	$value=&nfreeze($value);
                   13242: 	return '__FROZEN__'.&escape($value);
                   13243:     }
                   13244:     return &escape($value);
                   13245: }
                   13246: 
1.11      www      13247: 
1.557     albertel 13248: sub thaw_unescape {
                   13249:     my ($value)=@_;
                   13250:     if ($value =~ /^__FROZEN__/) {
                   13251: 	substr($value,0,10,undef);
                   13252: 	$value=&unescape($value);
                   13253: 	return &thaw($value);
                   13254:     }
                   13255:     return &unescape($value);
                   13256: }
                   13257: 
1.436     albertel 13258: sub correct_line_ends {
                   13259:     my ($result)=@_;
                   13260:     $$result =~s/\r\n/\n/mg;
                   13261:     $$result =~s/\r/\n/mg;
1.415     albertel 13262: }
1.1       albertel 13263: # ================================================================ Main Program
                   13264: 
1.184     www      13265: sub goodbye {
1.204     albertel 13266:    &logthis("Starting Shut down");
1.443     albertel 13267: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13268:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13269: #converted
1.599     albertel 13270: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13271:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13272: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13273: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13274: #1.1 only
1.870     albertel 13275: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13276: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13277: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13278: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13279:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13280:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13281:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13282:    &flushcourselogs();
                   13283:    &logthis("Shutting down");
                   13284: }
                   13285: 
1.852     albertel 13286: sub get_dns {
1.1210    raeburn  13287:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13288:     if (!$ignore_cache) {
                   13289: 	my ($content,$cached)=
                   13290: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13291: 	if ($cached) {
1.1210    raeburn  13292: 	    &$func($content,$hashref);
1.869     albertel 13293: 	    return;
                   13294: 	}
                   13295:     }
                   13296: 
                   13297:     my %alldns;
1.1359    raeburn  13298:     open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13299:     foreach my $dns (<$config>) {
                   13300: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  13301:         my $line = $1;
                   13302:         my ($host,$protocol) = split(/:/,$line);
                   13303:         if ($protocol ne 'https') {
                   13304:             $protocol = 'http';
                   13305:         }
                   13306: 	$alldns{$host} = $protocol;
1.869     albertel 13307:     }
                   13308:     while (%alldns) {
1.1263    raeburn  13309: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979     raeburn  13310: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345    raeburn  13311:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979     raeburn  13312:         delete($alldns{$dns});
1.852     albertel 13313: 	next if ($response->is_error());
                   13314: 	my @content = split("\n",$response->content);
1.1210    raeburn  13315: 	unless ($nocache) {
1.1219    raeburn  13316: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  13317: 	}
                   13318: 	&$func(\@content,$hashref);
1.869     albertel 13319: 	return;
1.852     albertel 13320:     }
                   13321:     close($config);
1.871     albertel 13322:     my $which = (split('/',$url))[3];
                   13323:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1359    raeburn  13324:     open($config,"<","$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 13325:     my @content = <$config>;
1.1210    raeburn  13326:     &$func(\@content,$hashref);
                   13327:     return;
                   13328: }
                   13329: 
                   13330: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  13331: sub parse_dns_checksums_tab {
1.1210    raeburn  13332:     my ($lines,$hashref) = @_;
1.1264    raeburn  13333:     my $lonhost = $perlvar{'lonHostID'};
                   13334:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  13335:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  13336:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13337:     my $webconfdir = '/etc/httpd/conf';
                   13338:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13339:         $webconfdir = '/etc/apache2';
                   13340:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13341:         if ($1 >= 10) {
                   13342:             $webconfdir = '/etc/apache2';
                   13343:         }
                   13344:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13345:         if ($1 >= 10.0) {
                   13346:             $webconfdir = '/etc/apache2';
                   13347:         }
                   13348:     }
1.1210    raeburn  13349:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13350:     my (%chksum,%revnum);
                   13351:     if (ref($lines) eq 'ARRAY') {
                   13352:         chomp(@{$lines});
1.1238    raeburn  13353:         my $version = shift(@{$lines});
                   13354:         if ($version eq $release) {  
1.1210    raeburn  13355:             foreach my $line (@{$lines}) {
1.1238    raeburn  13356:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  13357:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13358:                     if ($webconfdir eq '/etc/apache2') {
                   13359:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13360:                     }
                   13361:                 }
1.1238    raeburn  13362:                 $chksum{$file} = $shasum;
                   13363:                 $revnum{$file} = $version;
1.1210    raeburn  13364:             }
                   13365:             if (ref($hashref) eq 'HASH') {
                   13366:                 %{$hashref} = (
                   13367:                                 sums     => \%chksum,
                   13368:                                 versions => \%revnum,
                   13369:                               );
                   13370:             }
                   13371:         }
                   13372:     }
1.869     albertel 13373:     return;
1.852     albertel 13374: }
1.1210    raeburn  13375: 
                   13376: sub fetch_dns_checksums {
1.1238    raeburn  13377:     my %checksums;
                   13378:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  13379:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  13380:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13381:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  13382:              \%checksums);
1.1210    raeburn  13383:     return \%checksums;
                   13384: }
                   13385: 
1.327     albertel 13386: # ------------------------------------------------------------ Read domain file
                   13387: {
1.852     albertel 13388:     my $loaded;
1.846     albertel 13389:     my %domain;
                   13390: 
1.852     albertel 13391:     sub parse_domain_tab {
                   13392: 	my ($lines) = @_;
                   13393: 	foreach my $line (@$lines) {
                   13394: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13395: 
1.846     albertel 13396: 	    chomp($line);
1.852     albertel 13397: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13398: 	    my %this_domain;
                   13399: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13400: 			       'lang_def', 'city', 'longi', 'lati',
                   13401: 			       'primary') {
                   13402: 		$this_domain{$field} = shift(@elements);
                   13403: 	    }
                   13404: 	    $domain{$name} = \%this_domain;
1.852     albertel 13405: 	}
                   13406:     }
1.864     albertel 13407: 
                   13408:     sub reset_domain_info {
                   13409: 	undef($loaded);
                   13410: 	undef(%domain);
                   13411:     }
                   13412: 
1.852     albertel 13413:     sub load_domain_tab {
1.1293    raeburn  13414: 	my ($ignore_cache,$nocache) = @_;
                   13415: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13416: 	my $fh;
1.1359    raeburn  13417: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13418: 	    my @lines = <$fh>;
                   13419: 	    &parse_domain_tab(\@lines);
1.448     albertel 13420: 	}
1.852     albertel 13421: 	close($fh);
                   13422: 	$loaded = 1;
1.327     albertel 13423:     }
1.846     albertel 13424: 
                   13425:     sub domain {
1.852     albertel 13426: 	&load_domain_tab() if (!$loaded);
                   13427: 
1.846     albertel 13428: 	my ($name,$what) = @_;
                   13429: 	return if ( !exists($domain{$name}) );
                   13430: 
                   13431: 	if (!$what) {
                   13432: 	    return $domain{$name}{'description'};
                   13433: 	}
                   13434: 	return $domain{$name}{$what};
                   13435:     }
1.974     raeburn  13436: 
                   13437:     sub domain_info {
                   13438:         &load_domain_tab() if (!$loaded);
                   13439:         return %domain;
                   13440:     }
                   13441: 
1.327     albertel 13442: }
                   13443: 
                   13444: 
1.1       albertel 13445: # ------------------------------------------------------------- Read hosts file
                   13446: {
1.838     albertel 13447:     my %hostname;
1.844     albertel 13448:     my %hostdom;
1.845     albertel 13449:     my %libserv;
1.852     albertel 13450:     my $loaded;
1.888     albertel 13451:     my %name_to_host;
1.1074    raeburn  13452:     my %internetdom;
1.1107    raeburn  13453:     my %LC_dns_serv;
1.852     albertel 13454: 
                   13455:     sub parse_hosts_tab {
                   13456: 	my ($file) = @_;
                   13457: 	foreach my $configline (@$file) {
                   13458: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13459:             chomp($configline);
                   13460: 	    if ($configline =~ /^\^/) {
                   13461:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13462:                     $LC_dns_serv{$1} = 1;
                   13463:                 }
                   13464:                 next;
                   13465:             }
1.1074    raeburn  13466: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13467: 	    $name=~s/\s//g;
                   13468: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  13469:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13470:                     my $curr = $hostname{$id};
                   13471:                     my $skip;
                   13472:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13473:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13474:                             $skip = 1;
                   13475:                         } else {
                   13476:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13477:                         }
                   13478:                     }
                   13479:                     unless ($skip) {
                   13480:                         push(@{$name_to_host{$name}},$id);
                   13481:                     }
                   13482:                 } else {
                   13483:                     push(@{$name_to_host{$name}},$id);
                   13484:                 }
1.852     albertel 13485: 		$hostname{$id}=$name;
                   13486: 		$hostdom{$id}=$domain;
                   13487: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13488:                 if (defined($protocol)) {
                   13489:                     if ($protocol eq 'https') {
                   13490:                         $protocol{$id} = $protocol;
                   13491:                     } else {
                   13492:                         $protocol{$id} = 'http'; 
                   13493:                     }
1.968     raeburn  13494:                 } else {
1.969     raeburn  13495:                     $protocol{$id} = 'http';
1.968     raeburn  13496:                 }
1.1074    raeburn  13497:                 if (defined($intdom)) {
                   13498:                     $internetdom{$id} = $intdom;
                   13499:                 }
1.852     albertel 13500: 	    }
                   13501: 	}
                   13502:     }
1.864     albertel 13503:     
                   13504:     sub reset_hosts_info {
1.897     albertel 13505: 	&purge_remembered();
1.864     albertel 13506: 	&reset_domain_info();
                   13507: 	&reset_hosts_ip_info();
1.1339    raeburn  13508:         undef(%internetdom);
1.892     albertel 13509: 	undef(%name_to_host);
1.864     albertel 13510: 	undef(%hostname);
                   13511: 	undef(%hostdom);
                   13512: 	undef(%libserv);
                   13513: 	undef($loaded);
                   13514:     }
1.1       albertel 13515: 
1.852     albertel 13516:     sub load_hosts_tab {
1.1293    raeburn  13517: 	my ($ignore_cache,$nocache) = @_;
                   13518: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  13519: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13520: 	my @config = <$config>;
                   13521: 	&parse_hosts_tab(\@config);
                   13522: 	close($config);
                   13523: 	$loaded=1;
1.1       albertel 13524:     }
1.852     albertel 13525: 
1.838     albertel 13526:     sub hostname {
1.852     albertel 13527: 	&load_hosts_tab() if (!$loaded);
                   13528: 
1.838     albertel 13529: 	my ($lonid) = @_;
                   13530: 	return $hostname{$lonid};
                   13531:     }
1.845     albertel 13532: 
1.838     albertel 13533:     sub all_hostnames {
1.852     albertel 13534: 	&load_hosts_tab() if (!$loaded);
                   13535: 
1.838     albertel 13536: 	return %hostname;
                   13537:     }
1.845     albertel 13538: 
1.888     albertel 13539:     sub all_names {
1.1293    raeburn  13540:         my ($ignore_cache,$nocache) = @_;
                   13541: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13542: 
                   13543: 	return %name_to_host;
                   13544:     }
                   13545: 
1.974     raeburn  13546:     sub all_host_domain {
                   13547:         &load_hosts_tab() if (!$loaded);
                   13548:         return %hostdom;
                   13549:     }
                   13550: 
1.1339    raeburn  13551:     sub all_host_intdom {
                   13552:         &load_hosts_tab() if (!$loaded);
                   13553:         return %internetdom;
                   13554:     }
                   13555: 
1.845     albertel 13556:     sub is_library {
1.852     albertel 13557: 	&load_hosts_tab() if (!$loaded);
                   13558: 
1.845     albertel 13559: 	return exists($libserv{$_[0]});
                   13560:     }
                   13561: 
                   13562:     sub all_library {
1.852     albertel 13563: 	&load_hosts_tab() if (!$loaded);
                   13564: 
1.845     albertel 13565: 	return %libserv;
                   13566:     }
                   13567: 
1.1062    droeschl 13568:     sub unique_library {
                   13569: 	#2x reverse removes all hostnames that appear more than once
                   13570:         my %unique = reverse &all_library();
                   13571:         return reverse %unique;
                   13572:     }
                   13573: 
1.841     albertel 13574:     sub get_servers {
1.852     albertel 13575: 	&load_hosts_tab() if (!$loaded);
                   13576: 
1.841     albertel 13577: 	my ($domain,$type) = @_;
                   13578: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13579: 	                                          : %hostname;
                   13580: 	my %result;
1.842     albertel 13581: 	if (ref($domain) eq 'ARRAY') {
                   13582: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13583: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13584: 		    $result{$host} = $hostname;
                   13585: 		}
                   13586: 	    }
                   13587: 	} else {
                   13588: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13589: 		if ($hostdom{$host} eq $domain) {
                   13590: 		    $result{$host} = $hostname;
                   13591: 		}
1.841     albertel 13592: 	    }
                   13593: 	}
                   13594: 	return %result;
                   13595:     }
1.845     albertel 13596: 
1.1062    droeschl 13597:     sub get_unique_servers {
                   13598:         my %unique = reverse &get_servers(@_);
                   13599: 	return reverse %unique;
                   13600:     }
                   13601: 
1.844     albertel 13602:     sub host_domain {
1.852     albertel 13603: 	&load_hosts_tab() if (!$loaded);
                   13604: 
1.844     albertel 13605: 	my ($lonid) = @_;
                   13606: 	return $hostdom{$lonid};
                   13607:     }
                   13608: 
1.841     albertel 13609:     sub all_domains {
1.852     albertel 13610: 	&load_hosts_tab() if (!$loaded);
                   13611: 
1.841     albertel 13612: 	my %seen;
                   13613: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13614: 	return @uniq;
                   13615:     }
1.1074    raeburn  13616: 
                   13617:     sub internet_dom {
                   13618:         &load_hosts_tab() if (!$loaded);
                   13619: 
                   13620:         my ($lonid) = @_;
                   13621:         return $internetdom{$lonid};
                   13622:     }
1.1107    raeburn  13623: 
                   13624:     sub is_LC_dns {
                   13625:         &load_hosts_tab() if (!$loaded);
                   13626: 
                   13627:         my ($hostname) = @_;
                   13628:         return exists($LC_dns_serv{$hostname});
                   13629:     }
                   13630: 
1.1       albertel 13631: }
                   13632: 
1.847     albertel 13633: { 
                   13634:     my %iphost;
1.856     albertel 13635:     my %name_to_ip;
                   13636:     my %lonid_to_ip;
1.869     albertel 13637: 
1.847     albertel 13638:     sub get_hosts_from_ip {
                   13639: 	my ($ip) = @_;
                   13640: 	my %iphosts = &get_iphost();
                   13641: 	if (ref($iphosts{$ip})) {
                   13642: 	    return @{$iphosts{$ip}};
                   13643: 	}
                   13644: 	return;
1.839     albertel 13645:     }
1.864     albertel 13646:     
                   13647:     sub reset_hosts_ip_info {
                   13648: 	undef(%iphost);
                   13649: 	undef(%name_to_ip);
                   13650: 	undef(%lonid_to_ip);
                   13651:     }
1.856     albertel 13652: 
                   13653:     sub get_host_ip {
                   13654: 	my ($lonid) = @_;
                   13655: 	if (exists($lonid_to_ip{$lonid})) {
                   13656: 	    return $lonid_to_ip{$lonid};
                   13657: 	}
                   13658: 	my $name=&hostname($lonid);
                   13659:    	my $ip = gethostbyname($name);
                   13660: 	return if (!$ip || length($ip) ne 4);
                   13661: 	$ip=inet_ntoa($ip);
                   13662: 	$name_to_ip{$name}   = $ip;
                   13663: 	$lonid_to_ip{$lonid} = $ip;
                   13664: 	return $ip;
                   13665:     }
1.847     albertel 13666:     
                   13667:     sub get_iphost {
1.1293    raeburn  13668: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13669: 
1.869     albertel 13670: 	if (!$ignore_cache) {
                   13671: 	    if (%iphost) {
                   13672: 		return %iphost;
                   13673: 	    }
                   13674: 	    my ($ip_info,$cached)=
                   13675: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13676: 	    if ($cached) {
                   13677: 		%iphost      = %{$ip_info->[0]};
                   13678: 		%name_to_ip  = %{$ip_info->[1]};
                   13679: 		%lonid_to_ip = %{$ip_info->[2]};
                   13680: 		return %iphost;
                   13681: 	    }
                   13682: 	}
1.894     albertel 13683: 
                   13684: 	# get yesterday's info for fallback
                   13685: 	my %old_name_to_ip;
                   13686: 	my ($ip_info,$cached)=
                   13687: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13688: 	if ($cached) {
                   13689: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13690: 	}
                   13691: 
1.1293    raeburn  13692: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13693: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13694: 	    my $ip;
                   13695: 	    if (!exists($name_to_ip{$name})) {
                   13696: 		$ip = gethostbyname($name);
                   13697: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13698: 		    if (defined($old_name_to_ip{$name})) {
                   13699: 			$ip = $old_name_to_ip{$name};
                   13700: 			&logthis("Can't find $name defaulting to old $ip");
                   13701: 		    } else {
                   13702: 			&logthis("Name $name no IP found");
                   13703: 			next;
                   13704: 		    }
                   13705: 		} else {
                   13706: 		    $ip=inet_ntoa($ip);
1.847     albertel 13707: 		}
                   13708: 		$name_to_ip{$name} = $ip;
                   13709: 	    } else {
                   13710: 		$ip = $name_to_ip{$name};
1.653     albertel 13711: 	    }
1.888     albertel 13712: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13713: 		$lonid_to_ip{$id} = $ip;
                   13714: 	    }
                   13715: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13716: 	}
1.1293    raeburn  13717:         unless ($nocache) {
                   13718: 	    &do_cache_new('iphost','iphost',
                   13719: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13720: 		          48*60*60);
                   13721:         }
1.869     albertel 13722: 
1.847     albertel 13723: 	return %iphost;
1.598     albertel 13724:     }
                   13725: 
1.992     raeburn  13726:     #
                   13727:     #  Given a DNS returns the loncapa host name for that DNS 
                   13728:     # 
                   13729:     sub host_from_dns {
                   13730:         my ($dns) = @_;
                   13731:         my @hosts;
                   13732:         my $ip;
                   13733: 
1.993     raeburn  13734:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13735:             $ip = $name_to_ip{$dns};
                   13736:         }
                   13737:         if (!$ip) {
                   13738:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13739:             if (length($ip) == 4) { 
                   13740: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13741:             }
                   13742:         }
                   13743:         if ($ip) {
                   13744: 	    @hosts = get_hosts_from_ip($ip);
                   13745: 	    return $hosts[0];
                   13746:         }
                   13747:         return undef;
1.986     foxr     13748:     }
1.992     raeburn  13749: 
1.1074    raeburn  13750:     sub get_internet_names {
                   13751:         my ($lonid) = @_;
                   13752:         return if ($lonid eq '');
                   13753:         my ($idnref,$cached)=
                   13754:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13755:         if ($cached) {
                   13756:             return $idnref;
                   13757:         }
                   13758:         my $ip = &get_host_ip($lonid);
                   13759:         my @hosts = &get_hosts_from_ip($ip);
                   13760:         my %iphost = &get_iphost();
                   13761:         my (@idns,%seen);
                   13762:         foreach my $id (@hosts) {
                   13763:             my $dom = &host_domain($id);
                   13764:             my $prim_id = &domain($dom,'primary');
                   13765:             my $prim_ip = &get_host_ip($prim_id);
                   13766:             next if ($seen{$prim_ip});
                   13767:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13768:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13769:                     my $intdom = &internet_dom($id);
                   13770:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13771:                         push(@idns,$intdom);
                   13772:                     }
                   13773:                 }
                   13774:             }
                   13775:             $seen{$prim_ip} = 1;
                   13776:         }
1.1219    raeburn  13777:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13778:     }
                   13779: 
1.986     foxr     13780: }
                   13781: 
1.1079    raeburn  13782: sub all_loncaparevs {
1.1249    raeburn  13783:     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  13784: }
                   13785: 
1.1227    raeburn  13786: # ---------------------------------------------------------- Read loncaparev table
                   13787: {
                   13788:     sub load_loncaparevs { 
                   13789:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  13790:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  13791:                 while (my $configline=<$config>) {
                   13792:                     chomp($configline);
                   13793:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13794:                     $loncaparevs{$hostid}=$loncaparev;
                   13795:                 }
                   13796:                 close($config);
                   13797:             }
                   13798:         }
                   13799:     }
                   13800: }
                   13801: 
                   13802: # ---------------------------------------------------------- Read serverhostID table
                   13803: {
                   13804:     sub load_serverhomeIDs {
                   13805:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  13806:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  13807:                 while (my $configline=<$config>) {
                   13808:                     chomp($configline);
                   13809:                     my ($name,$id)=split(/:/,$configline);
                   13810:                     $serverhomeIDs{$name}=$id;
                   13811:                 }
                   13812:                 close($config);
                   13813:             }
                   13814:         }
                   13815:     }
                   13816: }
                   13817: 
                   13818: 
1.862     albertel 13819: BEGIN {
                   13820: 
                   13821: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13822:     unless ($readit) {
                   13823: {
                   13824:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13825:     %perlvar = (%perlvar,%{$configvars});
                   13826: }
                   13827: 
                   13828: 
1.1       albertel 13829: # ------------------------------------------------------ Read spare server file
                   13830: {
1.1359    raeburn  13831:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13832: 
                   13833:     while (my $configline=<$config>) {
                   13834:        chomp($configline);
1.284     matthew  13835:        if ($configline) {
1.784     albertel 13836: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13837: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13838: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13839:        }
                   13840:     }
1.448     albertel 13841:     close($config);
1.1       albertel 13842: }
1.11      www      13843: # ------------------------------------------------------------ Read permissions
                   13844: {
1.1359    raeburn  13845:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13846: 
                   13847:     while (my $configline=<$config>) {
1.448     albertel 13848: 	chomp($configline);
                   13849: 	if ($configline) {
                   13850: 	    my ($role,$perm)=split(/ /,$configline);
                   13851: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13852: 	}
1.11      www      13853:     }
1.448     albertel 13854:     close($config);
1.11      www      13855: }
                   13856: 
                   13857: # -------------------------------------------- Read plain texts for permissions
                   13858: {
1.1359    raeburn  13859:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13860: 
                   13861:     while (my $configline=<$config>) {
1.448     albertel 13862: 	chomp($configline);
                   13863: 	if ($configline) {
1.742     raeburn  13864: 	    my ($short,@plain)=split(/:/,$configline);
                   13865:             %{$prp{$short}} = ();
                   13866: 	    if (@plain > 0) {
                   13867:                 $prp{$short}{'std'} = $plain[0];
                   13868:                 for (my $i=1; $i<@plain; $i++) {
                   13869:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13870:                 }
                   13871:             }
1.448     albertel 13872: 	}
1.135     www      13873:     }
1.448     albertel 13874:     close($config);
1.135     www      13875: }
                   13876: 
                   13877: # ---------------------------------------------------------- Read package table
                   13878: {
1.1359    raeburn  13879:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13880: 
                   13881:     while (my $configline=<$config>) {
1.483     albertel 13882: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13883: 	chomp($configline);
                   13884: 	my ($short,$plain)=split(/:/,$configline);
                   13885: 	my ($pack,$name)=split(/\&/,$short);
                   13886: 	if ($plain ne '') {
                   13887: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13888: 	    $packagetab{$short}=$plain; 
                   13889: 	}
1.11      www      13890:     }
1.448     albertel 13891:     close($config);
1.329     matthew  13892: }
                   13893: 
1.1073    raeburn  13894: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  13895: 
                   13896: &load_loncaparevs();
1.1073    raeburn  13897: 
1.1074    raeburn  13898: # ---------------------------------------------------------- Read serverhostID table
                   13899: 
1.1227    raeburn  13900: &load_serverhomeIDs();
                   13901: 
                   13902: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13903: {
                   13904:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13905:     if (-e $file) {
                   13906:         my $parser = HTML::LCParser->new($file);
                   13907:         while (my $token = $parser->get_token()) {
                   13908:             if ($token->[0] eq 'S') {
                   13909:                 my $item = $token->[1];
                   13910:                 my $name = $token->[2]{'name'};
                   13911:                 my $value = $token->[2]{'value'};
1.1285    raeburn  13912:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  13913:                 my $namematch = $token->[2]{'namematch'};
                   13914:                 if ($item eq 'parameter') {
                   13915:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   13916:                         my $release = $parser->get_text();
                   13917:                         $release =~ s/(^\s*|\s*$ )//gx;
                   13918:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   13919:                     }
                   13920:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  13921:                     my $release = $parser->get_text();
                   13922:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  13923:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  13924:                 }
                   13925:             }
                   13926:         }
                   13927:     }
1.1073    raeburn  13928: }
                   13929: 
1.1138    raeburn  13930: # ---------------------------------------------------------- Read managers table
                   13931: {
                   13932:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  13933:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  13934:             while (my $configline=<$config>) {
                   13935:                 chomp($configline);
                   13936:                 next if ($configline =~ /^\#/);
                   13937:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13938:                     $managerstab{$configline} = 1;
                   13939:                 }
                   13940:             }
                   13941:             close($config);
                   13942:         }
                   13943:     }
                   13944: }
                   13945: 
1.329     matthew  13946: # ------------- set up temporary directory
                   13947: {
1.1117    foxr     13948:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13949: 
1.11      www      13950: }
                   13951: 
1.794     albertel 13952: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13953: 				'compress_threshold'=> 20_000,
                   13954:  			        });
1.185     www      13955: 
1.281     www      13956: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13957: $dumpcount=0;
1.958     www      13958: $locknum=0;
1.22      www      13959: 
1.163     harris41 13960: &logtouch();
1.672     albertel 13961: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13962: $readit=1;
1.564     albertel 13963:     {
                   13964: 	use integer;
                   13965: 	my $test=(2**32)+1;
1.568     albertel 13966: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13967: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13968:     }
1.195     www      13969: }
1.1       albertel 13970: }
1.179     www      13971: 
1.1       albertel 13972: 1;
1.191     harris41 13973: __END__
                   13974: 
1.243     albertel 13975: =pod
                   13976: 
1.191     harris41 13977: =head1 NAME
                   13978: 
1.243     albertel 13979: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13980: 
                   13981: =head1 SYNOPSIS
                   13982: 
1.243     albertel 13983: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13984: 
                   13985:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13986: 
1.243     albertel 13987: Common parameters:
                   13988: 
                   13989: =over 4
                   13990: 
                   13991: =item *
                   13992: 
                   13993: $uname : an internal username (if $cname expecting a course Id specifically)
                   13994: 
                   13995: =item *
                   13996: 
                   13997: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13998: 
                   13999: =item *
                   14000: 
                   14001: $symb : a resource instance identifier
                   14002: 
                   14003: =item *
                   14004: 
                   14005: $namespace : the name of a .db file that contains the data needed or
                   14006: being set.
                   14007: 
                   14008: =back
                   14009: 
1.394     bowersj2 14010: =head1 OVERVIEW
1.191     harris41 14011: 
1.394     bowersj2 14012: lonnet provides subroutines which interact with the
                   14013: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14014: about classes, users, and resources.
1.243     albertel 14015: 
                   14016: For many of these objects you can also use this to store data about
                   14017: them or modify them in various ways.
1.191     harris41 14018: 
1.394     bowersj2 14019: =head2 Symbs
1.191     harris41 14020: 
1.394     bowersj2 14021: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14022: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14023: map, the resource number of the resource in the map, and the URL of
                   14024: the resource itself. The latter is somewhat redundant, but might help
                   14025: if maps change.
                   14026: 
                   14027: An example is
                   14028: 
                   14029:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14030: 
                   14031: The respective map entry is
                   14032: 
                   14033:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14034:   title="Problem 2">
                   14035:  </resource>
                   14036: 
                   14037: Symbs are used by the random number generator, as well as to store and
                   14038: restore data specific to a certain instance of for example a problem.
                   14039: 
                   14040: =head2 Storing And Retrieving Data
                   14041: 
                   14042: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14043: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14044: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14045: is is the non-critical message twin of cstore. These functions are for
                   14046: handlers to store a perl hash to a user's permanent data space in an
                   14047: easy manner, and to retrieve it again on another call. It is expected
                   14048: that a handler would use this once at the beginning to retrieve data,
                   14049: and then again once at the end to send only the new data back.
                   14050: 
                   14051: The data is stored in the user's data directory on the user's
                   14052: homeserver under the ID of the course.
                   14053: 
                   14054: The hash that is returned by restore will have all of the previous
                   14055: value for all of the elements of the hash.
                   14056: 
                   14057: Example:
                   14058: 
                   14059:  #creating a hash
                   14060:  my %hash;
                   14061:  $hash{'foo'}='bar';
                   14062: 
                   14063:  #storing it
                   14064:  &Apache::lonnet::cstore(\%hash);
                   14065: 
                   14066:  #changing a value
                   14067:  $hash{'foo'}='notbar';
                   14068: 
                   14069:  #adding a new value
                   14070:  $hash{'bar'}='foo';
                   14071:  &Apache::lonnet::cstore(\%hash);
                   14072: 
                   14073:  #retrieving the hash
                   14074:  my %history=&Apache::lonnet::restore();
                   14075: 
                   14076:  #print the hash
                   14077:  foreach my $key (sort(keys(%history))) {
                   14078:    print("\%history{$key} = $history{$key}");
                   14079:  }
                   14080: 
                   14081: Will print out:
1.191     harris41 14082: 
1.394     bowersj2 14083:  %history{1:foo} = bar
                   14084:  %history{1:keys} = foo:timestamp
                   14085:  %history{1:timestamp} = 990455579
                   14086:  %history{2:bar} = foo
                   14087:  %history{2:foo} = notbar
                   14088:  %history{2:keys} = foo:bar:timestamp
                   14089:  %history{2:timestamp} = 990455580
                   14090:  %history{bar} = foo
                   14091:  %history{foo} = notbar
                   14092:  %history{timestamp} = 990455580
                   14093:  %history{version} = 2
                   14094: 
                   14095: Note that the special hash entries C<keys>, C<version> and
                   14096: C<timestamp> were added to the hash. C<version> will be equal to the
                   14097: total number of versions of the data that have been stored. The
                   14098: C<timestamp> attribute will be the UNIX time the hash was
                   14099: stored. C<keys> is available in every historical section to list which
                   14100: keys were added or changed at a specific historical revision of a
                   14101: hash.
                   14102: 
                   14103: B<Warning>: do not store the hash that restore returns directly. This
                   14104: will cause a mess since it will restore the historical keys as if the
                   14105: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14106: 
1.394     bowersj2 14107: Calling convention:
1.191     harris41 14108: 
1.1225    raeburn  14109:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  14110:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14111: 
1.394     bowersj2 14112: For more detailed information, see lonnet specific documentation.
1.191     harris41 14113: 
1.394     bowersj2 14114: =head1 RETURN MESSAGES
1.191     harris41 14115: 
1.394     bowersj2 14116: =over 4
1.191     harris41 14117: 
1.394     bowersj2 14118: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14119: 
1.394     bowersj2 14120: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14121: when the connection is brought back up
1.191     harris41 14122: 
1.394     bowersj2 14123: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14124: for later delivery
1.191     harris41 14125: 
1.967     bisitz   14126: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14127: 
1.394     bowersj2 14128: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14129: that was requested
1.191     harris41 14130: 
1.243     albertel 14131: =back
1.191     harris41 14132: 
1.243     albertel 14133: =head1 PUBLIC SUBROUTINES
1.191     harris41 14134: 
1.243     albertel 14135: =head2 Session Environment Functions
1.191     harris41 14136: 
1.243     albertel 14137: =over 4
1.191     harris41 14138: 
1.394     bowersj2 14139: =item * 
                   14140: X<appenv()>
1.949     raeburn  14141: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14142: the user envirnoment file, and will be restored for each access this
1.620     albertel 14143: user makes during this session, also modifies the %env for the current
1.949     raeburn  14144: process. Optional rolesarrayref - if defined contains a reference to an array
                   14145: of roles which are exempt from the restriction on modifying user.role entries 
                   14146: in the user's environment.db and in %env.    
1.191     harris41 14147: 
                   14148: =item *
1.394     bowersj2 14149: X<delenv()>
1.987     raeburn  14150: B<delenv($delthis,$regexp)>: removes all items from the session
                   14151: environment file that begin with $delthis. If the 
                   14152: optional second arg - $regexp - is true, $delthis is treated as a 
                   14153: regular expression, otherwise \Q$delthis\E is used. 
                   14154: The values are also deleted from the current processes %env.
1.191     harris41 14155: 
1.795     albertel 14156: =item * get_env_multiple($name) 
                   14157: 
                   14158: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14159: values may be defined and end up as an array ref.
                   14160: 
                   14161: returns an array of values
                   14162: 
1.243     albertel 14163: =back
                   14164: 
                   14165: =head2 User Information
1.191     harris41 14166: 
1.243     albertel 14167: =over 4
1.191     harris41 14168: 
                   14169: =item *
1.394     bowersj2 14170: X<queryauthenticate()>
                   14171: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14172: authentication scheme
                   14173: 
                   14174: =item *
1.394     bowersj2 14175: X<authenticate()>
1.1073    raeburn  14176: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14177: authenticate user from domain's lib servers (first use the current
                   14178: one). C<$upass> should be the users password.
1.1073    raeburn  14179: $checkdefauth is optional (value is 1 if a check should be made to
                   14180:    authenticate user using default authentication method, and allow
                   14181:    account creation if username does not have account in the domain).
                   14182: $clientcancheckhost is optional (value is 1 if checking whether the
                   14183:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14184: 
                   14185: =item *
1.394     bowersj2 14186: X<homeserver()>
                   14187: B<homeserver($uname,$udom)>: find the server which has
                   14188: the user's directory and files (there must be only one), this caches
                   14189: the answer, and also caches if there is a borken connection.
1.191     harris41 14190: 
                   14191: =item *
1.394     bowersj2 14192: X<idget()>
1.1300    raeburn  14193: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   14194: a list of student/employee IDs or clicker IDs
                   14195: (student/employee IDs are a unique resource in a domain, there must be 
                   14196: only 1 ID per username, and only 1 username per ID in a specific domain).
                   14197: clickerIDs are not necessarily unique, as students might share clickers.
                   14198: (returns hash: id=>name,id=>name)
1.191     harris41 14199: 
                   14200: =item *
1.394     bowersj2 14201: X<idrget()>
                   14202: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14203: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14204: 
                   14205: =item *
1.394     bowersj2 14206: X<idput()>
1.1300    raeburn  14207: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   14208: names and associated student/employee IDs or clicker IDs.
                   14209: 
                   14210: =item *
                   14211: X<iddel()>
                   14212: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   14213: student/employee ID or clicker ID username look-ups from domain.
                   14214: The homeserver ($uhome) and namespace ($namespace) are optional.
                   14215: If no $uhome is provided, it will be determined usig &homeserver()
                   14216: for each user.  If no $namespace is provided, the default is ids.
                   14217: 
                   14218: =item *
                   14219: X<updateclickers()>
                   14220: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   14221: clicker ID-to-username look-ups in clickers.db on library server.
                   14222: Permitted actions are add or del (i.e., add or delete). The 
                   14223: clickers.db contains clickerID as keys (escaped), and each corresponding
                   14224: value is an escaped comma-separated list of usernames (for whom the
                   14225: library server is the homeserver), who registered that particular ID.
                   14226: If $critical is true, the update will be sent via &critical, otherwise
                   14227: &reply() will be used.
1.191     harris41 14228: 
                   14229: =item *
1.394     bowersj2 14230: X<rolesinit()>
1.1169    droeschl 14231: B<rolesinit($udom,$username)>: get user privileges.
                   14232: returns user role, first access and timer interval hashes
1.243     albertel 14233: 
                   14234: =item *
1.1171    droeschl 14235: X<privileged()>
                   14236: B<privileged($username,$domain)>: returns a true if user has a
                   14237: privileged and active role (i.e. su or dc), false otherwise.
                   14238: 
                   14239: =item *
1.551     albertel 14240: X<getsection()>
                   14241: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14242: course $cname, return section name/number or '' for "not in course"
                   14243: and '-1' for "no section"
                   14244: 
                   14245: =item *
1.394     bowersj2 14246: X<userenvironment()>
                   14247: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14248: passed in @what from the requested user's environment, returns a hash
                   14249: 
1.858     raeburn  14250: =item * 
                   14251: X<userlog_query()>
1.859     albertel 14252: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14253: activity.log file. %filters defines filters applied when parsing the
                   14254: log file. These can be start or end timestamps, or the type of action
                   14255: - log to look for Login or Logout events, check for Checkin or
                   14256: Checkout, role for role selection. The response is in the form
                   14257: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14258: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14259: 
1.243     albertel 14260: =back
                   14261: 
                   14262: =head2 User Roles
                   14263: 
                   14264: =over 4
                   14265: 
                   14266: =item *
                   14267: 
1.1284    raeburn  14268: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14269: returns codes for allowed actions.
                   14270: 
                   14271: The first argument is required, all others are optional.
                   14272: 
                   14273: $priv is the privilege being checked.
                   14274: $uri contains additional information about what is being checked for access (e.g.,
                   14275: URL, course ID etc.). 
                   14276: $symb is the unique resource instance identifier in a course; if needed,
                   14277: but not provided, it will be retrieved via a call to &symbread(). 
                   14278: $role is the role for which a priv is being checked (only used if priv is evb). 
                   14279: $clientip is the user's IP address (only used when checking for access to portfolio 
                   14280: files).
                   14281: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   14282: prevents recursive calls to &allowed.
                   14283: 
1.243     albertel 14284:  F: full access
                   14285:  U,I,K: authentication modes (cxx only)
                   14286:  '': forbidden
                   14287:  1: user needs to choose course
                   14288:  2: browse allowed
1.766     albertel 14289:  A: passphrase authentication needed
1.1284    raeburn  14290:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14291: 
                   14292: =item *
                   14293: 
1.1192    raeburn  14294: constructaccess($url,$setpriv) : check for access to construction space URL
                   14295: 
                   14296: See if the owner domain and name in the URL match those in the
                   14297: expected environment.  If so, return three element list
                   14298: ($ownername,$ownerdomain,$ownerhome).
                   14299: 
                   14300: Otherwise return the null string.
                   14301: 
                   14302: If second argument 'setpriv' is true, it assigns the privileges,
                   14303: and returns the same three element list, unless the owner has
                   14304: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14305: in which case the null string is returned.
                   14306: 
                   14307: =item *
                   14308: 
1.1326    raeburn  14309: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14310: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14311: for system, domain, and course level. $uname and $udom are optional (current
                   14312: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14313: 
                   14314: =item *
                   14315: 
1.988     raeburn  14316: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14317: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14318: $type is Course (default) or Community.
1.988     raeburn  14319: If $forcedefault evaluates to true, text returned will be default 
                   14320: text for $type. Otherwise, if this is a course, the text returned 
                   14321: will be a custom name for the role (if defined in the course's 
                   14322: environment).  If no custom name is defined the default is returned.
                   14323:    
1.832     raeburn  14324: =item *
                   14325: 
1.1219    raeburn  14326: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14327: All arguments are optional. Returns a hash of a roles, either for
                   14328: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14329: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14330: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14331: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14332: For each key, value is set to colon-separated start and end times for
                   14333: the role.  If no username and domain are specified, will default to
1.934     raeburn  14334: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14335: of role statuses (active, future or previous), roles 
                   14336: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14337: to restrict the list of roles reported. If no array ref is 
                   14338: provided for types, will default to return only active roles.
1.834     albertel 14339: 
1.1195    raeburn  14340: =item *
                   14341: 
                   14342: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  14343: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   14344: 
                   14345: Additional optional arguments are: $type (if role checking is to be restricted 
                   14346: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  14347: available roles) or future (roles available in the future), and
                   14348: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  14349: have active Domain Coordinator role in course's domain or in additional
                   14350: domains (specified in 'Domains to check for privileged users' in course
                   14351: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14352: 
                   14353: =item *
                   14354: 
                   14355: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14356: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14357: $possdomains and $possroles are optional array refs -- to domains to check and
                   14358: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14359: users' roles.db to check for a dc or su role in any domain. This can be
                   14360: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14361: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14362: this then allows &privileged_by_domain() to be used, which caches the identity
                   14363: of privileged users, eliminating the need for repeated calls to &dump().
                   14364: 
                   14365: =item *
                   14366: 
                   14367: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14368: where the outer hash keys are domains specified in the $possdomains array ref,
                   14369: next inner hash keys are privileged roles specified in the $roles array ref,
                   14370: and the innermost hash contains key = value pairs for username:domain = end:start
                   14371: for active or future "privileged" users with that role in that domain. To avoid
                   14372: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14373: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  14374: 
1.243     albertel 14375: =back
                   14376: 
                   14377: =head2 User Modification
                   14378: 
                   14379: =over 4
                   14380: 
                   14381: =item *
                   14382: 
1.957     raeburn  14383: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14384: user for the level given by URL.  Optional start and end dates (leave empty
                   14385: string or zero for "no date")
1.191     harris41 14386: 
                   14387: =item *
                   14388: 
1.243     albertel 14389: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14390: change a users, password, possible return values are: ok,
                   14391: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14392: refused
1.191     harris41 14393: 
                   14394: =item *
                   14395: 
1.243     albertel 14396: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14397: 
                   14398: =item *
                   14399: 
1.1058    raeburn  14400: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14401:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14402: 
                   14403: will update user information (firstname,middlename,lastname,generation,
                   14404: permanentemail), and if forceid is true, student/employee ID also.
                   14405: A user's institutional affiliation(s) can also be updated.
                   14406: User information fields will not be overwritten with empty entries 
                   14407: unless the field is included in the $candelete array reference.
                   14408: This array is included when a single user is modified via "Manage Users",
                   14409: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14410: 
                   14411: =item *
                   14412: 
1.286     matthew  14413: modifystudent
                   14414: 
1.957     raeburn  14415: modify a student's enrollment and identification information.
1.1235    raeburn  14416: The course id is resolved based on the current user's environment.  
                   14417: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14418: associated with a course.
                   14419: 
1.297     matthew  14420: This call is essentially a wrapper for lonnet::modifyuser and
                   14421: lonnet::modify_student_enrollment
1.286     matthew  14422: 
                   14423: Inputs: 
                   14424: 
                   14425: =over 4
                   14426: 
1.957     raeburn  14427: =item B<$udom> Student's loncapa domain
1.286     matthew  14428: 
1.957     raeburn  14429: =item B<$uname> Student's loncapa login name
1.286     matthew  14430: 
1.964     bisitz   14431: =item B<$uid> Student/Employee ID
1.286     matthew  14432: 
1.957     raeburn  14433: =item B<$umode> Student's authentication mode
1.286     matthew  14434: 
1.957     raeburn  14435: =item B<$upass> Student's password
1.286     matthew  14436: 
1.957     raeburn  14437: =item B<$first> Student's first name
1.286     matthew  14438: 
1.957     raeburn  14439: =item B<$middle> Student's middle name
1.286     matthew  14440: 
1.957     raeburn  14441: =item B<$last> Student's last name
1.286     matthew  14442: 
1.957     raeburn  14443: =item B<$gene> Student's generation
1.286     matthew  14444: 
1.957     raeburn  14445: =item B<$usec> Student's section in course
1.286     matthew  14446: 
                   14447: =item B<$end> Unix time of the roles expiration
                   14448: 
                   14449: =item B<$start> Unix time of the roles start date
                   14450: 
                   14451: =item B<$forceid> If defined, allow $uid to be changed
                   14452: 
                   14453: =item B<$desiredhome> server to use as home server for student
                   14454: 
1.957     raeburn  14455: =item B<$email> Student's permanent e-mail address
                   14456: 
                   14457: =item B<$type> Type of enrollment (auto or manual)
                   14458: 
1.963     raeburn  14459: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14460: 
                   14461: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14462: 
1.963     raeburn  14463: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14464: 
1.963     raeburn  14465: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14466: 
1.1216    raeburn  14467: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14468: 
                   14469: =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  14470: 
1.286     matthew  14471: =back
1.297     matthew  14472: 
                   14473: =item *
                   14474: 
                   14475: modify_student_enrollment
                   14476: 
1.1235    raeburn  14477: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14478: 'role.request.course' must be defined for this function to proceed.
                   14479: 
                   14480: Inputs:
                   14481: 
                   14482: =over 4
                   14483: 
1.1235    raeburn  14484: =item $udom, student's domain
1.297     matthew  14485: 
1.1235    raeburn  14486: =item $uname, student's name
1.297     matthew  14487: 
1.1235    raeburn  14488: =item $uid, student's user id
1.297     matthew  14489: 
1.1235    raeburn  14490: =item $first, student's first name
1.297     matthew  14491: 
                   14492: =item $middle
                   14493: 
                   14494: =item $last
                   14495: 
                   14496: =item $gene
                   14497: 
                   14498: =item $usec
                   14499: 
                   14500: =item $end
                   14501: 
                   14502: =item $start
                   14503: 
1.957     raeburn  14504: =item $type
                   14505: 
                   14506: =item $locktype
                   14507: 
                   14508: =item $cid
                   14509: 
                   14510: =item $selfenroll
                   14511: 
                   14512: =item $context
                   14513: 
1.1216    raeburn  14514: =item $credits, number of credits student will earn from this class
                   14515: 
1.1314    raeburn  14516: =item $instsec, institutional course section code for student
                   14517: 
1.297     matthew  14518: =back
                   14519: 
1.191     harris41 14520: 
                   14521: =item *
                   14522: 
1.243     albertel 14523: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14524: custom role; give a custom role to a user for the level given by URL.  Specify
                   14525: name and domain of role author, and role name
1.191     harris41 14526: 
                   14527: =item *
                   14528: 
1.243     albertel 14529: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14530: 
                   14531: =item *
                   14532: 
1.243     albertel 14533: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14534: 
                   14535: =back
                   14536: 
                   14537: =head2 Course Infomation
                   14538: 
                   14539: =over 4
1.191     harris41 14540: 
                   14541: =item *
                   14542: 
1.1118    foxr     14543: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14544: specified course id, including all environment settings for the
                   14545: course, the description of the course will be in the hash under the
                   14546: key 'description'
1.191     harris41 14547: 
1.1118    foxr     14548: $options is an optional parameter that if supplied is a hash reference that controls
                   14549: what how this function works.  It has the following key/values:
                   14550: 
                   14551: =over 4
                   14552: 
                   14553: =item freshen_cache
                   14554: 
                   14555: If defined, and the environment cache for the course is valid, it is 
                   14556: returned in the returned hash.
                   14557: 
                   14558: =item one_time
                   14559: 
                   14560: If defined, the last cache time is set to _now_
                   14561: 
                   14562: =item user
                   14563: 
                   14564: If defined, the supplied username is used instead of the current user.
                   14565: 
                   14566: 
                   14567: =back
                   14568: 
1.191     harris41 14569: =item *
                   14570: 
1.624     albertel 14571: resdata($name,$domain,$type,@which) : request for current parameter
                   14572: setting for a specific $type, where $type is either 'course' or 'user',
                   14573: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  14574: answers for 10 minutes.
1.243     albertel 14575: 
1.877     foxr     14576: =item *
                   14577: 
                   14578: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14579: data base, returning a hash that is keyed by the resource name and has
                   14580: values that are the resource value.  I believe that the timestamps and
                   14581: versions are also returned.
                   14582: 
1.1236    raeburn  14583: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14584: supplemental content area. This routine caches the number of files for 
                   14585: 10 minutes.
                   14586: 
1.243     albertel 14587: =back
                   14588: 
                   14589: =head2 Course Modification
                   14590: 
                   14591: =over 4
1.191     harris41 14592: 
                   14593: =item *
                   14594: 
1.243     albertel 14595: writecoursepref($courseid,%prefs) : write preferences (environment
                   14596: database) for a course
1.191     harris41 14597: 
                   14598: =item *
                   14599: 
1.1011    raeburn  14600: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14601: 
                   14602: =item *
                   14603: 
1.1038    raeburn  14604: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14605: 
1.1167    droeschl 14606: =item *
                   14607: 
                   14608: is_course($courseid), is_course($cdom, $cnum)
                   14609: 
                   14610: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14611: two component version $cdom, $cnum. It checks if the specified course exists.
                   14612: 
                   14613: Returns:
                   14614:     undef if the course doesn't exist, otherwise
                   14615:     in scalar context the combined courseid.
                   14616:     in list context the two components of the course identifier, domain and 
                   14617:     courseid.    
                   14618: 
1.243     albertel 14619: =back
                   14620: 
                   14621: =head2 Resource Subroutines
                   14622: 
                   14623: =over 4
1.191     harris41 14624: 
                   14625: =item *
                   14626: 
1.243     albertel 14627: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14628: 
                   14629: =item *
                   14630: 
1.243     albertel 14631: repcopy($filename) : subscribes to the requested file, and attempts to
                   14632: replicate from the owning library server, Might return
1.607     raeburn  14633: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14634: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14635: resource. Expects the local filesystem pathname
                   14636: (/home/httpd/html/res/....)
                   14637: 
                   14638: =back
                   14639: 
                   14640: =head2 Resource Information
                   14641: 
                   14642: =over 4
1.191     harris41 14643: 
                   14644: =item *
                   14645: 
1.1228    raeburn  14646: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14647: and returns the value of a variety of different possible values,
                   14648: $varname should be a request string, and the other parameters can be
                   14649: used to specify who and what one is asking about. Ordinarily, $cid 
                   14650: does not need to be specified, as it is retrived from 
                   14651: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14652: within lonuserstate::loadmap() when initializing a course, before
                   14653: $env{'request.course.id'} has been set, so it needs to be provided
                   14654: in that one case.
1.243     albertel 14655: 
                   14656: Possible values for $varname are environment.lastname (or other item
                   14657: from the envirnment hash), user.name (or someother aspect about the
                   14658: user), resource.0.maxtries (or some other part and parameter of a
                   14659: resource)
1.204     albertel 14660: 
                   14661: =item *
                   14662: 
1.243     albertel 14663: directcondval($number) : get current value of a condition; reads from a state
                   14664: string
1.204     albertel 14665: 
                   14666: =item *
                   14667: 
1.243     albertel 14668: condval($condidx) : value of condition index based on state
1.204     albertel 14669: 
                   14670: =item *
                   14671: 
1.243     albertel 14672: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14673: resource's metadata, $what should be either a specific key, or either
                   14674: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14675: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14676: 
                   14677: this function automatically caches all requests
1.191     harris41 14678: 
                   14679: =item *
                   14680: 
1.243     albertel 14681: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14682: network of library servers; returns file handle of where SQL and regex results
                   14683: will be stored for query
1.191     harris41 14684: 
                   14685: =item *
                   14686: 
1.1282    raeburn  14687: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   14688: return symbolic list entry (all arguments optional). 
                   14689: 
                   14690: Args: filename is the filename (including path) for the file for which a symb 
                   14691: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   14692: to check access status if more than one resource was found in the bighash 
                   14693: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   14694: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   14695: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14696: cause possible symbs to be checked to determine if they are subject to content
                   14697: blocking, if so they will not be included as possible symbs; possibles is a
                   14698: ref to a hash, which, as a side effect, will be populated with all possible 
                   14699: symbs (content blocking not tested).
                   14700:  
1.243     albertel 14701: returns the data handle
1.191     harris41 14702: 
                   14703: =item *
                   14704: 
1.1190    raeburn  14705: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   14706: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14707: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  14708: on failure, user must be in a course, as it assumes the existence of
                   14709: the course initial hash, and uses $env('request.course.id'}.  The third
                   14710: arg is an optional reference to a scalar.  If this arg is passed in the 
                   14711: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14712: encrypted; otherwise it will be null.  
1.191     harris41 14713: 
                   14714: =item *
                   14715: 
1.243     albertel 14716: symbclean($symb) : removes versions numbers from a symb, returns the
                   14717: cleaned symb
1.191     harris41 14718: 
                   14719: =item *
                   14720: 
1.243     albertel 14721: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14722: course map, user must be in a course for it to work.
1.191     harris41 14723: 
                   14724: =item *
                   14725: 
1.243     albertel 14726: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14727: 
                   14728: =item *
                   14729: 
1.243     albertel 14730: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14731: a random seed, all arguments are optional, if they aren't sent it uses the
                   14732: environment to derive them. Note: if symb isn't sent and it can't get one
                   14733: from &symbread it will use the current time as its return value
1.191     harris41 14734: 
                   14735: =item *
                   14736: 
1.243     albertel 14737: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14738: unfakeable, receipt
1.191     harris41 14739: 
                   14740: =item *
                   14741: 
1.620     albertel 14742: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14743: 
                   14744: =item *
                   14745: 
1.243     albertel 14746: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14747: 
                   14748: =item *
                   14749: 
1.243     albertel 14750: 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 14751: 
                   14752: =item *
                   14753: 
1.243     albertel 14754: 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 14755: 
                   14756: =item *
                   14757: 
1.243     albertel 14758: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14759: 
                   14760: =item *
                   14761: 
1.243     albertel 14762: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14763: forcing spreadsheet to reevaluate the resource scores next time.
                   14764: 
1.1195    raeburn  14765: =item * 
                   14766: 
1.1196    raeburn  14767: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14768: when viewing in course context.
1.1195    raeburn  14769: 
1.1196    raeburn  14770:  input: six args -- filename (decluttered), course number, course domain,
                   14771:                     url, symb (if registered) and group (if this is a 
                   14772:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  14773: 
1.1196    raeburn  14774:  output: array of five scalars --
1.1195    raeburn  14775:          $cfile -- url for file editing if editable on current server
                   14776:          $home -- homeserver of resource (i.e., for author if published,
                   14777:                                           or course if uploaded.).
                   14778:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  14779:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   14780:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  14781: 
                   14782: =item *
                   14783: 
                   14784: is_course_upload($file,$cnum,$cdom)
                   14785: 
                   14786: Used in course context to determine if current file was uploaded to 
                   14787: the course (i.e., would be found in /userfiles/docs on the course's 
                   14788: homeserver.
                   14789: 
                   14790:   input: 3 args -- filename (decluttered), course number and course domain.
                   14791:   output: boolean -- 1 if file was uploaded.
                   14792: 
1.243     albertel 14793: =back
                   14794: 
                   14795: =head2 Storing/Retreiving Data
                   14796: 
                   14797: =over 4
1.191     harris41 14798: 
                   14799: =item *
                   14800: 
1.1269    raeburn  14801: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   14802: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14803: the remaining args aren't required and if they aren't passed or are '' they will
                   14804: be derived from the env (with the exception of $laststore, which is an 
                   14805: optional arg used when a user's submission is stored in grading).
                   14806: $laststore is $version=$timestamp, where $version is the most recent version
                   14807: number retrieved for the corresponding $symb in the $namespace db file, and
                   14808: $timestamp is the timestamp for that transaction (UNIX time).
                   14809: $laststore is currently only passed when cstore() is called by 
                   14810: structuretags::finalize_storage().
1.191     harris41 14811: 
                   14812: =item *
                   14813: 
1.1269    raeburn  14814: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   14815: but uses critical subroutine
1.191     harris41 14816: 
                   14817: =item *
                   14818: 
1.243     albertel 14819: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14820: all args are optional
1.191     harris41 14821: 
                   14822: =item *
                   14823: 
1.717     albertel 14824: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14825: dumps the complete (or key matching regexp) namespace into a hash
                   14826: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14827: normally &store()ed into
                   14828: 
                   14829: $range should be either an integer '100' (give me the first 100
                   14830:                                            matching records)
                   14831:               or be  two integers sperated by a - with no spaces
                   14832:                  '30-50' (give me the 30th through the 50th matching
                   14833:                           records)
                   14834: 
                   14835: 
                   14836: =item *
                   14837: 
1.1269    raeburn  14838: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14839: replaces a &store() version of data with a replacement set of data
                   14840: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  14841: reference. If $tolog is true, the transaction is logged in the courselog
                   14842: with an action=PUTSTORE.
1.717     albertel 14843: 
                   14844: =item *
                   14845: 
1.243     albertel 14846: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14847: works very similar to store/cstore, but all data is stored in a
                   14848: temporary location and can be reset using tmpreset, $storehash should
                   14849: be a hash reference, returns nothing on success
1.191     harris41 14850: 
                   14851: =item *
                   14852: 
1.243     albertel 14853: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14854: similar to restore, but all data is stored in a temporary location and
                   14855: can be reset using tmpreset. Returns a hash of values on success,
                   14856: error string otherwise.
1.191     harris41 14857: 
                   14858: =item *
                   14859: 
1.243     albertel 14860: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14861: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14862: 
                   14863: =item *
                   14864: 
1.243     albertel 14865: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14866: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14867: 
                   14868: =item *
                   14869: 
1.243     albertel 14870: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14871: namesp ($udom and $uname are optional)
1.191     harris41 14872: 
                   14873: =item *
                   14874: 
1.702     albertel 14875: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14876: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14877: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14878: 
1.702     albertel 14879: $range should be either an integer '100' (give me the first 100
                   14880:                                            matching records)
                   14881:               or be  two integers sperated by a - with no spaces
                   14882:                  '30-50' (give me the 30th through the 50th matching
                   14883:                           records)
1.449     matthew  14884: =item *
                   14885: 
                   14886: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14887: $store can be a scalar, an array reference, or if the amount to be 
                   14888: incremented is > 1, a hash reference.
                   14889: 
                   14890: ($udom and $uname are optional)
1.191     harris41 14891: 
                   14892: =item *
                   14893: 
1.243     albertel 14894: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14895: ($udom and $uname are optional)
1.191     harris41 14896: 
                   14897: =item *
                   14898: 
1.243     albertel 14899: cput($namespace,$storehash,$udom,$uname) : critical put
                   14900: ($udom and $uname are optional)
1.191     harris41 14901: 
                   14902: =item *
                   14903: 
1.748     albertel 14904: newput($namespace,$storehash,$udom,$uname) :
                   14905: 
                   14906: Attempts to store the items in the $storehash, but only if they don't
                   14907: currently exist, if this succeeds you can be certain that you have 
                   14908: successfully created a new key value pair in the $namespace db.
                   14909: 
                   14910: 
                   14911: Args:
                   14912:  $namespace: name of database to store values to
                   14913:  $storehash: hashref to store to the db
                   14914:  $udom: (optional) domain of user containing the db
                   14915:  $uname: (optional) name of user caontaining the db
                   14916: 
                   14917: Returns:
                   14918:  'ok' -> succeeded in storing all keys of $storehash
                   14919:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14920:                         least <key> already existed in the db (other
                   14921:                         requested keys may also already exist)
1.967     bisitz   14922:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14923:  'con_lost' -> unable to contact request server
                   14924:  'refused' -> action was not allowed by remote machine
                   14925: 
                   14926: 
                   14927: =item *
                   14928: 
1.243     albertel 14929: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14930: reference filled in from namesp (encrypts the return communication)
                   14931: ($udom and $uname are optional)
1.191     harris41 14932: 
                   14933: =item *
                   14934: 
1.243     albertel 14935: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14936: critical subroutine
                   14937: 
1.806     raeburn  14938: =item *
                   14939: 
1.860     raeburn  14940: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14941: array reference filled in from namespace found in domain level on either
                   14942: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14943: 
                   14944: =item *
                   14945: 
1.860     raeburn  14946: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14947: domain level either on specified domain server ($uhome) or primary domain 
                   14948: server ($udom and $uhome are optional)
1.806     raeburn  14949: 
1.943     raeburn  14950: =item * 
                   14951: 
1.1240    raeburn  14952: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   14953: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14954: the target domain.
                   14955: 
                   14956: May also include additional key => value pairs for the following groups:
                   14957: 
                   14958: =over
                   14959: 
                   14960: =item
                   14961: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14962: 
                   14963: =over
                   14964: 
                   14965: =item defaultquota, authorquota
                   14966: 
                   14967: =back
                   14968: 
                   14969: =item
                   14970: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14971: portfolio for users).
                   14972: 
                   14973: =over
                   14974: 
                   14975: =item
                   14976: aboutme, blog, webdav, portfolio
                   14977: 
                   14978: =back
                   14979: 
                   14980: =item
                   14981: requestcourses: ability to request courses, and how requests are processed.
                   14982: 
                   14983: =over
                   14984: 
                   14985: =item
1.1305    raeburn  14986: official, unofficial, community, textbook, placement
1.1240    raeburn  14987: 
                   14988: =back
                   14989: 
                   14990: =item
                   14991: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14992: 
                   14993: =over
                   14994: 
                   14995: =item
1.1256    raeburn  14996: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  14997: 
                   14998: =back
                   14999: 
                   15000: =item
                   15001: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15002: for course's uploaded content.
                   15003: 
                   15004: =over
                   15005: 
                   15006: =item
1.1246    raeburn  15007: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  15008: communityquota, textbookquota, placementquota
1.1240    raeburn  15009: 
                   15010: =back
                   15011: 
                   15012: =item
                   15013: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15014: on your servers.
                   15015: 
                   15016: =over
                   15017: 
                   15018: =item 
                   15019: remotesessions, hostedsessions
                   15020: 
                   15021: =back
                   15022: 
                   15023: =back
                   15024: 
                   15025: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15026: utility to create a configuration.db file on a domain's primary library server 
                   15027: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15028: -- corresponding values are authentication type (internal, krb4, krb5,
                   15029: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   15030: will be available. Values are retrieved from cache (if current), unless the
                   15031: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15032: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15033: 
                   15034: Typical usage:
1.943     raeburn  15035: 
1.1240    raeburn  15036: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15037: 
1.243     albertel 15038: =back
                   15039: 
                   15040: =head2 Network Status Functions
                   15041: 
                   15042: =over 4
1.191     harris41 15043: 
                   15044: =item *
                   15045: 
1.1137    raeburn  15046: dirlist() : return directory list based on URI (first arg).
                   15047: 
                   15048: Inputs: 1 required, 5 optional.
                   15049: 
                   15050: =over
                   15051: 
                   15052: =item 
                   15053: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15054: 
                   15055: =item
                   15056: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15057: 
                   15058: =item
                   15059: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15060: 
                   15061: =item
                   15062: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15063: 
                   15064: =item
                   15065: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15066: 
                   15067: =item 
                   15068: $alternateRoot - path to prepend in place of path from $uri.
                   15069: 
                   15070: =back
                   15071: 
                   15072: Returns: Array of up to two items.
                   15073: 
                   15074: =over
                   15075: 
                   15076: a reference to an array of files/subdirectories
                   15077: 
                   15078: =over
                   15079: 
                   15080: Each element in the array of files/subdirectories is a & separated list of
                   15081: item name and the result of running stat on the item.  If dirlist was requested
                   15082: for a file instead of a directory, the item name will be ''. For a directory 
                   15083: listing, if the item is a metadata file, the element will end &N&M 
                   15084: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15085: default copyright set (1).  
                   15086: 
                   15087: =back
                   15088: 
                   15089: a scalar containing error condition (if encountered).
                   15090: 
                   15091: =over
                   15092: 
                   15093: =item 
                   15094: no_host (no homeserver identified for $username:$domain).
                   15095: 
                   15096: =item 
                   15097: no_such_host (server contacted for listing not identified as valid host).
                   15098: 
                   15099: =item 
                   15100: con_lost (connection to remote server failed).
                   15101: 
                   15102: =item 
                   15103: refused (invalid $username:$domain received on lond side).
                   15104: 
                   15105: =item 
                   15106: no_such_dir (directory at specified path on lond side does not exist). 
                   15107: 
                   15108: =item 
                   15109: empty (directory at specified path on lond side is empty).
                   15110: 
                   15111: =over
                   15112: 
                   15113: This is currently not encountered because the &ls3, &ls2, 
                   15114: &ls (_handler) routines on the lond side do not filter out
                   15115: . and .. from a directory listing. 
                   15116: 
                   15117: =back
                   15118: 
                   15119: =back
                   15120: 
                   15121: =back
1.191     harris41 15122: 
                   15123: =item *
                   15124: 
1.243     albertel 15125: spareserver() : find server with least workload from spare.tab
                   15126: 
1.986     foxr     15127: 
                   15128: =item *
                   15129: 
                   15130: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15131: if there is no corresponding loncapa host.
                   15132: 
1.243     albertel 15133: =back
                   15134: 
1.986     foxr     15135: 
1.243     albertel 15136: =head2 Apache Request
                   15137: 
                   15138: =over 4
1.191     harris41 15139: 
                   15140: =item *
                   15141: 
1.243     albertel 15142: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15143: localhost, posts hash
                   15144: 
                   15145: =back
                   15146: 
                   15147: =head2 Data to String to Data
                   15148: 
                   15149: =over 4
1.191     harris41 15150: 
                   15151: =item *
                   15152: 
1.243     albertel 15153: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15154: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15155: 
                   15156: =item *
                   15157: 
1.243     albertel 15158: hashref2str($hashref) : convert a hashref into a string complete with
                   15159: escaping and '=' and '&' separators, supports elements that are
                   15160: arrayrefs and hashrefs
1.191     harris41 15161: 
                   15162: =item *
                   15163: 
1.243     albertel 15164: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15165: with escaping and '&' separators, supports elements that are arrayrefs
                   15166: and hashrefs
1.191     harris41 15167: 
                   15168: =item *
                   15169: 
1.243     albertel 15170: str2hash($string) : convert string to hash using unescaping and
                   15171: splitting on '=' and '&', supports elements that are arrayrefs and
                   15172: hashrefs
1.191     harris41 15173: 
                   15174: =item *
                   15175: 
1.243     albertel 15176: str2array($string) : convert string to hash using unescaping and
                   15177: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15178: 
                   15179: =back
                   15180: 
                   15181: =head2 Logging Routines
                   15182: 
                   15183: 
                   15184: These routines allow one to make log messages in the lonnet.log and
                   15185: lonnet.perm logfiles.
1.191     harris41 15186: 
1.1119    foxr     15187: =over 4
                   15188: 
1.191     harris41 15189: =item *
                   15190: 
1.243     albertel 15191: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15192: 
                   15193: =item *
                   15194: 
1.243     albertel 15195: logthis() : append message to the normal lonnet.log file, it gets
                   15196: preiodically rolled over and deleted.
1.191     harris41 15197: 
                   15198: =item *
                   15199: 
1.243     albertel 15200: logperm() : append a permanent message to lonnet.perm.log, this log
                   15201: file never gets deleted by any automated portion of the system, only
                   15202: messages of critical importance should go in here.
                   15203: 
1.1119    foxr     15204: 
1.243     albertel 15205: =back
                   15206: 
                   15207: =head2 General File Helper Routines
                   15208: 
                   15209: =over 4
1.191     harris41 15210: 
                   15211: =item *
                   15212: 
1.481     raeburn  15213: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15214: (a) files in /uploaded
                   15215:   (i) If a local copy of the file exists - 
                   15216:       compares modification date of local copy with last-modified date for 
                   15217:       definitive version stored on home server for course. If local copy is 
                   15218:       stale, requests a new version from the home server and stores it. 
                   15219:       If the original has been removed from the home server, then local copy 
                   15220:       is unlinked.
                   15221:   (ii) If local copy does not exist -
                   15222:       requests the file from the home server and stores it. 
                   15223:   
                   15224:   If $caller is 'uploadrep':  
                   15225:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15226:     for request for files originally uploaded via DOCS. 
                   15227:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15228:   
                   15229:   Otherwise:
                   15230:      This indicates a call from the content generation phase of the request.
                   15231:      -  returns the entire contents of the file or -1.
                   15232:      
                   15233: (b) files in /res
                   15234:    - returns the entire contents of a file or -1; 
                   15235:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15236: 
1.712     albertel 15237: 
                   15238: =item *
                   15239: 
                   15240: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15241:                   reference
                   15242: 
                   15243: returns either a stat() list of data about the file or an empty list
                   15244: if the file doesn't exist or couldn't find out about it (connection
                   15245: problems or user unknown)
                   15246: 
1.191     harris41 15247: =item *
                   15248: 
1.243     albertel 15249: filelocation($dir,$file) : returns file system location of a file
                   15250: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15251: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15252: and a file of ../bob will become /a/bob)
1.191     harris41 15253: 
                   15254: =item *
                   15255: 
                   15256: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15257: filelocation except for hrefs
                   15258: 
                   15259: =item *
                   15260: 
1.1261    raeburn  15261: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15262: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15263: 
1.243     albertel 15264: =back
                   15265: 
1.608     albertel 15266: =head2 Usererfile file routines (/uploaded*)
                   15267: 
                   15268: =over 4
                   15269: 
                   15270: =item *
                   15271: 
                   15272: userfileupload(): main rotine for putting a file in a user or course's
                   15273:                   filespace, arguments are,
                   15274: 
1.620     albertel 15275:  formname - required - this is the name of the element in $env where the
1.608     albertel 15276:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15277:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15278:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15279:  context - if coursedoc, store the file in the course of the active role
                   15280:              of the current user; 
                   15281:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15282:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15283:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15284:          if undefined, it will be placed in "unknown"
                   15285: 
                   15286:  (This routine calls clean_filename() to remove any dangerous
                   15287:  characters from the filename, and then calls finuserfileupload() to
                   15288:  complete the transaction)
                   15289: 
                   15290:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15291:  and /adm/notfound.html if unsuccessful
                   15292: 
                   15293: =item *
                   15294: 
                   15295: clean_filename(): routine for cleaing a filename up for storage in
                   15296:                  userfile space, argument is:
                   15297: 
                   15298:  filename - proposed filename
                   15299: 
                   15300: returns: the new clean filename
                   15301: 
                   15302: =item *
                   15303: 
1.1090    raeburn  15304: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15305: userspace, probably shouldn't be called directly
                   15306: 
                   15307:   docuname: username or courseid of destination for the file
                   15308:   docudom: domain of user/course of destination for the file
                   15309:   formname: same as for userfileupload()
1.1090    raeburn  15310:   fname: filename (including subdirectories) for the file
                   15311:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   15312:   allfiles: reference to hash used to store objects found by parser
                   15313:   codebase: reference to hash used for codebases of java objects found by parser
                   15314:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15315:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15316:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15317:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15318:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15319:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15320:   mimetype: reference to scalar to accommodate mime type determined
                   15321:             from File::MMagic if $parser = parse.
1.608     albertel 15322: 
                   15323:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15324:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15325:  was 'overwrite').
                   15326:  
1.608     albertel 15327: 
                   15328: =item *
                   15329: 
                   15330: renameuserfile(): renames an existing userfile to a new name
                   15331: 
                   15332:   Args:
                   15333:    docuname: username or courseid of destination for the file
                   15334:    docudom: domain of user/course of destination for the file
                   15335:    old: current file name (including any subdirs under userfiles)
                   15336:    new: desired file name (including any subdirs under userfiles)
                   15337: 
                   15338: =item *
                   15339: 
                   15340: mkdiruserfile(): creates a directory is a userfiles dir
                   15341: 
                   15342:   Args:
                   15343:    docuname: username or courseid of destination for the file
                   15344:    docudom: domain of user/course of destination for the file
                   15345:    dir: dir to create (including any subdirs under userfiles)
                   15346: 
                   15347: =item *
                   15348: 
                   15349: removeuserfile(): removes a file that exists in userfiles
                   15350: 
                   15351:   Args:
                   15352:    docuname: username or courseid of destination for the file
                   15353:    docudom: domain of user/course of destination for the file
                   15354:    fname: filname to delete (including any subdirs under userfiles)
                   15355: 
                   15356: =item *
                   15357: 
                   15358: removeuploadedurl(): convience function for removeuserfile()
                   15359: 
                   15360:   Args:
                   15361:    url:  a full /uploaded/... url to delete
                   15362: 
1.747     albertel 15363: =item * 
                   15364: 
                   15365: get_portfile_permissions():
                   15366:   Args:
                   15367:     domain: domain of user or course contain the portfolio files
                   15368:     user: name of user or num of course contain the portfolio files
                   15369:   Returns:
                   15370:     hashref of a dump of the proper file_permissions.db
                   15371:    
                   15372: 
                   15373: =item * 
                   15374: 
                   15375: get_access_controls():
                   15376: 
                   15377: Args:
                   15378:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15379:   group: (optional) the group you want the files associated with
                   15380:   file: (optional) the file you want access info on
                   15381: 
                   15382: Returns:
1.749     raeburn  15383:     a hash (keys are file names) of hashes containing
                   15384:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15385:         values are XML containing access control settings (see below) 
1.747     albertel 15386: 
                   15387: Internal notes:
                   15388: 
1.749     raeburn  15389:  access controls are stored in file_permissions.db as key=value pairs.
                   15390:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15391:         where scope -> public,guest,course,group,domains or users.
                   15392:               end -> UNIX time for end of access (0 -> no end date)
                   15393:               start -> UNIX time for start of access
                   15394: 
                   15395:     value -> XML description of access control
                   15396:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15397:             <start></start>
                   15398:             <end></end>
                   15399: 
                   15400:             <password></password>  for scope type = guest
                   15401: 
                   15402:             <domain></domain>     for scope type = course or group
                   15403:             <number></number>
                   15404:             <roles id="">
                   15405:              <role></role>
                   15406:              <access></access>
                   15407:              <section></section>
                   15408:              <group></group>
                   15409:             </roles>
                   15410: 
                   15411:             <dom></dom>         for scope type = domains
                   15412: 
                   15413:             <users>             for scope type = users
                   15414:              <user>
                   15415:               <uname></uname>
                   15416:               <udom></udom>
                   15417:              </user>
                   15418:             </users>
                   15419:            </scope> 
                   15420:               
                   15421:  Access data is also aggregated for each file in an additional key=value pair:
                   15422:  key -> path to file/file_name\0accesscontrol 
                   15423:  value -> reference to hash
                   15424:           hash contains key = value pairs
                   15425:           where key = uniqueID:scope_end_start
                   15426:                 value = UNIX time record was last updated
                   15427: 
                   15428:           Used to improve speed of look-ups of access controls for each file.  
                   15429:  
                   15430:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15431: 
1.1198    raeburn  15432: =item *
                   15433: 
1.749     raeburn  15434: modify_access_controls():
                   15435: 
                   15436: Modifies access controls for a portfolio file
                   15437: Args
                   15438: 1. file name
                   15439: 2. reference to hash of required changes,
                   15440: 3. domain
                   15441: 4. username
                   15442:   where domain,username are the domain of the portfolio owner 
                   15443:   (either a user or a course) 
                   15444: 
                   15445: Returns:
                   15446: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15447: 2. result of deletions ('ok' or 'error', with error message).
                   15448: 3. reference to hash of any new or updated access controls.
                   15449: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15450:    key = integer (inbound ID)
1.1198    raeburn  15451:    value = uniqueID
                   15452: 
                   15453: =item *
                   15454: 
                   15455: get_timebased_id():
                   15456: 
                   15457: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   15458: course via the Course Editor (e.g., folders, composite pages, 
                   15459: group bulletin boards).
                   15460: 
                   15461: Args: (first three required; six others optional)
                   15462: 
                   15463: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15464:    docssequence, or name of group
                   15465: 
                   15466: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15467:    e.g., num, boardids
                   15468: 
                   15469: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   15470:    file will be named nohist_namespace.db
                   15471: 
                   15472: 4. cdom: domain of course; default is current course domain from %env
                   15473: 
                   15474: 5. cnum: course number; default is current course number from %env
                   15475: 
                   15476: 6. idtype: set to concat if an additional digit is to be appended to the 
                   15477:    unix timestamp to form the suffix, if the plain timestamp is already
                   15478:    in use.  Default is to not do this, but simply increment the unix 
                   15479:    timestamp by 1 until a unique key is obtained.
                   15480: 
                   15481: 7. who: holder of locking key; defaults to user:domain for user.
                   15482: 
                   15483: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   15484:    retrying); default is 3.
                   15485: 
                   15486: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   15487: 
                   15488: Returns:
                   15489: 
                   15490: 1. suffix obtained (numeric)
                   15491: 
                   15492: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15493: 
                   15494: 3. error: contains (localized) error message if an error occurred.
                   15495: 
1.747     albertel 15496: 
1.608     albertel 15497: =back
                   15498: 
1.243     albertel 15499: =head2 HTTP Helper Routines
                   15500: 
                   15501: =over 4
                   15502: 
1.191     harris41 15503: =item *
                   15504: 
                   15505: escape() : unpack non-word characters into CGI-compatible hex codes
                   15506: 
                   15507: =item *
                   15508: 
                   15509: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15510: 
1.243     albertel 15511: =back
                   15512: 
                   15513: =head1 PRIVATE SUBROUTINES
                   15514: 
                   15515: =head2 Underlying communication routines (Shouldn't call)
                   15516: 
                   15517: =over 4
                   15518: 
                   15519: =item *
                   15520: 
                   15521: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15522: 
                   15523: =item *
                   15524: 
                   15525: reply() : uses subreply to send a message to remote machine, logs all failures
                   15526: 
                   15527: =item *
                   15528: 
                   15529: critical() : passes a critical message to another server; if cannot
                   15530: get through then place message in connection buffer directory and
                   15531: returns con_delayed, if incapable of saving message, returns
                   15532: con_failed
                   15533: 
                   15534: =item *
                   15535: 
                   15536: reconlonc() : tries to reconnect lonc client processes.
                   15537: 
                   15538: =back
                   15539: 
                   15540: =head2 Resource Access Logging
                   15541: 
                   15542: =over 4
                   15543: 
                   15544: =item *
                   15545: 
                   15546: flushcourselogs() : flush (save) buffer logs and access logs
                   15547: 
                   15548: =item *
                   15549: 
                   15550: courselog($what) : save message for course in hash
                   15551: 
                   15552: =item *
                   15553: 
                   15554: courseacclog($what) : save message for course using &courselog().  Perform
                   15555: special processing for specific resource types (problems, exams, quizzes, etc).
                   15556: 
1.191     harris41 15557: =item *
                   15558: 
                   15559: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15560: as a PerlChildExitHandler
1.243     albertel 15561: 
                   15562: =back
                   15563: 
                   15564: =head2 Other
                   15565: 
                   15566: =over 4
                   15567: 
                   15568: =item *
                   15569: 
                   15570: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15571: 
                   15572: =back
                   15573: 
                   15574: =cut
1.877     foxr     15575: 

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